an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions
HTML agent-harnessagent-orchestrationagentsai-agentsautonomous-agentsclaude-codecodexcoding-agentsdesktop-appdeveloper-toolselectrongemini-cliharnessharness-engineeringlocal-firstmemorymulti-agentopencodeorchestrationtypescript
feat(triggers): one home for everything that starts work without you
Chaitanya Giri9f441257f145
diff --git a/README.md b/README.mdindex 243d0e80..f0e5c237 100644--- a/README.md+++ b/README.md@@ -247,7 +247,7 @@ src/App.tsx top-level layout + wiringdesign/ tokens.css / tokens.ts / global.css (design source of truth)components/ PixelPanel, AgentDetailPanel, CommandBar, ApprovalsPanel, MemoryPanel, …- CommandCenterPanel, Michael's control surface (Terminal/Floor/Memory/Activity/Tasks/Schedules/Handbook tabs)+ CommandCenterPanel, Michael's control surface (Terminal/Floor/Memory/Activity/Tasks/Triggers/Handbook tabs)ToolWaterfall, per-agent tool-span waterfall for the observability viewTasksKanban, dependency-aware kanban board (Tasks tab)ThreadsPanel, hive message conversation viewer (Messages tab)diff --git a/blog/src/posts/command-center-guide.md b/blog/src/posts/command-center-guide.mdindex 677489c2..e8e626f9 100644--- a/blog/src/posts/command-center-guide.md+++ b/blog/src/posts/command-center-guide.md@@ -13,7 +13,7 @@ author:initials: CGfaq:- q: "What is the Command Center in Munder Difflin?"- a: "It's Michael's control surface — the management view of the whole hive. It has tabs for the orchestrator Terminal, the Floor (roster, dispatch, per-agent model selector, live fleet monitoring), Memory (semantic search plus a memory graph), Activity (event log, board, real token telemetry, observability, and a CI watcher), Tasks (a dependency-aware kanban board), and Schedules (recurring missions with last/next-fired times)."+ a: "It's Michael's control surface — the management view of the whole hive. It has tabs for the orchestrator Terminal, the Floor (roster, dispatch, per-agent model selector, live fleet monitoring), Memory (semantic search plus a memory graph), Activity (event log, board, real token telemetry, observability, and a CI watcher), Tasks (a dependency-aware kanban board), and Triggers (everything that starts work without you — schedules with last/next-fired times, context, webhooks, and organization)."- q: "How does the task kanban work?"a: "The Tasks tab is a dependency-aware kanban board. You assign tasks to agents and track them across todo, doing, blocked, and done. Because tasks can declare dependencies, downstream work waits until its prerequisites finish, so a chain of related tasks starts in the right order without you babysitting the handoffs."- q: "How do per-agent budgets and cost tracking work?"@@ -26,7 +26,7 @@ faq:a: "Yes. You can ingest open issues from any registered repo via the gh CLI and assign them to agents with one click, and a CI status watcher shows live pass/fail/in-progress state for GitHub Actions runs in the Activity tab. Work flows in from GitHub, gets tracked on the kanban, and its CI result lands back in the same view."----<div class="callout tldr"><span class="ic">TL;DR</span><p>The office floor is fun to watch, but you don't manage a team by staring at desks. Munder Difflin's <strong>Command Center</strong> is the management view: a <strong>dependency-aware task kanban</strong>, <strong>live fleet monitoring with per-agent token budgets</strong>, <strong>real cost telemetry</strong> backed by a durable ledger, <strong>OpenTelemetry observability</strong> with a per-agent tool-span waterfall, plus GitHub issue ingestion, a CI watcher, and a Schedules tab. Rule of thumb: <strong>watch the floor for one agent right now, watch the board for the whole fleet over time</strong>.</p></div>+<div class="callout tldr"><span class="ic">TL;DR</span><p>The office floor is fun to watch, but you don't manage a team by staring at desks. Munder Difflin's <strong>Command Center</strong> is the management view: a <strong>dependency-aware task kanban</strong>, <strong>live fleet monitoring with per-agent token budgets</strong>, <strong>real cost telemetry</strong> backed by a durable ledger, <strong>OpenTelemetry observability</strong> with a per-agent tool-span waterfall, plus GitHub issue ingestion, a CI watcher, and a Triggers tab. Rule of thumb: <strong>watch the floor for one agent right now, watch the board for the whole fleet over time</strong>.</p></div><video controls preload="none" playsinline poster="/media/demo/features-poster.jpg" style="width:100%; border-radius:12px; margin:12px 0 24px;"><source src="/media/demo/features.mp4" type="video/mp4" />@@ -45,7 +45,7 @@ Six tabs, one control surface:- **Memory** — semantic search over the shared memory palace, plain text search, and a memory graph.- **Activity** — the append-only event log, the blackboard, real token telemetry, the observability view, and a CI watcher.- **Tasks** — the kanban board.-- **Schedules** — recurring missions and the adaptive heartbeat, with last/next-fired times.+- **Triggers** — everything that starts work without you, grouped by kind: schedules (recurring missions and the adaptive heartbeat, with last/next-fired times), context, webhooks, and organization.You could run the hive from the floor alone. But once you have more than two or three agents, the Command Center is where the actual decisions happen.@@ -73,9 +73,9 @@ This is the part that makes a 24/7 fleet safe to leave running.**Observability.** Also in Activity: a live **OpenTelemetry collector** with per-model cost attribution, a fleet grid, and a **per-agent tool-span waterfall** — the "what exactly is this agent doing, step by step, and what does each step cost" view. It's the same discipline we covered in [observability for agent fleets](/blog/observability-for-agent-fleets/), built into the harness instead of bolted on.-## Schedules: the board's fourth dimension+## Triggers: the board's fourth dimension-The kanban answers "what's in flight." The **Schedules tab** answers "what happens next without me." Recurring missions carry a label, an interval, a target agent, and a body, and the tab shows last-fired and next-fired times, so drift is visible. A scheduler **heartbeat** re-engages the floor when it goes quiet. Together with the board, it turns the hive from something you drive into something you supervise — the full pattern is in [scheduling autonomous agent missions](/blog/scheduling-autonomous-agent-missions/).+The kanban answers "what's in flight." The **Triggers tab** answers "what happens next without me" — every way the hive wakes up when you aren't typing. **Schedules** are the first and oldest of them: recurring missions carry a label, an interval, a target agent, and a body, and the tab shows last-fired and next-fired times, so drift is visible. A scheduler **heartbeat** re-engages the floor when it goes quiet. Together with the board, it turns the hive from something you drive into something you supervise — the full pattern is in [scheduling autonomous agent missions](/blog/scheduling-autonomous-agent-missions/).## Floor or board? A simple rulediff --git a/blog/src/posts/how-the-god-orchestrator-works.md b/blog/src/posts/how-the-god-orchestrator-works.mdindex a39bf677..b982e6c2 100644--- a/blog/src/posts/how-the-god-orchestrator-works.md+++ b/blog/src/posts/how-the-god-orchestrator-works.md@@ -165,9 +165,10 @@ single-writer and single-committer principles the orchestrator depends on.## The orchestrator's interfaceIn v0.1.6, Michael's interface expands significantly. His sidebar becomes a full Command Center: a-Tasks tab gives him a kanban board to track work across agents with dependency links; a Schedules tab-lets you pre-program recurring directives so the floor stays active between your check-ins; an Activity-tab shows real token and dollar cost per agent drawn from transcript files; and a GitHub Issues section+Tasks tab gives him a kanban board to track work across agents with dependency links; a Triggers tab+collects everything that wakes the hive without you — schedules first among them — so you can+pre-program recurring directives and the floor stays active between your check-ins; an Activity tab+shows real token and dollar cost per agent drawn from transcript files; and a GitHub Issues sectionin the Floor tab lets him receive and route repo issues directly. The orchestrator is the same agent —the harness simply gives him better tools.diff --git a/blog/src/posts/how-to-install-and-use-munder-difflin.md b/blog/src/posts/how-to-install-and-use-munder-difflin.mdindex 3f203789..5af69886 100644--- a/blog/src/posts/how-to-install-and-use-munder-difflin.md+++ b/blog/src/posts/how-to-install-and-use-munder-difflin.md@@ -207,10 +207,10 @@ with six tabs:directly from your Claude Code transcript files).- **Tasks** — a dependency-aware kanban board. Add tasks with assignees, priorities, and `dependsOn`links; Michael and his team track status here.-- **Schedules** — recurring missions. Set a label, interval (1h / 6h / 24h / weekly), and a directive+- **Triggers** — every way the office wakes itself, starting with recurring missions. Set a label, interval (1h / 6h / 24h / weekly), and a directivebody; the harness dispatches it to the target agent automatically, no human needed.-For long-running floors, the Schedules tab is the most powerful: set a '30-minute floor check' mission+For long-running floors, the Triggers tab is the most powerful: set a '30-minute floor check' missionpointing at Michael with a directive like 'Are all agents making progress? Re-engage anyone idle.' —and the harness keeps the team moving even when you're away.diff --git a/blog/src/posts/your-first-hour-with-munder-difflin.md b/blog/src/posts/your-first-hour-with-munder-difflin.mdindex 1f2d90fd..86127294 100644--- a/blog/src/posts/your-first-hour-with-munder-difflin.md+++ b/blog/src/posts/your-first-hour-with-munder-difflin.md@@ -23,7 +23,7 @@ faq:- q: "How do I review what an agent actually changed?"a: "Open the built-in Monaco IDE from the title-bar IDE button. Its git CHANGES rail lists every modified file, and clicking one opens a read-only side-by-side diff against HEAD — the VS Code editor engine, fully self-hosted, with all filesystem and git access brokered through the main process. There's also a per-agent git tab with status, log, and commit graph."- q: "Can Munder Difflin keep working after I walk away?"- a: "Yes — that's the point. The Schedules tab in the Command Center holds recurring missions with a label, interval, target agent, and body, plus a heartbeat that re-engages the floor when it goes quiet. It's local-first, so the office runs 24/7 on hardware you already own."+ a: "Yes — that's the point. The Triggers tab in the Command Center holds recurring missions with a label, interval, target agent, and body, plus a heartbeat that re-engages the floor when it goes quiet. It's local-first, so the office runs 24/7 on hardware you already own."---<div class="callout tldr"><span class="ic">TL;DR</span><p><strong>You can go from zero to a running AI office in one hour.</strong> Minute 0: install. Minute 5: the <strong>onboarding wizard</strong> (harness home, repos, auto-mode, orchestrator engine). Minute 10: your <strong>first brief to Michael</strong>, the GOD orchestrator. Minute 20: watch avatars work the floor and open a real desk terminal. Minute 40: your <strong>first approval</strong> and a side-by-side diff in the built-in <strong>Monaco IDE</strong>. Minute 60: set a <strong>schedule</strong> and walk away — the office keeps working.</p></div>@@ -73,7 +73,7 @@ Before you click approve, look at the work. Hit the title-bar **IDE** button and## Minute 60 — Leave it running-The last move of the hour is the one that changes your relationship with the tool: schedule something. The Command Center's **Schedules** tab takes a label, an interval, a target agent, and a mission body — "every morning, triage new GitHub issues," say — and a heartbeat re-engages the floor if it goes quiet. Last-fired and next-fired times are right there in the tab.+The last move of the hour is the one that changes your relationship with the tool: schedule something. The Command Center's **Triggers** tab takes a label, an interval, a target agent, and a mission body — "every morning, triage new GitHub issues," say — and a heartbeat re-engages the floor if it goes quiet. Last-fired and next-fired times are right there in the tab.Close the laptop. It's local-first, so tomorrow the office is exactly where you left it — probably with mail in your queue. For patterns on what's worth automating, see [scheduling autonomous agent missions](/blog/scheduling-autonomous-agent-missions/).diff --git a/src/main/config.ts b/src/main/config.tsindex 43116a8b..78e07041 100644--- a/src/main/config.ts+++ b/src/main/config.ts@@ -12,6 +12,15 @@ import {import { defaultMcpDefaults } from '../shared/mcpCatalog';import { expandTilde } from './fs';import type { IntegrationRecord } from '../shared/integrations';+import {+ DEFAULT_CONTEXT_TRIGGER,+ DEFAULT_ORG_TRIGGER,+ DEFAULT_TRIGGER_MODE,+ DEFAULT_WEBHOOK_SCHEMA,+ type ContextTriggerConfig,+ type OrgTriggerConfig,+ type WebhookTrigger+} from '../shared/triggers';/** A recurring auto-dispatched mission fired on an interval by the scheduler. */export interface ScheduledMission {@@ -21,10 +30,15 @@ export interface ScheduledMission {to: string;body: string;enabled: boolean;- /** When true, the scheduler asks the renderer to `/compact` live terminals when- * this mission fires — but only agents whose context has filled past a- * threshold (30% for ~250k windows, 20% for ~1M windows) are compacted, so- * small/idle sessions are left alone instead of compacting on every tick. */+ /** When true, the scheduler asks the renderer to compact live terminals when+ * this mission fires — but only agents whose context has filled past the bar+ * in `contextTrigger.compact` (60% by default, 40% on ~1M-token windows), so+ * small/idle sessions are left alone instead of compacting on every tick.+ *+ * This gate used to be described here but was never actually implemented: every+ * live agent was compacted on every tick. It is real now, and the bars live in+ * `ContextTriggerConfig` where the operator can edit them, so do not restate+ * the numbers anywhere else — they will drift. */autoCompact?: boolean;lastFiredAt?: number;/** Mission flavor. Absent ⇒ 'dispatch' (the classic interval-dispatch mission,@@ -97,7 +111,11 @@ export const HEARTBEAT_MISSION: ScheduledMission = {export const COMPACT_MAINTENANCE_MISSION: ScheduledMission = {id: 'compact-maintenance',label: 'Auto-compact (maintenance)',- intervalMs: 3_600_000,+ // 2h, matching DEFAULT_CONTEXT_TRIGGER.compact.everyMs. The two cadences must+ // agree: this mission is the schedule half of the same behaviour the context+ // trigger now owns, and a 1h seed here would keep interrupting agents on the+ // old rhythm no matter what the trigger says.+ intervalMs: 7_200_000,to: '',body: '',enabled: false,@@ -105,6 +123,11 @@ export const COMPACT_MAINTENANCE_MISSION: ScheduledMission = {kind: 'compact'};+/** The 1h cadence `compact-maintenance` was seeded with before Triggers doubled+ * it. `migrateTriggersV1` bumps only missions still sitting on this EXACT value,+ * so an interval the user tuned by hand is left exactly where they put it. */+const LEGACY_COMPACT_MAINTENANCE_INTERVAL_MS = 3_600_000;+/** Circuit-breaker thresholds (Lane A #6.6b). The breaker runs inside the* heartbeat beat, so it only ticks when the heartbeat is enabled. Trip* conditions are behavioral by default; `costCapUsd` is the only $-based one and@@ -316,15 +339,40 @@ export interface HarnessConfig {* tunes this in Settings → Realtime Michael. */realtimeIdleDisconnectMs?: number;- // ─── Generic inbound webhook + status API ──────────────────────────────────- /** Master toggle for the generic webhook HTTP API (POST → work, GET → status). */+ // ─── Generic inbound webhook + status API (LEGACY, single-endpoint) ─────────+ // Superseded by `webhookTriggers`, which allows many endpoints over one server+ // and one tunnel. These three are kept because they are the MIGRATION SOURCE+ // (`migrateTriggersV1` folds them into a `WebhookTrigger`) and because the main+ // process still reads them until the server is rewired onto the new list.+ // Nothing new should be written here.+ /** @deprecated Use `webhookTriggers[].enabled`. */webhookEnabled?: boolean;/** App-generated shared secret callers echo in `x-md-webhook-secret`. Never- * logged, and never forwarded into the routed message/card/response. */+ * logged, and never forwarded into the routed message/card/response.+ * @deprecated Use `webhookTriggers[].secret` (one secret per endpoint, so+ * revoking one caller never disturbs the others). */webhookSecret?: string;- /** Local HTTP port the generic webhook server binds to (default 3849). */+ /** Local HTTP port the generic webhook server binds to (default 3849).+ * @deprecated The port is a property of the shared server, not of any one+ * trigger; `webhookTriggers` are multiplexed over it by id. */webhookPort?: number;+ // ─── Triggers (src/shared/triggers.ts owns every type here) ────────────────+ /** Auto-compaction / auto-clearing of agent terminal context. Both halves ship+ * in DEFAULT_CONTEXT_TRIGGER; `readConfig` deep-fills them, because the+ * top-level merge below is one level deep and a half-written sub-object would+ * otherwise reach consumers with `undefined` thresholds. */+ contextTrigger?: ContextTriggerConfig;+ /** Inbound HTTP endpoints, one entry per caller. Replaces the legacy single+ * webhook above; several coexist on one port, told apart by `id` in the path. */+ webhookTriggers?: WebhookTrigger[];+ /** Peer messaging between teammates' clone nodes. Persistence + UI only today —+ * no transport service reads `apiKey` yet. */+ orgTrigger?: OrgTriggerConfig;+ /** One-time guard for `migrateTriggersV1` (legacy webhook → webhookTriggers,+ * 1h → 2h compact cadence). Set once the migration has run to completion. */+ triggersMigratedV1?: boolean;+// ─── Memory reflection (the janitor's condense half) ───────────────────────/** Master toggle for the in-process MemoryReflector. Default on. */reflectEnabled?: boolean;@@ -385,6 +433,13 @@ const DEFAULTS: HarnessConfig = {webhookEnabled: false,webhookSecret: undefined,webhookPort: undefined,+ // Triggers. These three are the ONLY object/array defaults that get handed+ // straight back out of `readConfig` for a config that never persisted them, so+ // `withTriggerDefaults` re-copies them on every read — see the note there.+ contextTrigger: DEFAULT_CONTEXT_TRIGGER,+ webhookTriggers: [],+ orgTrigger: DEFAULT_ORG_TRIGGER,+ triggersMigratedV1: false,// Memory reflection — preventive; nobody is over threshold today, so it sits// dark until an agent's memory crosses one of these (the verify gate is the// safety for the LLM step). Thresholds DECIDED by god 2026-06-06.@@ -405,18 +460,122 @@ function configPath(): string {return join(app.getPath('userData'), 'config.json');}+/**+ * Deep-fill the trigger sub-objects, and hand back copies of them.+ *+ * TWO problems, one fix. First, the merge in `readConfig` is one level deep, so a+ * `contextTrigger` persisted by an older build (or by a `writeConfig` that+ * patched only `compact`) arrives missing sub-keys that DEFAULTS would have+ * supplied — the consumer then reads `undefined` where it expects a number and+ * the rule never fires. Second, that same shallow merge hands the literal+ * DEFAULT_CONTEXT_TRIGGER / DEFAULT_ORG_TRIGGER instances to every config that+ * didn't persist them, so one caller mutating what it read would rewrite the+ * defaults for the whole process — and for every config read afterwards.+ *+ * Every branch below therefore constructs a fresh object, including the+ * "nothing persisted" branch.+ */+function withTriggerDefaults(cfg: HarnessConfig): HarnessConfig {+ return {+ ...cfg,+ contextTrigger: {+ compact: { ...DEFAULT_CONTEXT_TRIGGER.compact, ...cfg.contextTrigger?.compact },+ clear: { ...DEFAULT_CONTEXT_TRIGGER.clear, ...cfg.contextTrigger?.clear }+ },+ orgTrigger: { ...DEFAULT_ORG_TRIGGER, ...cfg.orgTrigger },+ webhookTriggers: Array.isArray(cfg.webhookTriggers)+ ? cfg.webhookTriggers.map((t) => ({ ...t }))+ : []+ };+}++/** Set once `migrateTriggersV1` has run in THIS process. `writeConfig` reads+ * before it writes, so without an in-memory latch the migration's own persist+ * would re-enter `readConfig` and run the migration a second time before+ * `triggersMigratedV1: true` ever reached disk. */+let triggersMigrationRan = false;++/**+ * Fold the pre-Triggers config shape forward, exactly once per install.+ *+ * Runs from `readConfig`, so it is complete before any consumer can observe the+ * config — there is no boot ordering to get wrong and no window in which half+ * the app sees the old shape. Two things move:+ *+ * 1. The single legacy webhook (`webhookEnabled`/`webhookSecret`) becomes one+ * `WebhookTrigger` with the stable id `legacy`, so the caller that already+ * holds that secret keeps working across the upgrade. Skipped when+ * `webhookTriggers` is already populated — the user has moved on, and+ * re-adding a synthesised entry would resurrect a revoked endpoint.+ * 2. The seeded `compact-maintenance` mission moves from the old 1h cadence to+ * 2h, but ONLY if it still reads exactly 1h. A user-chosen interval is a+ * decision, not a stale default, and is left alone.+ *+ * Wrapped end-to-end in a try/catch: a config that is corrupt in some unrelated+ * way must still boot the app, and a migration is never worth a failed launch.+ */+function migrateTriggersV1(cfg: HarnessConfig): HarnessConfig {+ if (cfg.triggersMigratedV1 || triggersMigrationRan) return cfg;+ triggersMigrationRan = true;+ try {+ const next: HarnessConfig = { ...cfg, triggersMigratedV1: true };++ const legacySecret = typeof cfg.webhookSecret === 'string' ? cfg.webhookSecret.trim() : '';+ if (legacySecret && (cfg.webhookTriggers?.length ?? 0) === 0) {+ next.webhookTriggers = [+ {+ id: 'legacy',+ name: 'Default webhook',+ secret: legacySecret,+ enabled: cfg.webhookEnabled ?? false,+ mode: DEFAULT_TRIGGER_MODE,+ schema: DEFAULT_WEBHOOK_SCHEMA,+ createdAt: Date.now()+ }+ ];+ }++ const missions = Array.isArray(cfg.missions) ? cfg.missions : [];+ const stale = (m: ScheduledMission): boolean =>+ m?.id === COMPACT_MAINTENANCE_MISSION.id+ && m.intervalMs === LEGACY_COMPACT_MAINTENANCE_INTERVAL_MS;+ if (missions.some(stale)) {+ next.missions = missions.map((m) =>+ stale(m) ? { ...m, intervalMs: COMPACT_MAINTENANCE_MISSION.intervalMs } : m+ );+ }++ persistConfig(next);+ return next;+ } catch {+ // Leave the config exactly as read. The latch above stays set, so a failing+ // migration retries on the next launch rather than on every single read.+ return cfg;+ }+}+export function readConfig(): HarnessConfig {const p = configPath();- if (!existsSync(p)) return { ...DEFAULTS };+ // No file yet = a first run with nothing to migrate; the defaults ARE the+ // post-migration shape. Deliberately does not persist — a bare read must not+ // conjure a config.json before onboarding has written one.+ if (!existsSync(p)) return withTriggerDefaults({ ...DEFAULTS });try {const raw = readFileSync(p, 'utf8');const parsed = JSON.parse(raw);- return { ...DEFAULTS, ...parsed };+ return migrateTriggersV1(withTriggerDefaults({ ...DEFAULTS, ...parsed }));} catch {- return { ...DEFAULTS };+ return withTriggerDefaults({ ...DEFAULTS });}}+function persistConfig(next: HarnessConfig): HarnessConfig {+ const p = configPath();+ mkdirSync(dirname(p), { recursive: true });+ writeFileSync(p, JSON.stringify(next, null, 2), 'utf8');+ return next;+}+export function writeConfig(patch: Partial<HarnessConfig>): HarnessConfig {const current = readConfig();const next: HarnessConfig = { ...current, ...patch };@@ -437,10 +596,7 @@ export function writeConfig(patch: Partial<HarnessConfig>): HarnessConfig {const prior = current.recentHives ?? [];next.recentHives = [patch.harnessHome, ...prior.filter((h) => h !== patch.harnessHome)].slice(0, 8);}- const p = configPath();- mkdirSync(dirname(p), { recursive: true });- writeFileSync(p, JSON.stringify(next, null, 2), 'utf8');- return next;+ return persistConfig(next);}/** Wipe the persisted config back to first-run defaults so the app boots into@@ -449,7 +605,11 @@ export function resetConfig(): HarnessConfig {const p = configPath();mkdirSync(dirname(p), { recursive: true });writeFileSync(p, JSON.stringify(DEFAULTS, null, 2), 'utf8');- return { ...DEFAULTS };+ // Drop the migration latch too: the file on disk is back to `triggersMigratedV1:+ // false`, and a latch left set would keep the flag from ever being written again+ // in this process. The migration itself is a no-op on defaults either way.+ triggersMigrationRan = false;+ return withTriggerDefaults({ ...DEFAULTS });}/** Model ids by tier (Lane A #6.4). Kept in sync with AGENT_MODELS indiff --git a/src/main/index.ts b/src/main/index.tsindex b5fac95f..a67f67da 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -33,7 +33,19 @@ import { PersistStore } from './db';import { readAgentUsage, readContextTokens, seedSessionTranscript, resolveSessionCwd } from './transcript';import { listIssues, listCIRuns } from './github';import { SlackWebhookServer, SlackReplyServer, postSlackReply, type SlackEventFile } from './slack';-import { WebhookServer, type WebhookInbound, type WebhookTaskStatus } from './webhook';+import {+ WebhookServer,+ type WebhookDispatch, type WebhookEndpointRef, type WebhookInbound, type WebhookTaskStatus+} from './webhook';+import {+ classifyInboundKind, isAutoAllowed,+ DEFAULT_CONTEXT_TRIGGER, DEFAULT_ORG_TRIGGER, DEFAULT_TRIGGER_MODE, DEFAULT_WEBHOOK_SCHEMA,+ type ContextRule, type ContextTriggerConfig, type InboundKind, type OrgTriggerConfig,+ type TriggerHistoryEntry, type TriggerMode, type WebhookTrigger+} from '../shared/triggers';+import {+ appendTriggerHistory, clearTriggerHistory, listTriggerHistory, updateTriggerHistory+} from './triggerHistory';import { transcribeWithGroq, DEFAULT_GROQ_MODEL } from './freeflow';import { registerRealtimeIpc } from './realtime';import { registerRealtimeActionIpc } from './realtimeActions';@@ -608,8 +620,14 @@ function syncMissions(): void {// renderer, which queues a /compact per agent (deduped — never two at// once) and delivers it only when that agent goes idle (its drain loop),// so a working agent compacts between steps, never mid-step.+ //+ // The CADENCE now belongs to the context trigger, not to a mission — but+ // the legacy per-mission `autoCompact` flag keeps working, routed through+ // the same emit so there is exactly ONE path from main to the renderer.+ // It carries the context trigger's current rule so a mission-driven+ // compaction obeys the same pressure thresholds as a trigger-driven one.if (m.autoCompact || m.kind === 'compact') {- try { liveWebContents()?.send('mission:autoCompact'); } catch { /* window gone */ }+ emitContextTrigger('compact', contextRule('compact'));}const current = readConfig().missions ?? [];const next = current.map((x) =>@@ -635,6 +653,114 @@ function syncMissions(): void {}}+// ─── Context trigger (auto-compact / auto-clear own their own timers) ────────+// Compaction used to ride on a mission (`compact-maintenance`), which meant the+// operator had TWO competing controls for one behaviour — a schedule with an+// interval and a trigger with a cadence. The mission is retired (see the+// retirement migration in ensureDefaultMissions); these timers are the single+// remaining source of scheduled context maintenance.+//+// Main owns only the CADENCE. The pressure gate (`minContextPct`) needs each+// agent's live context usage, which only the renderer has, so the whole rule+// rides along in the event and the renderer decides which agents actually get+// the command. That split is why the payload carries the rule rather than a bare+// "go" signal.++/** Timers for the two halves, keyed by action. Same two-phase shape as+ * `missionTimers` (a setTimeout for the remaining time, then a steady interval)+ * so a partially-elapsed cadence survives a re-arm. */+const contextTimers = new Map<'compact' | 'clear', MissionTimer>();++/** `ContextRule` has no `lastFiredAt` (unlike `ScheduledMission`), so the last-run+ * instants live in the durable kv store instead. Without them every re-arm —+ * boot, a settings edit, a wake from sleep — would restart a 2h cadence from+ * zero, and an operator who edits the rule twice a day would never see it fire. */+const CONTEXT_LAST_RUN_KV_KEY = 'triggers.context.lastRun';+let contextLastRun: Record<string, number> | null = null;++function contextRunMap(): Record<string, number> {+ if (!contextLastRun) {+ try { contextLastRun = persist.getKv<Record<string, number>>(CONTEXT_LAST_RUN_KV_KEY) ?? {}; }+ catch { contextLastRun = {}; }+ }+ return contextLastRun;+}++/** When the rule last ran. An UNRECORDED half is stamped NOW rather than read as+ * the epoch: `remaining` would otherwise clamp to 0 and compact every terminal+ * the instant the app boots. It is the same trap `ensureDefaultMissions` avoids+ * by stamping `lastFiredAt` when it seeds a mission — a first launch should wait+ * a full cadence, not open with an interruption. */+function contextLastRunAt(action: 'compact' | 'clear'): number {+ const map = contextRunMap();+ const v = map[action];+ if (typeof v === 'number' && Number.isFinite(v)) return v;+ return stampContextRun(action);+}++function stampContextRun(action: 'compact' | 'clear'): number {+ const map = contextRunMap();+ const at = Date.now();+ map[action] = at;+ try { persist.setKv(CONTEXT_LAST_RUN_KV_KEY, map); } catch { /* DB best-effort */ }+ return at;+}++/** The live rule for one half, deep-filled. `readConfig` already fills both+ * halves, so the default is only a belt-and-braces fallback. */+function contextRule(action: 'compact' | 'clear'): ContextRule {+ return readConfig().contextTrigger?.[action] ?? DEFAULT_CONTEXT_TRIGGER[action];+}++/** Clear and forget both context timers (setTimeout + setInterval handles). */+function clearContextTimers(): void {+ for (const t of contextTimers.values()) {+ if (t.timeout) clearTimeout(t.timeout);+ if (t.interval) clearInterval(t.interval);+ }+ contextTimers.clear();+}++/** Ask the renderer to run one half of the context trigger. */+function emitContextTrigger(action: 'compact' | 'clear', rule: ContextRule): void {+ try { liveWebContents()?.send('trigger:context', { action, rule }); } catch { /* window gone */ }+ // TRANSITIONAL ALIAS: the renderer still carries the pre-Triggers+ // `mission:autoCompact` listener as a fallback. Both fire for compact until+ // every consumer has moved to `trigger:context`; then this line goes.+ if (action === 'compact') {+ try { liveWebContents()?.send('mission:autoCompact'); } catch { /* window gone */ }+ }+}++/** (Re)arm both context timers from persisted config. Clear-then-arm, so calling+ * it after a settings change, on boot, or on wake from sleep can never stack+ * duplicates. Honors elapsed-time-since-last-run exactly like mission arming:+ * an overdue rule fires ONCE and then settles into its steady cadence. */+function syncContextTriggers(): void {+ clearContextTimers();+ for (const action of ['compact', 'clear'] as const) {+ const rule = contextRule(action);+ if (!rule.enabled || !(rule.everyMs > 0)) continue;+ const fire = (): void => {+ try {+ stampContextRun(action);+ // Re-read: the operator may have edited the message/thresholds since the+ // timer was armed, and the renderer should act on what's current.+ emitContextTrigger(action, contextRule(action));+ } catch (e) {+ console.error('[triggers] context', action, e);+ }+ };+ const remaining = Math.max(0, rule.everyMs - (Date.now() - contextLastRunAt(action)));+ const entry: MissionTimer = {};+ entry.timeout = setTimeout(() => {+ fire();+ entry.interval = setInterval(fire, rule.everyMs);+ }, remaining);+ contextTimers.set(action, entry);+ }+}+/** Startup migration (#57/#58): archive every agent entry that is `archived:false`* but has NO live PTY. This runs in bootstrapHiveServices, BEFORE the renderer can* respawn anything, so at this point NO agent owns a PTY — every `archived:false`@@ -691,32 +817,47 @@ function ensureDefaultMissions(): void {});}- // maint-1: the dedicated auto-compact maintenance mission. Auto-compact USED to- // ride solely on the ops standup's autoCompact flag, so replacing the standup- // silently disabled compaction for all long-running agents. This makes it a- // first-class, persistent schedule:- // • FIRST seed (flag unset): add it ENABLED + MIGRATE — drop autoCompact from- // every OTHER mission so this is the single source of truth (no double- // /compact whether compaction rode the standup or a stopgapped custom mission).- // • PERSISTENT (flag set): if the user later deletes it, it reappears DISABLED- // next boot — never silently lost (only user-disabled, with a UI warning).+ // maint-1 RETIREMENT: `compact-maintenance` is no longer a mission. Scheduled+ // compaction is now the CONTEXT TRIGGER's job, so the operator has exactly one+ // control (a cadence + a pressure gate + an editable message) instead of two+ // that could disagree — a mission saying "hourly" while the trigger said "2h"+ // was a real, unresolvable conflict.+ //+ // The carry-over preserves the operator's decisions: whether compaction was ON+ // and how often. It runs at most once per install, and its guard is the+ // mission's own ABSENCE — nothing seeds `compact-maintenance` any more, so once+ // this has removed it there is nothing left to carry and a later hand-edit of+ // the trigger can never be clobbered. That keeps the `*Seeded` convention's+ // promise (exactly once, ever) without a config flag that would only ever be+ // read here; `compactMaintenanceSeeded` is left set so nothing re-seeds it.const cfg3 = readConfig();const missions3 = cfg3.missions ?? [];- const hasCompact = missions3.some((m) => m.id === COMPACT_MAINTENANCE_MISSION.id);- if (!cfg3.compactMaintenanceSeeded) {- const migrated = missions3.map((m) =>- m.id === COMPACT_MAINTENANCE_MISSION.id ? m : { ...m, autoCompact: false }- );+ const retiring = missions3.find((m) => m.id === COMPACT_MAINTENANCE_MISSION.id);+ if (retiring) {+ const current = cfg3.contextTrigger ?? DEFAULT_CONTEXT_TRIGGER;writeConfig({- missions: hasCompact- ? migrated- : [...migrated, { ...COMPACT_MAINTENANCE_MISSION, lastFiredAt: Date.now() }],+ missions: missions3.filter((m) => m.id !== COMPACT_MAINTENANCE_MISSION.id),+ contextTrigger: {+ ...current,+ compact: {+ ...current.compact,+ enabled: retiring.enabled,+ // A hand-tuned interval is a decision; only a missing/absurd one falls+ // back to whatever the trigger already carries.+ everyMs: retiring.intervalMs > 0 ? retiring.intervalMs : current.compact.everyMs+ }+ },compactMaintenanceSeeded: true});- } else if (!hasCompact) {- writeConfig({- missions: [...missions3, { ...COMPACT_MAINTENANCE_MISSION, enabled: false, lastFiredAt: Date.now() }]- });+ // …and its elapsed time, so retiring the mission mid-cycle doesn't restart a+ // 2h cadence from zero (the timers honour last-run exactly as arming did).+ if (typeof retiring.lastFiredAt === 'number' && retiring.lastFiredAt > 0) {+ const map = contextRunMap();+ map.compact = retiring.lastFiredAt;+ try { persist.setKv(CONTEXT_LAST_RUN_KV_KEY, map); } catch { /* DB best-effort */ }+ }+ console.log('[triggers] retired the compact-maintenance mission into contextTrigger.compact',+ `(enabled: ${retiring.enabled}, everyMs: ${retiring.intervalMs})`);}}@@ -1392,14 +1533,28 @@ function stopSlackServer(): void {try { if (existsSync(slackReplyConfigPath())) unlinkSync(slackReplyConfigPath()); } catch { /* noop */ }}-// ─── Generic inbound webhook + status API ────────────────────────────────────+// ─── Generic inbound webhook + status API (multi-endpoint) ───────────────────/** The running generic-webhook server, or null when disabled/stopped. A PUBLIC- * (tunnel-forwarded) surface — secret-gated, unlike the loopback /reply. */+ * (tunnel-forwarded) surface — secret-gated, unlike the loopback /reply. ONE+ * server and ONE tunnel serve EVERY configured endpoint; the id in the request+ * path picks which. Adding a webhook therefore costs no port and no tunnel, and+ * never disturbs a caller already pointed at another endpoint's URL. */let webhookServer: WebhookServer | null = null;-/** Last public tunnel URL handed out — persisted so Settings can re-show the- * endpoint after a reopen (loca.lt rotates it per restart). */+/** Last public tunnel URL handed out — retained so Settings can re-show the+ * endpoint after a reopen (the tunnel rotates it per restart). */let lastWebhookUrl: string | undefined;+/** Local port the shared server binds to. The port is a property of the SERVER,+ * not of any one trigger — `webhookPort` stays the (legacy) override. */+const WEBHOOK_DEFAULT_PORT = 3849;++/** The endpoints the operator has switched on. A disabled webhook is not merely+ * rejected at the door — it is never handed to the server, so its id does not+ * exist on the wire and its secret is not in memory on the request path. */+function enabledWebhookEndpoints(): WebhookTrigger[] {+ return (readConfig().webhookTriggers ?? []).filter((t) => t.enabled && !!t.secret);+}+/** SHA-256 hex of a capability token. The raw token is returned to the caller* exactly once (the POST response) and never persisted; only this digest lands* on the kanban card, so a GET can match without the raw token ever resting. */@@ -1407,63 +1562,196 @@ function hashWebhookToken(token: string): string {return createHash('sha256').update(token).digest('hex');}-/** Turn a verified webhook POST into hive work: create ONE stamped kanban card- * (origin + token hash) and route the message to god/Michael's inbox as a- * request. Returns the raw capability token + card id to hand back to the caller- * (the ONLY echo of the token). The secret never reaches here. Returns null only- * if the card — the thing the caller will poll — could not be created. */-function handleWebhookMessage(msg: WebhookInbound): { token: string; taskId: string } | null {- // 192-bit unguessable token, returned once; only its hash is stored.- const token = randomBytes(24).toString('hex');- const taskId = `webhook-${randomBytes(8).toString('hex')}`;- const full = msg.title ?? msg.message;- const title = full.length > 80 ? `${full.slice(0, 79)}…` : full;+/** tokenHash → id of the `pending` history entry it belongs to.+ *+ * A message the mode gate held has NO kanban card (the card is what approval+ * creates), so this map is the only way its caller's GET can be answered — and+ * answered HONESTLY, as "awaiting-approval" rather than a lie about queued work.+ * It stores the token's DIGEST, never the token, exactly like the card stamp,+ * and it is mirrored into the durable kv store so a restart doesn't 404 every+ * caller that is still politely waiting on the operator. */+let heldWebhookTokens: Map<string, string> | null = null;+const HELD_TOKENS_KV_KEY = 'triggers.webhook.heldTokens';++function heldTokens(): Map<string, string> {+ if (heldWebhookTokens) return heldWebhookTokens;+ let stored: Record<string, string> | undefined;+ try { stored = persist.getKv<Record<string, string>>(HELD_TOKENS_KV_KEY); }+ catch { stored = undefined; }+ const entries = stored && typeof stored === 'object' ? Object.entries(stored) : [];+ heldWebhookTokens = new Map(entries.filter((e): e is [string, string] => typeof e[1] === 'string'));+ return heldWebhookTokens;+}++function persistHeldTokens(): void {+ try { persist.setKv(HELD_TOKENS_KV_KEY, Object.fromEntries(heldTokens())); }+ catch (e) { console.error('[webhook] could not persist held-token map:', e); }+}++/** Drop mappings whose history entry has aged out of the (capped) ledger — the+ * operator can no longer decide them, so their tokens are dead weight. */+function pruneHeldTokens(): void {+ const map = heldTokens();+ if (map.size === 0) return;+ const live = new Set(listTriggerHistory().map((e) => e.id));+ let changed = false;+ for (const [hash, entryId] of [...map]) {+ if (!live.has(entryId)) { map.delete(hash); changed = true; }+ }+ if (changed) persistHeldTokens();+}++/** The token digest a held history entry was accepted under, if we still have it. */+function heldTokenHashFor(entryId: string): string | undefined {+ for (const [hash, id] of heldTokens()) if (id === entryId) return hash;+ return undefined;+}- // 1) Create the stamped card. This is the critical step — the caller's token is- // only useful if a card exists to poll, so a failure here fails the POST.+/** Tell the Triggers tab its ledger moved, so history live-refreshes instead of+ * waiting for the operator to re-open the tab. */+function notifyTriggerHistoryUpdated(): void {+ try { liveWebContents()?.send('triggerHistory:updated'); } catch { /* window gone */ }+}++/**+ * Create the stamped kanban card for an inbound message and route it to god.+ *+ * Split out of `handleWebhookMessage` because the APPROVAL path takes exactly+ * this route later — an operator saying yes must produce the same card and the+ * same god request an auto-allowed message would have, or the two paths drift+ * and "approved" quietly means something weaker than "allowed".+ *+ * Returns false only when the card — the thing the caller polls — could not be+ * written. The god routing is best-effort: the card already exists and is+ * pollable even if the send hiccups.+ */+function dispatchWebhookWork(arg: {+ taskId: string;+ title: string;+ message: string;+ /** Stamped onto the card so a GET can match the caller's token. */+ tokenHash?: string;+ /** 'webhook' | 'org' — only for the subject line and the god-facing note. */+ origin: 'webhook' | 'org';+}): boolean {try {const ledger = hive.tasks() as { tasks?: HiveTask[] };const existing = Array.isArray(ledger?.tasks) ? ledger.tasks : [];const card: HiveTask = {- id: taskId,- title,- description: msg.message,+ id: arg.taskId,+ title: arg.title,+ description: arg.message,status: 'todo',dependsOn: [],priority: 1,createdAt: new Date().toISOString(),- webhook: { tokenHash: hashWebhookToken(token) }+ ...(arg.tokenHash ? { webhook: { tokenHash: arg.tokenHash } } : {})};hive.writeTasks([...existing, card]);} catch (e) {console.error('[webhook] could not create task card:', e instanceof Error ? e.message : e);- return null;+ return false;}-- // 2) Route the work to god/Michael (god inbox request). Body carries ONLY the- // user message + the card id (so whoever finishes it updates that card's- // status/result for the caller's GET) — never the secret or the raw token.- // Best-effort: the card already exists and is pollable even if this hiccups.+ // Body carries ONLY the sender's message + the card id (so whoever finishes it+ // updates that card's status/result for the caller's GET) — never the secret,+ // never the raw token.try {hive.send({to: 'god',act: 'request',- subject: `[webhook] ${title}`,- body: `${msg.message}\n\n(Inbound via the generic webhook API, tracked as kanban card ${taskId}. When this work is finished, set that card's status to 'done' and fill its 'result' so the caller's status check reflects the outcome.)`,+ subject: `[${arg.origin}] ${arg.title}`,+ body: `${arg.message}\n\n(Inbound via the generic ${arg.origin} API, tracked as kanban card ${arg.taskId}. When this work is finished, set that card's status to 'done' and fill its 'result' so the caller's status check reflects the outcome.)`,requires_reply: false}, 'webhook');} catch (e) {console.error('[webhook] could not route to god:', e instanceof Error ? e.message : e);}- return { token, taskId };+ return true;+}++/**+ * A verified POST, run through the endpoint's TriggerMode.+ *+ * `isAutoAllowed(mode, kind)` is the whole gate. When it says yes this behaves+ * exactly as the single-endpoint server always did — card, god request, capability+ * token. When it says no NOTHING reaches the hive: the message is written to the+ * ledger as `pending` and sits there until the operator decides, and the caller+ * is handed its token plus a 202 so it can watch the hold rather than believe+ * work started.+ *+ * Either way an `inbound` history row is recorded. The secret never reaches here+ * (the server hands over `{id,name}` only) and no credential is ever written to+ * the ledger.+ */+function handleWebhookMessage(msg: WebhookInbound, endpoint: WebhookEndpointRef): WebhookDispatch | null {+ // 192-bit unguessable token, returned once; only its hash is stored.+ const token = randomBytes(24).toString('hex');+ const tokenHash = hashWebhookToken(token);+ const full = msg.title ?? msg.message;+ const title = full.length > 80 ? `${full.slice(0, 79)}…` : full;++ const trigger = (readConfig().webhookTriggers ?? []).find((t) => t.id === endpoint.id);+ // An endpoint that vanished between the request and this lookup falls back to+ // the STRICTEST mode, never the most permissive one.+ const mode: TriggerMode = trigger?.mode ?? DEFAULT_TRIGGER_MODE;+ // The caller's own declaration wins; `classifyInboundKind` is the conservative+ // guess for callers that don't declare (it leans 'directive' on purpose).+ const kind: InboundKind = msg.kind ?? classifyInboundKind(msg.message);+ const peer = msg.from?.trim() || endpoint.name || endpoint.id;+ // Minted here, not derived from the task id, because a HELD message has no task+ // id yet and must still be pairable with the reply it eventually earns.+ const correlationId = randomBytes(8).toString('hex');++ const base = {+ source: 'webhook' as const,+ sourceId: endpoint.id,+ sourceName: endpoint.name,+ direction: 'inbound' as const,+ peer,+ title,+ body: msg.message,+ kind,+ correlationId+ };++ if (!isAutoAllowed(mode, kind)) {+ const entry = appendTriggerHistory({ ...base, decision: 'pending' });+ heldTokens().set(tokenHash, entry.id);+ persistHeldTokens();+ notifyTriggerHistoryUpdated();+ return { token, pending: true };+ }++ const taskId = `webhook-${randomBytes(8).toString('hex')}`;+ if (!dispatchWebhookWork({ taskId, title, message: msg.message, tokenHash, origin: 'webhook' })) return null;+ appendTriggerHistory({ ...base, decision: 'auto-allowed', taskId });+ notifyTriggerHistoryUpdated();+ return { token, taskId, pending: false };}/** Resolve a capability token to its task's public status — scoped to the ONE- * card whose stored hash matches; never lists or leaks any other task. Returns- * null for any non-match (the server answers 404 either way, so a probe can't- * tell "unknown" from "malformed"). */+ * card (or the ONE held message) whose stored hash matches; never lists or leaks+ * any other task. Returns null for any non-match (the server answers 404 either+ * way, so a probe can't tell "unknown" from "malformed"). */function lookupWebhookStatus(token: string): WebhookTaskStatus | null {- const wanted = Buffer.from(hashWebhookToken(token));+ const hash = hashWebhookToken(token);++ // Held messages first — they have no card, and the O(1) hit keeps the common+ // "still waiting" poll off the task scan entirely.+ const heldEntryId = heldTokens().get(hash);+ if (heldEntryId) {+ const entry = listTriggerHistory().find((e) => e.id === heldEntryId);+ if (!entry) { heldTokens().delete(hash); persistHeldTokens(); return null; }+ if (entry.decision === 'pending') {+ return { status: 'awaiting-approval', title: entry.title ?? '' };+ }+ if (entry.decision === 'rejected') {+ return { status: 'rejected', title: entry.title ?? '' };+ }+ // Approved: the release stamped this hash onto a real card, so fall through.+ }++ const wanted = Buffer.from(hash);let tasks: HiveTask[];try {const ledger = hive.tasks() as { tasks?: HiveTask[] };@@ -1481,33 +1769,143 @@ function lookupWebhookStatus(token: string): WebhookTaskStatus | null {return null;}-/** Build a WebhookServer from the current config and start it, replacing any- * running instance. No-op + error when disabled or the secret is unset. The- * public tunnel is opened only here — never on a default; it stays opt-in- * (user enables + presses Start in Settings). */+// ─── Webhook done-observer (the OUTBOUND half of the trigger ledger) ─────────+// Mirrors `pollSlackDoneTasks`: watch the kanban for webhook-origin cards that+// reach 'done' and write the reply side of the conversation, tagged with the+// inbound row's correlationId so the UI can pair request ↔ response.+//+// Unlike the Slack poller there is no "baseline" of already-done ids: the LEDGER+// is the record of what we've already paired, so a card that finished while the+// app was closed still gets its outbound row on the next boot, and re-seeding+// from the ledger makes a duplicate impossible.+let webhookDoneTimer: ReturnType<typeof setInterval> | null = null;+let webhookOutboundRecorded: Set<string> | null = null;++function seedWebhookOutbound(): Set<string> {+ const seen = new Set<string>();+ try {+ for (const e of listTriggerHistory()) {+ if (e.direction === 'outbound' && e.taskId) seen.add(e.taskId);+ }+ } catch { /* unreadable ledger → treat as empty; appends are still deduped by taskId */ }+ return seen;+}++function pollWebhookDoneTasks(): void {+ let tasks: HiveTask[];+ try {+ const ledger = hive.tasks() as { tasks?: HiveTask[] };+ tasks = Array.isArray(ledger?.tasks) ? ledger.tasks : [];+ } catch { return; } // unreadable/missing tasks.json → skip this tick+ const done = tasks.filter((t) =>+ t.status === 'done' && (t.webhook != null || t.id.startsWith('webhook-')));+ if (done.length === 0) return;+ const recorded = webhookOutboundRecorded ?? (webhookOutboundRecorded = seedWebhookOutbound());+ const fresh = done.filter((t) => !recorded.has(t.id));+ if (fresh.length === 0) return;++ const history = listTriggerHistory();+ let wrote = false;+ for (const t of fresh) {+ const inbound = history.find((e) => e.direction === 'inbound' && e.taskId === t.id);+ // No inbound row = a card from before the ledger existed. Nothing to pair it+ // with, so mark it handled rather than writing a half of a conversation.+ if (!inbound) { recorded.add(t.id); continue; }+ appendTriggerHistory({+ source: inbound.source,+ sourceId: inbound.sourceId,+ sourceName: inbound.sourceName,+ direction: 'outbound',+ peer: inbound.peer,+ title: t.title,+ body: (t.result ?? '').trim() || '(finished with no result recorded)',+ kind: inbound.kind,+ correlationId: inbound.correlationId,+ taskId: t.id+ });+ recorded.add(t.id);+ wrote = true;+ }+ if (wrote) notifyTriggerHistoryUpdated();+}++/** Begin watching the kanban for webhook-origin done-transitions (idempotent). */+function startWebhookDoneObserver(): void {+ if (webhookDoneTimer) return;+ webhookOutboundRecorded = seedWebhookOutbound();+ webhookDoneTimer = setInterval(() => {+ try { pollWebhookDoneTasks(); } catch (e) { console.error('[webhook] done-observer:', e); }+ }, 5000);+}++/** Stop watching the kanban. Safe to call when not running. */+function stopWebhookDoneObserver(): void {+ if (webhookDoneTimer) { clearInterval(webhookDoneTimer); webhookDoneTimer = null; }+ webhookOutboundRecorded = null;+}++/** Build the shared WebhookServer from the enabled endpoints and start it. A+ * server that is already up is RE-POINTED rather than restarted (see+ * `reconcileWebhookServer`): restarting would mint a fresh tunnel URL and break+ * every other endpoint's caller. The public tunnel is opened only here — never+ * on a default; a webhook reaches the wire only once the operator enables it. */async function startWebhookServer(): Promise<{ ok: boolean; url?: string; error?: string }> {- const cfg = readConfig();- if (!cfg.webhookEnabled || !cfg.webhookSecret) {- return { ok: false, error: 'webhook disabled or missing secret' };+ const endpoints = enabledWebhookEndpoints();+ if (endpoints.length === 0) return { ok: false, error: 'no enabled webhook endpoints' };+ if (webhookServer) {+ webhookServer.setEndpoints(endpoints);+ return { ok: true, url: webhookServer.publicUrl() ?? lastWebhookUrl };}- webhookServer?.stop();- webhookServer = new WebhookServer({- port: cfg.webhookPort && cfg.webhookPort > 0 ? cfg.webhookPort : 3849,- secret: cfg.webhookSecret,+ pruneHeldTokens();+ const cfg = readConfig();+ const server = new WebhookServer({+ port: cfg.webhookPort && cfg.webhookPort > 0 ? cfg.webhookPort : WEBHOOK_DEFAULT_PORT,+ endpoints,onMessage: handleWebhookMessage,lookupStatus: lookupWebhookStatus});- const res = await webhookServer.start();- if (!res.ok) { webhookServer = null; return res; }+ webhookServer = server;+ const res = await server.start();+ // ok:false covers BOTH "never bound the port" (fatal → drop the instance) and+ // "bound fine, tunnel unavailable" (the security boundary is live and must stay+ // reachable/stoppable — dropping it there would leak an unstoppable listener).+ if (!res.ok && !server.listening()) { webhookServer = null; return res; }if (res.url) lastWebhookUrl = res.url;+ startWebhookDoneObserver();return res;}+/** Bring the running server in line with config after any webhook mutation.+ * Live endpoint swap when it's up, start when the enabled set becomes non-empty,+ * stop when it empties. Never restarts a healthy server. */+function reconcileWebhookServer(): void {+ const endpoints = enabledWebhookEndpoints();+ if (endpoints.length === 0) { stopWebhookServer(); return; }+ if (webhookServer) { webhookServer.setEndpoints(endpoints); return; }+ void startWebhookServer().then((r) => {+ if (!r.ok) console.error('[webhook] start failed:', r.error);+ else console.log('[webhook] listening', r.url ? `(tunnel: ${r.url})` : '(no tunnel)');+ });+}++/** Per-endpoint public URLs for the settings surface's copy button. Empty string+ * when no tunnel has ever come up — the UI shows the endpoint, just not a URL+ * it could hand out yet. */+function webhookEndpointUrls(): { id: string; url: string }[] {+ const base = (webhookServer?.publicUrl() ?? lastWebhookUrl ?? '').replace(/\/+$/, '');+ return (readConfig().webhookTriggers ?? []).map((t) => ({+ id: t.id,+ url: base ? `${base}/${encodeURIComponent(t.id)}` : ''+ }));+}+/** Stop and forget the webhook server. Best-effort; safe when not running. The* last tunnel URL is retained so Settings keeps showing it. */function stopWebhookServer(): void {try { webhookServer?.stop(); } catch (e) { console.error('[webhook] stop failed:', e); }webhookServer = null;+ // The done-observer deliberately OUTLIVES the server (it is a ledger concern,+ // not a transport one) — it is torn down with the process/hive, not here.}/** The persisted main-window geometry (kv key `window.bounds`). */@@ -2459,6 +2857,8 @@ ipcMain.handle('config:changeHome', async (_evt, payload: unknown) => {// mid-copy — a live git commit into hive/.git would otherwise be copied as a// half-written object and corrupt the moved repo.try { clearMissionTimers(); } catch (e) { console.error('[changeHome] clearMissionTimers:', e); }+ try { clearContextTimers(); } catch (e) { console.error('[changeHome] clearContextTimers:', e); }+ try { stopWebhookDoneObserver(); } catch (e) { console.error('[changeHome] stopWebhookDoneObserver:', e); }try { stopEphemeralWorkerWatcher(); } catch (e) { console.error('[changeHome] stopWorkerWatcher:', e); }try { integrationBroker.stop(); } catch (e) { console.error('[changeHome] broker.stop:', e); }try { hive.stopRouter(); } catch (e) { console.error('[changeHome] stopRouter:', e); }@@ -2488,7 +2888,7 @@ ipcMain.handle('config:changeHome', async (_evt, payload: unknown) => {bootstrapHiveServices();const cfg = readConfig();if (cfg.slackEnabled && cfg.slackSigningSecret) void startSlackServer();- if (cfg.webhookEnabled && cfg.webhookSecret) void startWebhookServer();+ reconcileWebhookServer();return { ok: false, error: `Could not copy data: ${e instanceof Error ? e.message : String(e)}` };}}@@ -2773,12 +3173,15 @@ function teardownAndQuit(): void {// Each teardown step is best-effort: a throw here (e.g. a dying child or a// half-torn-down socket) must never abort the quit or pop a crash dialog.try { clearMissionTimers(); } catch (e) { console.error('[quit] clearMissionTimers:', e); }+ try { clearContextTimers(); } catch (e) { console.error('[quit] clearContextTimers:', e); }+ try { stopWebhookDoneObserver(); } catch (e) { console.error('[quit] stopWebhookDoneObserver:', e); }try { stopEphemeralWorkerWatcher(); } catch (e) { console.error('[quit] stopWorkerWatcher:', e); }try { integrationBroker.stop(); } catch (e) { console.error('[quit] broker.stop:', e); }try { hive.stopRouter(); } catch (e) { console.error('[quit] stopRouter:', e); }try { hookServer.stop(); } catch (e) { console.error('[quit] hookServer.stop:', e); }try { telemetry.stop(); } catch (e) { console.error('[quit] telemetry.stop:', e); }try { stopSlackServer(); } catch (e) { console.error('[quit] slack.stop:', e); }+ try { stopWebhookServer(); } catch (e) { console.error('[quit] webhook.stop:', e); }try { memory.stop(); } catch (e) { console.error('[quit] memory.stop:', e); }try { reflector.stop(); } catch (e) { console.error('[quit] reflector.stop:', e); }try { persist.close(); } catch (e) { console.error('[quit] persist.close:', e); }@@ -2827,6 +3230,8 @@ ipcMain.handle('app:resetAll', () => {allowQuit = true;// Tear everything down first so nothing writes back into the dirs we wipe.try { clearMissionTimers(); } catch (e) { console.error('[reset] clearMissionTimers:', e); }+ try { clearContextTimers(); } catch (e) { console.error('[reset] clearContextTimers:', e); }+ try { stopWebhookDoneObserver(); } catch (e) { console.error('[reset] stopWebhookDoneObserver:', e); }try { stopEphemeralWorkerWatcher(); } catch (e) { console.error('[reset] stopWorkerWatcher:', e); }try { integrationBroker.stop(); } catch (e) { console.error('[reset] broker.stop:', e); }try { hive.stopRouter(); } catch (e) { console.error('[reset] stopRouter:', e); }@@ -3122,7 +3527,180 @@ ipcMain.handle('slack:setConfig', (_evt, patch: unknown) => {return { ok: true };});-// ─── IPC: Generic webhook + status API ──────────────────────────────────────+// ─── IPC: Triggers — context (auto-compact / auto-clear) ────────────────────+ipcMain.handle('triggers:getContext', () => readConfig().contextTrigger ?? DEFAULT_CONTEXT_TRIGGER);+ipcMain.handle('triggers:setContext', (_evt, arg: unknown) => {+ const current = readConfig().contextTrigger ?? DEFAULT_CONTEXT_TRIGGER;+ const p = (arg ?? {}) as Partial<ContextTriggerConfig>;+ const next: ContextTriggerConfig = {+ compact: sanitizeContextRule(p.compact, current.compact),+ clear: sanitizeContextRule(p.clear, current.clear)+ };+ writeConfig({ contextTrigger: next });+ // The timers ARE the setting — a cadence saved but not re-armed would keep+ // firing on the old rhythm until the next boot.+ syncContextTriggers();+ return next;+});++/** Clamp one half of the context trigger. The renderer is not trusted with the+ * arming maths: a zero/negative/NaN `everyMs` would arm a runaway timer, and an+ * out-of-range percentage would silently disable (or permanently trip) the+ * pressure gate. */+function sanitizeContextRule(patch: Partial<ContextRule> | undefined, current: ContextRule): ContextRule {+ const p = (patch ?? {}) as Partial<ContextRule>;+ const num = (v: unknown, fallback: number, min: number, max: number): number =>+ typeof v === 'number' && Number.isFinite(v) ? Math.min(max, Math.max(min, v)) : fallback;+ return {+ enabled: typeof p.enabled === 'boolean' ? p.enabled : current.enabled,+ everyMs: num(p.everyMs, current.everyMs, 60_000, 86_400_000),+ minContextPct: num(p.minContextPct, current.minContextPct, 0, 100),+ minContextPctLargeWindow: num(p.minContextPctLargeWindow, current.minContextPctLargeWindow, 0, 100),+ message: typeof p.message === 'string' ? p.message : current.message+ };+}++// ─── IPC: Triggers — webhooks (many endpoints, one server, one tunnel) ──────+ipcMain.handle('webhooks:list', () => readConfig().webhookTriggers ?? []);+ipcMain.handle('webhooks:save', (_evt, arg: unknown) => {+ const incoming = Array.isArray(arg) ? arg : [];+ const existing = readConfig().webhookTriggers ?? [];+ const list: WebhookTrigger[] = [];+ const seen = new Set<string>();+ for (const raw of incoming) {+ const t = sanitizeWebhookTrigger(raw, existing);+ if (!t || seen.has(t.id)) continue; // an id is a URL path segment — one owner each+ seen.add(t.id);+ list.push(t);+ }+ writeConfig({ webhookTriggers: list });+ reconcileWebhookServer();+ return list;+});+ipcMain.handle('webhooks:delete', (_evt, arg: unknown) => {+ const id = typeof arg === 'string' ? arg : '';+ const list = (readConfig().webhookTriggers ?? []).filter((t) => t.id !== id);+ writeConfig({ webhookTriggers: list });+ // Revoking one endpoint must not disturb the others: the live server is+ // re-pointed, not restarted, so every remaining caller's URL keeps working.+ reconcileWebhookServer();+ return list;+});+/** Mint a strong (256-bit) secret for the operator to paste into their caller.+ * Not persisted here — it belongs to whichever endpoint the UI saves it onto. */+ipcMain.handle('webhooks:generateSecret', () => randomBytes(32).toString('hex'));+/** Server state + the tunnel root + one public URL per configured endpoint (the+ * UI offers a copy button per webhook, so the root alone isn't enough). */+ipcMain.handle('webhooks:status', () => ({+ running: webhookServer != null,+ url: lastWebhookUrl,+ endpoints: webhookEndpointUrls()+}));++/** Normalise one endpoint coming back from the renderer. Unknown/blank fields+ * fall back to what is already persisted, so a UI that round-trips a partially+ * filled row can never blank a live secret or silently widen a mode. */+function sanitizeWebhookTrigger(raw: unknown, existing: WebhookTrigger[]): WebhookTrigger | null {+ if (!raw || typeof raw !== 'object') return null;+ const r = raw as Partial<WebhookTrigger>;+ const id = typeof r.id === 'string' ? r.id.trim() : '';+ // The id is spliced into a public URL path. Restrict it to a boring charset+ // rather than escaping later: no slashes (which would forge a nested route),+ // no encoded traversal, nothing that could make two endpoints alias.+ if (!/^[A-Za-z0-9._-]{1,64}$/.test(id)) return null;+ const prior = existing.find((t) => t.id === id);+ const secret = typeof r.secret === 'string' && r.secret.trim() ? r.secret.trim() : prior?.secret ?? '';+ const mode = isTriggerMode(r.mode) ? r.mode : prior?.mode ?? DEFAULT_TRIGGER_MODE;+ return {+ id,+ name: typeof r.name === 'string' && r.name.trim() ? r.name.trim() : prior?.name ?? id,+ secret,+ // A secretless endpoint can never be enabled — it would be an open door.+ enabled: secret ? (typeof r.enabled === 'boolean' ? r.enabled : prior?.enabled ?? false) : false,+ mode,+ schema: typeof r.schema === 'string' && r.schema.trim() ? r.schema : prior?.schema ?? DEFAULT_WEBHOOK_SCHEMA,+ createdAt: typeof r.createdAt === 'number' && r.createdAt > 0 ? r.createdAt : prior?.createdAt ?? Date.now()+ };+}++function isTriggerMode(v: unknown): v is TriggerMode {+ return v === 'strict' || v === 'allow-all' || v === 'communication-only';+}++// ─── IPC: Triggers — organisation (persistence only; no transport yet) ──────+ipcMain.handle('org:getTrigger', () => readConfig().orgTrigger ?? DEFAULT_ORG_TRIGGER);+ipcMain.handle('org:setTrigger', (_evt, arg: unknown) => {+ const current = readConfig().orgTrigger ?? DEFAULT_ORG_TRIGGER;+ const p = (arg ?? {}) as Partial<OrgTriggerConfig>;+ // PERSIST ONLY — the peer messaging service does not exist yet, so nothing+ // reads `apiKey` beyond the settings surface that shows it. Deliberately no+ // start/stop, no network, no side effect of any kind.+ const next: OrgTriggerConfig = {+ apiKey: typeof p.apiKey === 'string' ? p.apiKey.trim() : current.apiKey,+ enabled: typeof p.enabled === 'boolean' ? p.enabled : current.enabled,+ mode: isTriggerMode(p.mode) ? p.mode : current.mode+ };+ writeConfig({ orgTrigger: next });+ return next;+});++// ─── IPC: Triggers — history ledger + the approval gate ─────────────────────+ipcMain.handle('triggerHistory:list', () => listTriggerHistory());+ipcMain.handle('triggerHistory:clear', (_evt, arg: unknown) => {+ const source = arg === 'webhook' || arg === 'org' ? arg : undefined;+ clearTriggerHistory(source);+ pruneHeldTokens();+ notifyTriggerHistoryUpdated();+ return { ok: true };+});+/**+ * The operator's verdict on a held message.+ *+ * 'approved' RELEASES it: it takes the identical path an auto-allowed message+ * would have taken (card + god request), then the entry flips. 'rejected' just+ * flips — nothing is ever dispatched.+ *+ * Idempotent by construction: only an entry still sitting at `pending` can be+ * decided, so a double-click (or two windows deciding at once) cannot dispatch+ * the same message twice.+ */+ipcMain.handle('triggerHistory:decide', (_evt, arg: unknown) => {+ const p = (arg ?? {}) as { id?: unknown; decision?: unknown };+ const id = typeof p.id === 'string' ? p.id : '';+ const decision = p.decision === 'approved' ? 'approved' : p.decision === 'rejected' ? 'rejected' : null;+ if (!id || !decision) return null;+ const entry: TriggerHistoryEntry | undefined = listTriggerHistory().find((e) => e.id === id);+ if (!entry) return null;+ if (entry.decision !== 'pending') return entry; // already decided → no-op, not a re-dispatch++ if (decision === 'rejected') {+ const next = updateTriggerHistory(id, { decision: 'rejected' });+ notifyTriggerHistoryUpdated();+ return next;+ }++ const taskId = `webhook-${randomBytes(8).toString('hex')}`;+ const tokenHash = heldTokenHashFor(id);+ const title = entry.title ?? (entry.body.length > 80 ? `${entry.body.slice(0, 79)}…` : entry.body);+ if (!dispatchWebhookWork({ taskId, title, message: entry.body, tokenHash, origin: entry.source })) {+ // The card is what the caller polls and what god works from. Leave the entry+ // pending so the operator can approve again once the hive is writable.+ return entry;+ }+ // The hash now lives on the card, so the caller's GET resolves through the+ // normal task lookup from here on.+ if (tokenHash) { heldTokens().delete(tokenHash); persistHeldTokens(); }+ const next = updateTriggerHistory(id, { decision: 'approved', taskId });+ pruneHeldTokens();+ notifyTriggerHistoryUpdated();+ return next;+});++// ─── IPC: Generic webhook (LEGACY single-endpoint channels) ─────────────────+// Kept alive for Settings → Webhook, which still speaks the one-secret shape.+// They are now THIN SHIMS over the multi-endpoint engine: the legacy secret and+// enabled flag map onto the `legacy` WebhookTrigger the config migration created,+// so the two surfaces can never disagree about whether the endpoint is live.ipcMain.handle('webhook:start', () => startWebhookServer());ipcMain.handle('webhook:stop', () => { stopWebhookServer(); return { ok: true }; });/** Current state + last public endpoint URL, for the Settings badge/URL field. */@@ -3132,6 +3710,7 @@ ipcMain.handle('webhook:status', () => ({ running: webhookServer != null, url: lipcMain.handle('webhook:generateSecret', () => {const secret = randomBytes(32).toString('hex');writeConfig({ webhookSecret: secret });+ upsertLegacyWebhookTrigger({ secret });return { ok: true, secret };});ipcMain.handle('webhook:setConfig', (_evt, patch: unknown) => {@@ -3141,14 +3720,40 @@ ipcMain.handle('webhook:setConfig', (_evt, patch: unknown) => {if (typeof p.port === 'number' && Number.isFinite(p.port)) next.webhookPort = p.port;if (typeof p.enabled === 'boolean') next.webhookEnabled = p.enabled;writeConfig(next);- // Disabling (or clearing the secret) stops the public surface immediately. As- // with Slack we do NOT auto-(re)start — the user presses Start to open the- // tunnel and fetch the fresh endpoint URL.- const cfg = readConfig();- if (!cfg.webhookEnabled || !cfg.webhookSecret) stopWebhookServer();+ upsertLegacyWebhookTrigger({+ secret: typeof p.secret === 'string' ? p.secret.trim() : undefined,+ enabled: typeof p.enabled === 'boolean' ? p.enabled : undefined+ });+ // Disabling (or clearing the secret) stops the public surface immediately; the+ // reconcile also picks up the case where OTHER endpoints are still enabled, in+ // which case the server stays up minus the legacy one.+ reconcileWebhookServer();return { ok: true };});+/** Mirror a legacy `webhook:setConfig` / `webhook:generateSecret` edit onto the+ * `legacy` WebhookTrigger. Creates the row only once a secret exists — an+ * enabled endpoint without a secret would be an open door, so a bare "enable"+ * against a never-configured webhook is deliberately a no-op. */+function upsertLegacyWebhookTrigger(patch: { secret?: string; enabled?: boolean }): void {+ const list = readConfig().webhookTriggers ?? [];+ const prior = list.find((t) => t.id === 'legacy');+ const secret = patch.secret !== undefined ? patch.secret : prior?.secret ?? '';+ if (!secret) return;+ const row: WebhookTrigger = {+ id: 'legacy',+ name: prior?.name ?? 'Default webhook',+ secret,+ enabled: patch.enabled !== undefined ? patch.enabled : prior?.enabled ?? false,+ mode: prior?.mode ?? DEFAULT_TRIGGER_MODE,+ schema: prior?.schema ?? DEFAULT_WEBHOOK_SCHEMA,+ createdAt: prior?.createdAt ?? Date.now()+ };+ writeConfig({+ webhookTriggers: prior ? list.map((t) => (t.id === 'legacy' ? row : t)) : [...list, row]+ });+}+// ─── IPC: Free Flow (voice dictation → message queue) ────────────────────────// Entry point B is hold-Option-to-talk, handled entirely in the renderer// (capture-phase key listeners) — no globalShortcut here. macOS doesn't deliver@@ -3757,6 +4362,12 @@ function bootstrapHiveServices(): void {});ensureDefaultMissions(); // one-time: seed the built-in hourly ops standupsyncMissions(); // arm recurring auto-dispatch missions now the router is live+ syncContextTriggers(); // …and the context trigger's own compact/clear cadences+ // Pair replies to inbound webhook messages in the ledger. Tied to the FEATURE+ // (any endpoint configured), not to the server: an approved message's card can+ // finish long after the operator switched the public surface back off, and its+ // reply still belongs in the history.+ if ((readConfig().webhookTriggers ?? []).length > 0) startWebhookDoneObserver();hookServer.start();// Bind the telemetry collector BEFORE the renderer spawns any agent, then point// the hive at it so every subsequent spawn is instrumented. Best-effort — a bind@@ -3835,6 +4446,10 @@ function healthCheckPtys(reason: string, awayMs: number | null): void {function onSystemResume(reason: string): void {console.log(`[power] ${reason} — re-arming scheduler, beats, router, keep-awake`);try { syncMissions(); } catch (e) { console.error('[power] syncMissions on resume', e); }+ // Same freeze, same catch-up: the context timers honour elapsed-time-since-last-+ // run, so a compact/clear that came due while the machine slept fires ONCE here+ // rather than being lost or replayed N times.+ try { syncContextTriggers(); } catch (e) { console.error('[power] syncContextTriggers on resume', e); }try { armAlwaysOnBeats(); } catch (e) { console.error('[power] armAlwaysOnBeats on resume', e); }// The hive message router (outbox→inbox drain) is a setInterval that freezes// during true system sleep exactly like the beats above — but it was the one@@ -3914,9 +4529,10 @@ app.whenReady().then(() => {else console.log('[slack] webhook listening', r.url ? `(tunnel: ${r.url})` : '(no tunnel)');});}- // Auto-start the generic webhook only when the user has explicitly enabled it- // AND a secret exists — never a default-on public surface. Opt-in, like Slack.- if (slackCfg.webhookEnabled && slackCfg.webhookSecret) {+ // Auto-start the generic webhook only for endpoints the user has explicitly+ // enabled (each with its own secret) — never a default-on public surface.+ // Opt-in, like Slack; an install with no enabled endpoint opens no tunnel.+ if (enabledWebhookEndpoints().length > 0) {void startWebhookServer().then((r) => {if (!r.ok) console.error('[webhook] auto-start failed:', r.error);else console.log('[webhook] listening', r.url ? `(tunnel: ${r.url})` : '(no tunnel)');diff --git a/src/main/realtimeActions.ts b/src/main/realtimeActions.tsindex 3c9a0595..9c10ed68 100644--- a/src/main/realtimeActions.ts+++ b/src/main/realtimeActions.ts@@ -37,6 +37,8 @@import { ipcMain } from 'electron';import type { HiveMessage, HiveTask, Registry } from './hive';import type { ScheduledMission } from './config';+import { inferAgentProvider } from '../shared/agentProvider';+import { clearCommandForProvider } from '../shared/providerAutomation';export const VOICE_ACTOR = 'michael-voice';@@ -543,9 +545,19 @@ function buildSpawn(deps: RealtimeActionDeps, spec: RealtimeSpawnSpec, label: stfunction buildClearContext(deps: RealtimeActionDeps, r: ResolvedAgent): () => Promise<string> {return async () => {- // Queue '/clear' through the renderer message queue: delivery inherits every- // existing safety gate (idle-only, boot grace, draft/picker protection).- deps.enqueueToAgent(r.id, '/clear');+ // '/clear' is NOT universal — it was hardcoded here for every provider, which+ // meant Grok/OpenCode/pi (whose verb is '/new') got a literal "/clear" typed+ // as chat text, and Crush/Copilot got one with no prompt able to receive it.+ // Resolve the provider's own verb; null = nothing safe to type, so say so+ // rather than sending a command that does nothing.+ const provider = inferAgentProvider(undefined, deps.hiveRegistry().agents?.[r.id]?.provider);+ const command = clearCommandForProvider(provider);+ if (!command) {+ return `${r.name} runs on ${provider}, which has no context-clear command I can type. Clear it from their terminal.`;+ }+ // Queue through the renderer message queue: delivery inherits every existing+ // safety gate (idle-only, boot grace, draft/picker protection).+ deps.enqueueToAgent(r.id, command);attribute(deps, 'clear_context', r.id);return `Queued a context clear for ${r.name} — it lands the moment they're idle.`;};diff --git a/src/main/triggerHistory.ts b/src/main/triggerHistory.tsnew file mode 100644index 00000000..af2a90f8--- /dev/null+++ b/src/main/triggerHistory.ts@@ -0,0 +1,153 @@+/**+ * The trigger ledger on disk — every inbound message a webhook or a peer's clone+ * node pushed at us, and every reply we sent back.+ *+ * It lives in its OWN file rather than in config.json for two reasons: it is+ * append-heavy (config.json is rewritten wholesale on every `writeConfig`, so a+ * growing array in it would make every unrelated settings write more expensive),+ * and it is disposable — losing history must never be able to cost the user their+ * settings. Structurally it follows config.ts: sync fs, mkdirSync-on-write, and a+ * try/catch around every disk touch that degrades to an empty ledger. Nothing here+ * throws at its caller, because the caller is always on a request path where+ * failing to RECORD an event must not fail the event itself.+ *+ * SECURITY — NEVER write a secret, API key or token into an entry. The ledger is+ * plaintext JSON in userData and is surfaced verbatim in the UI, so a webhook+ * secret or an org apiKey landing here would be a durable leak of a live+ * credential. Entries are therefore built FIELD BY FIELD below rather than by+ * spreading the caller's object: a caller that hands us a whole `WebhookTrigger`+ * (which carries `secret`) still gets only the ledger fields persisted.+ */+import { app } from 'electron';+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { randomBytes } from 'node:crypto';+import {+ TRIGGER_HISTORY_LIMIT,+ type InboundKind,+ type TriggerHistoryEntry+} from '../shared/triggers';++/** What a caller must supply; `id` and `at` are stamped for them unless the+ * caller has its own (a replayed/reconstructed entry keeps its identity). */+export type TriggerHistoryInput =+ Omit<TriggerHistoryEntry, 'id' | 'at'> & { id?: string; at?: number };++/** Only these may be changed after the fact. The ledger is append-only in spirit:+ * an entry's source, direction and body are the record of what happened and are+ * not rewritable — the mutable part is the operator's verdict on it. */+export type TriggerHistoryPatch = Partial<+ Pick<TriggerHistoryEntry, 'decision' | 'taskId' | 'correlationId' | 'title'>+>;++function historyPath(): string {+ return join(app.getPath('userData'), 'trigger-history.json');+}++/** Newest first ON DISK as well as in memory. `listTriggerHistory` is the hot+ * path (the UI re-reads it on every render of the Triggers tab) and the cap is+ * enforced on every append, so keeping the file in display order makes both a+ * slice instead of a sort. */+function readAll(): TriggerHistoryEntry[] {+ const p = historyPath();+ if (!existsSync(p)) return [];+ try {+ const parsed = JSON.parse(readFileSync(p, 'utf8'));+ if (!Array.isArray(parsed)) return [];+ return parsed.filter(isEntry);+ } catch {+ return [];+ }+}++function writeAll(entries: TriggerHistoryEntry[]): void {+ try {+ const p = historyPath();+ mkdirSync(dirname(p), { recursive: true });+ writeFileSync(p, JSON.stringify(entries, null, 2), 'utf8');+ } catch { /* best-effort; a ledger write must never fail the event it records */ }+}++/** Structural guard for one persisted row. A hand-edited or partially-written+ * file drops the bad rows rather than the whole ledger. */+function isEntry(v: unknown): v is TriggerHistoryEntry {+ if (!v || typeof v !== 'object') return false;+ const e = v as Partial<TriggerHistoryEntry>;+ return typeof e.id === 'string'+ && (e.source === 'webhook' || e.source === 'org')+ && (e.direction === 'inbound' || e.direction === 'outbound')+ && typeof e.body === 'string'+ && typeof e.at === 'number';+}++function normaliseKind(kind: unknown): InboundKind {+ return kind === 'communication' ? 'communication' : 'directive';+}++/**+ * Record one event and return the row as persisted (the caller usually needs the+ * generated `id` so it can flip a `pending` decision later).+ *+ * The returned entry is what went to disk, so callers never have to guess how+ * their input was normalised.+ */+export function appendTriggerHistory(input: TriggerHistoryInput): TriggerHistoryEntry {+ // Explicit field list — see the SECURITY note at the top of this file.+ const entry: TriggerHistoryEntry = {+ id: input.id ?? randomBytes(8).toString('hex'),+ source: input.source,+ sourceId: input.sourceId,+ sourceName: input.sourceName,+ direction: input.direction,+ peer: input.peer,+ title: input.title,+ body: input.body,+ kind: normaliseKind(input.kind),+ decision: input.decision,+ correlationId: input.correlationId,+ taskId: input.taskId,+ at: input.at ?? Date.now()+ };+ writeAll([entry, ...readAll()].slice(0, TRIGGER_HISTORY_LIMIT));+ return entry;+}++/** The whole ledger, newest first. */+export function listTriggerHistory(): TriggerHistoryEntry[] {+ return readAll();+}++/**+ * Amend one entry's verdict — the `pending` → `approved`/`rejected` transition+ * when the operator answers a strict-mode message, plus the `taskId` of whatever+ * the approval spawned. Returns null when the id is gone, which is a normal+ * outcome: the entry may have aged past TRIGGER_HISTORY_LIMIT while the operator+ * was deciding, and that is not an error worth throwing over.+ */+export function updateTriggerHistory(+ id: string,+ patch: TriggerHistoryPatch+): TriggerHistoryEntry | null {+ const all = readAll();+ const i = all.findIndex((e) => e.id === id);+ if (i < 0) return null;+ const next: TriggerHistoryEntry = { ...all[i] };+ if (patch.decision !== undefined) next.decision = patch.decision;+ if (patch.taskId !== undefined) next.taskId = patch.taskId;+ if (patch.correlationId !== undefined) next.correlationId = patch.correlationId;+ if (patch.title !== undefined) next.title = patch.title;+ all[i] = next;+ writeAll(all);+ return next;+}++/** Wipe the ledger, or just one source's half of it (clearing webhook noise+ * should not throw away the org conversation, and vice versa). Removing the file+ * outright on a full clear keeps a stale-but-unreadable file from lingering. */+export function clearTriggerHistory(source?: 'webhook' | 'org'): void {+ if (!source) {+ try { rmSync(historyPath(), { force: true }); } catch { /* best-effort */ }+ return;+ }+ writeAll(readAll().filter((e) => e.source !== source));+}diff --git a/src/main/webhook.ts b/src/main/webhook.tsindex 14d8c3e4..01346f35 100644--- a/src/main/webhook.ts+++ b/src/main/webhook.ts@@ -1,49 +1,98 @@/**- * WebhookServer — a generic, secret-gated inbound HTTP API that turns an external- * POST into hive work and lets the caller poll that work's status by a token.+ * WebhookServer — a generic, secret-gated inbound HTTP API that turns external+ * POSTs into hive work and lets each caller poll that work's status by a token.*- * Modeled on `SlackWebhookServer` (same zero-SDK `node:http` + `tunnelmole`- * approach) but for arbitrary callers rather than Slack's Events API:- * - POST <endpoint> + `x-md-webhook-secret: <secret>` + JSON `{ message, title? }`- * → routes the message to god/Michael, creates a stamped kanban card, and- * returns a freshly-minted capability TOKEN: `{ ok, token, taskId }`.- * - GET <endpoint> + `x-md-webhook-token: <token>` (or `?token=`)+ * MANY endpoints, ONE server, ONE tunnel. Endpoints are told apart by the id in+ * the request path, so adding a webhook costs no extra port and no extra tunnel:+ * - POST /<webhookId> + `x-md-webhook-secret: <that endpoint's secret>`+ * + JSON body matching THAT endpoint's user-editable schema+ * → 200 `{ ok, token, taskId }` when the endpoint's TriggerMode lets the+ * message through (routed to god, kanban card created), or+ * → 202 `{ ok, pending: true, token, status: 'awaiting-approval' }` when the+ * mode holds it for the operator. Either way the caller gets its token.+ * - GET /<webhookId> + `x-md-webhook-token: <token>` (or `?token=`)* → returns ONLY that token's task status: `{ ok, status, title, result? }`.+ * - POST / (bare) is an alias for the endpoint with id `legacy`, so a caller+ * holding the pre-multi-endpoint URL keeps working across the upgrade.** SECURITY — this is a PUBLIC surface (tunnel-forwarded), unlike the loopback- * /reply endpoint, so the gate is strict:- * - constant-time secret comparison (`timingSafeEqual`, length-guarded),- * - the secret is read from options and NEVER logged, echoed, or forwarded into- * the routed message / card / response,- * - the capability token is unguessable (generated by the caller-side handler,- * 192-bit) and a GET reveals only the single task it maps to — no listing or- * enumeration of other work,- * - a request body cap + a basic fixed-window rate limit bound abuse before any- * parsing or crypto runs.+ * /reply endpoint, so the gate is strict. Every property of the single-endpoint+ * version is preserved, plus the ones multi-tenancy adds:+ * - constant-time secret comparison (`timingSafeEqual`, length-guarded), against+ * THAT endpoint's secret only — revoking one endpoint cannot affect another,+ * - an UNKNOWN endpoint id is answered exactly like a WRONG secret: the compare+ * still runs (against an unguessable per-process decoy) and the reply is the+ * same 401 body, so the surface can't be walked to discover which ids exist,+ * - GET does its token lookup whether or not the id is known, for the same+ * reason: identical work, identical 404 — no enumeration signal,+ * - secrets are held only in this class, and NEVER logged, echoed, or forwarded+ * into the routed message / card / response (the handler is handed `{id,name}`,+ * not the endpoint record),+ * - the capability token is unguessable (minted by the caller-side handler,+ * 192-bit) and a GET reveals only the single task it maps to — no listing,+ * - a request body cap + fixed-window rate limits (GLOBAL *and* per-endpoint, so+ * one noisy caller can't starve the others) bound abuse before parsing/crypto.** Runs in the Electron main process. Deliberately free of any `electron` import so* it can be unit-/smoke-tested as a plain Node module. The actual card creation +* god routing + token→status lookup are injected as callbacks (they need hive* access, which lives in the main entrypoint); this class owns only transport,- * the secret gate, rate limiting, and the tunnel.+ * the secret gate, schema validation, rate limiting, and the tunnel.*/import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';-import { timingSafeEqual } from 'node:crypto';+import { randomBytes, timingSafeEqual } from 'node:crypto';+import { validateAgainstSchema, type InboundKind } from '../shared/triggers';// NOTE: `tunnelmole` is an ESM-only package. The Electron main process is bundled// as CommonJS, so a static `import` gets externalized into `require('tunnelmole')`// and throws ERR_REQUIRE_ESM at load. It is imported dynamically inside// `openTunnel()` instead — Rollup preserves dynamic import() in CJS output, which// can load ESM. Do not hoist this back to a top-level import.-/** The validated body of an accepted POST — just the work to do. The secret has- * already been verified and is intentionally NOT part of this shape, so it can- * never be forwarded onward. */+/** One servable endpoint — the structural subset of `WebhookTrigger` this class+ * needs. A whole `WebhookTrigger` is assignable, so callers pass config rows+ * straight in without a mapping step. */+export interface WebhookEndpoint {+ id: string;+ name: string;+ /** Shared secret the caller echoes in `x-md-webhook-secret`. Never leaves this class. */+ secret: string;+ /** User-editable JSON Schema (serialised) inbound bodies are checked against. */+ schema: string;+}++/** What the dispatch handler is told about the endpoint a message arrived on.+ * DELIBERATELY excludes `secret`: the handler writes cards, hive messages and+ * history rows, and none of them may ever be able to carry a live credential. */+export interface WebhookEndpointRef {+ id: string;+ name: string;+}++/** The validated body of an accepted POST — just the work to do plus the sender's+ * own framing of it. The secret has already been verified and is intentionally+ * NOT part of this shape, so it can never be forwarded onward. */export interface WebhookInbound {message: string;title?: string;+ /** Declared by the caller when they bothered to; the handler classifies when not. */+ kind?: InboundKind;+ /** Who is sending, for the trigger history. Falls back to the endpoint name. */+ from?: string;}-/** What a GET exposes for a token — mirrors the kanban's public columns only. */+/** What the handler did with an accepted message. `pending` is the whole point of+ * the split: the caller is told, honestly, whether work actually started. */+export interface WebhookDispatch {+ /** Capability token to hand back — the ONLY echo, and only ever returned once. */+ token: string;+ /** Kanban card id; absent while a message waits for the operator (no card yet). */+ taskId?: string;+ /** true = held for operator approval (→ 202), false = routed to god (→ 200). */+ pending: boolean;+}++/** What a GET exposes for a token — mirrors the kanban's public columns only,+ * plus the synthetic statuses a held message reports before it becomes work. */export interface WebhookTaskStatus {status: string;title: string;@@ -53,15 +102,14 @@ export interface WebhookTaskStatus {export interface WebhookServerOptions {/** Local TCP port the HTTP server binds to (and the tunnel forwards to). */port: number;- /** Shared secret the caller must echo in `x-md-webhook-secret`. Required. */- secret: string;+ /** The endpoints to serve. May be swapped later with `setEndpoints`. */+ endpoints: WebhookEndpoint[];/**- * Turn a verified POST into hive work. MUST create the kanban card + route to- * god and return the capability token to hand back (plus the card id). Return- * null to signal a server-side failure (→ 500). The token it returns is the- * ONLY thing echoed to the caller; the secret never reaches here.+ * Turn a verified POST into hive work (or into a held message awaiting the+ * operator). Return null to signal a server-side failure (→ 500). The token it+ * returns is the ONLY thing echoed to the caller; no secret ever reaches here.*/- onMessage: (msg: WebhookInbound) => { token: string; taskId: string } | null;+ onMessage: (msg: WebhookInbound, endpoint: WebhookEndpointRef) => WebhookDispatch | null;/*** Resolve a capability token to its task's public status, or null when the* token maps to nothing (→ 404). MUST be scoped to the one token — it must@@ -77,25 +125,80 @@ const MAX_BODY_BYTES = 1024 * 1024; // 1 MBconst TUNNEL_START_TIMEOUT_MS = 10_000;/** Basic abuse guard: at most this many requests per fixed window, globally. */const RATE_LIMIT = 120;+/** …and this many per endpoint, so one noisy caller burns its own budget first+ * instead of everyone's. Strictly below the global cap, or it would never bind. */+const PER_ENDPOINT_RATE_LIMIT = 60;const RATE_WINDOW_MS = 60_000;+/** Bare `POST /` keeps serving the endpoint the pre-multi-endpoint migration+ * parked under this id, so a caller already pointed at the old URL is unaffected. */+export const LEGACY_ENDPOINT_ID = 'legacy';++/** Rate-limit bucket shared by EVERY unknown id. One bucket, not one per id:+ * per-id buckets for ids we don't serve would let a prober both grow our memory+ * unboundedly and — worse — observe that unknown ids never hit the per-endpoint+ * limit while real ones do. Sharing one bucket makes the two indistinguishable. */+const UNKNOWN_BUCKET = ':unknown';+export class WebhookServer {private server: Server | null = null;private tunnelUrl: string | null = null;private readonly port: number;- private readonly secret: string;- private readonly onMessage: (msg: WebhookInbound) => { token: string; taskId: string } | null;+ private endpoints = new Map<string, WebhookEndpoint>();+ private readonly onMessage: (msg: WebhookInbound, endpoint: WebhookEndpointRef) => WebhookDispatch | null;private readonly lookupStatus: (token: string) => WebhookTaskStatus | null;- // Fixed-window rate limiter (global; the remote IP is the tunnel's, so per-IP- // would be meaningless behind tunnelmole).- private windowStart = 0;- private windowCount = 0;+ /** Compared against when the requested id doesn't exist, purely so the failure+ * path does the same work as a wrong-secret failure. Random per process and+ * never exported, so it cannot be matched even by accident. */+ private readonly decoySecret = randomBytes(32).toString('hex');+ // Fixed-window rate limiters keyed by bucket ('' = global, else the endpoint id).+ // The remote IP is the tunnel's, so per-IP would be meaningless behind tunnelmole.+ private windows = new Map<string, { start: number; count: number }>();constructor(opts: WebhookServerOptions) {this.port = opts.port;- this.secret = opts.secret;this.onMessage = opts.onMessage;this.lookupStatus = opts.lookupStatus;+ this.setEndpoints(opts.endpoints);+ }++ /**+ * Swap the served endpoint list WITHOUT restarting the server or the tunnel —+ * the operator adds, edits and revokes webhooks from the UI, and a restart would+ * mint a fresh (ephemeral) tunnel URL, silently breaking every caller of every+ * OTHER endpoint. The map is rebuilt wholesale so a removed id stops resolving+ * on the very next request.+ */+ setEndpoints(list: WebhookEndpoint[]): void {+ const next = new Map<string, WebhookEndpoint>();+ for (const e of list) {+ if (!e || typeof e.id !== 'string' || !e.id || typeof e.secret !== 'string' || !e.secret) continue;+ next.set(e.id, e);+ }+ this.endpoints = next;+ // Drop rate-limit state for ids we no longer serve; keep the global and+ // unknown buckets so a swap can't be used to reset an in-flight flood.+ for (const key of [...this.windows.keys()]) {+ if (key === '' || key === UNKNOWN_BUCKET) continue;+ if (!next.has(key)) this.windows.delete(key);+ }+ }++ /** Ids currently served, for the settings surface that shows per-endpoint URLs. */+ endpointIds(): string[] {+ return [...this.endpoints.keys()];+ }++ /** The public tunnel URL, or null when no tunnel is up. */+ publicUrl(): string | null {+ return this.tunnelUrl;+ }++ /** Is the local HTTP server bound? `start()` reports ok:false for a tunnel+ * failure too, and in THAT case the security boundary is still live — the+ * caller must keep the instance (or the listener leaks, unstoppable). */+ listening(): boolean {+ return this.server != null;}/**@@ -106,7 +209,7 @@ export class WebhookServer {*/async start(): Promise<{ ok: boolean; url?: string; error?: string }> {if (this.server) return { ok: false, error: 'already running' };- if (!this.secret) return { ok: false, error: 'missing webhook secret' };+ if (this.endpoints.size === 0) return { ok: false, error: 'no enabled webhook endpoints' };try {await this.listen();} catch (e) {@@ -159,40 +262,58 @@ export class WebhookServer {}/** Fixed-window limiter — bounds total work before any parse/crypto runs. */- private allowRequest(): boolean {+ private allowRequest(bucket: string, limit: number): boolean {const now = Date.now();- if (now - this.windowStart > RATE_WINDOW_MS) { this.windowStart = now; this.windowCount = 0; }- this.windowCount += 1;- return this.windowCount <= RATE_LIMIT;+ const w = this.windows.get(bucket);+ if (!w || now - w.start > RATE_WINDOW_MS) {+ this.windows.set(bucket, { start: now, count: 1 });+ return true;+ }+ w.count += 1;+ return w.count <= limit;}private handleRequest(req: IncomingMessage, res: ServerResponse): void {// Rate limit first — cheapest possible rejection, ahead of any work.- if (!this.allowRequest()) { json(res, 429, { ok: false, error: 'rate limited' }); return; }+ if (!this.allowRequest('', RATE_LIMIT)) { json(res, 429, { ok: false, error: 'rate limited' }); return; }+ const id = readEndpointId(req);+ const endpoint = id !== null ? this.endpoints.get(id) ?? null : null;+ // Per-endpoint budget, with every unknown id sharing one bucket (see UNKNOWN_BUCKET).+ if (!this.allowRequest(endpoint ? endpoint.id : UNKNOWN_BUCKET, PER_ENDPOINT_RATE_LIMIT)) {+ json(res, 429, { ok: false, error: 'rate limited' }); return;+ }const method = req.method ?? '';- if (method === 'GET') { this.handleStatus(req, res); return; }- if (method === 'POST') { this.handleCreate(req, res); return; }+ if (method === 'GET') { this.handleStatus(req, res, endpoint); return; }+ if (method === 'POST') { this.handleCreate(req, res, endpoint); return; }res.writeHead(405); res.end();}- /** GET — return the status of the token's task (token only; never a listing). */- private handleStatus(req: IncomingMessage, res: ServerResponse): void {+ /**+ * GET — return the status of the token's task (token only; never a listing).+ *+ * The lookup runs even when the id is unknown, and the answer is then the same+ * 404 the unknown-token case gives. Skipping the lookup would make "no such+ * webhook" measurably cheaper than "no such token", which is exactly the signal+ * an id-enumeration probe is looking for.+ */+ private handleStatus(req: IncomingMessage, res: ServerResponse, endpoint: WebhookEndpoint | null): void {const token = readToken(req);if (!token) { json(res, 401, { ok: false, error: 'token required' }); return; }let status: WebhookTaskStatus | null = null;try { status = this.lookupStatus(token); }catch { json(res, 500, { ok: false, error: 'lookup failed' }); return; }- // 404 for an unknown token — identical to a malformed one, so a probe can't- // distinguish "valid but unknown" from "wrong shape" (no enumeration signal).- if (!status) { json(res, 404, { ok: false, error: 'not found' }); return; }+ // 404 for an unknown token — identical to a malformed one and to an unknown+ // endpoint id, so a probe can't distinguish any of the three (no enumeration).+ if (!status || !endpoint) { json(res, 404, { ok: false, error: 'not found' }); return; }json(res, 200, { ok: true, status: status.status, title: status.title, result: status.result ?? null });}- /** POST — verify the secret, then buffer + dispatch the JSON body. */- private handleCreate(req: IncomingMessage, res: ServerResponse): void {+ /** POST — verify this endpoint's secret, then buffer + validate + dispatch. */+ private handleCreate(req: IncomingMessage, res: ServerResponse, endpoint: WebhookEndpoint | null): void {// Authenticate BEFORE reading the body so an unauthenticated peer can't even- // make us buffer (within the size cap). 401 on any failure — no detail leaked.- if (!this.verifySecret(req)) { json(res, 401, { ok: false, error: 'unauthorized' }); return; }+ // make us buffer (within the size cap). 401 on any failure — no detail leaked,+ // and an unknown id lands here too so it is answered identically.+ if (!this.verifySecret(req, endpoint) || !endpoint) { json(res, 401, { ok: false, error: 'unauthorized' }); return; }const chunks: Buffer[] = [];let size = 0;@@ -205,36 +326,94 @@ export class WebhookServer {});req.on('end', () => {if (aborted) return;- let parsed: { message?: unknown; title?: unknown };+ let parsed: unknown;try { parsed = JSON.parse(Buffer.concat(chunks).toString('utf8')); }catch { json(res, 400, { ok: false, error: 'bad json' }); return; }- const message = typeof parsed.message === 'string' ? parsed.message.trim() : '';++ // The endpoint's own schema decides what a valid body is. Echoing the+ // validator's message is safe: it describes the CALLER's payload and can+ // never contain our secret (the schema is the operator's own document).+ const check = validateAgainstSchema(parsed, parseSchema(endpoint.schema));+ if (!check.ok) { json(res, 400, { ok: false, error: check.error }); return; }++ const body = (parsed ?? {}) as Record<string, unknown>;+ // `message` is required regardless of what the user's schema says — it is+ // the one field the router cannot work without, so a schema edited to drop+ // it fails here rather than producing an empty card.+ const message = typeof body.message === 'string' ? body.message.trim() : '';if (!message) { json(res, 400, { ok: false, error: 'message required' }); return; }- const title = typeof parsed.title === 'string' && parsed.title.trim() ? parsed.title.trim() : undefined;- let out: { token: string; taskId: string } | null = null;- try { out = this.onMessage({ message, title }); }+ const inbound: WebhookInbound = { message };+ const title = typeof body.title === 'string' ? body.title.trim() : '';+ if (title) inbound.title = title;+ if (body.kind === 'directive' || body.kind === 'communication') inbound.kind = body.kind;+ const from = typeof body.from === 'string' ? body.from.trim() : '';+ if (from) inbound.from = from;++ let out: WebhookDispatch | null = null;+ try { out = this.onMessage(inbound, { id: endpoint.id, name: endpoint.name }); }catch { json(res, 500, { ok: false, error: 'could not create task' }); return; }if (!out) { json(res, 500, { ok: false, error: 'could not create task' }); return; }+ // 202, not 200: the message was accepted but no work has started. The caller+ // still gets its token so it can poll the hold, and the GET reports the hold+ // honestly rather than pretending a task is queued.+ if (out.pending) {+ json(res, 202, {+ ok: true,+ pending: true,+ status: 'awaiting-approval',+ token: out.token,+ detail: 'accepted — waiting for the operator to approve it before the hive sees it'+ });+ return;+ }json(res, 200, { ok: true, token: out.token, taskId: out.taskId });});req.on('error', () => { if (!aborted) { try { res.writeHead(400); res.end(); } catch { /* socket gone */ } } });}/**- * Constant-time check that `x-md-webhook-secret` equals the configured secret.+ * Constant-time check that `x-md-webhook-secret` equals THIS endpoint's secret.* A length mismatch is itself a failure and short-circuits before the compare* (timingSafeEqual throws on unequal lengths).+ *+ * A null endpoint (unknown id) still runs the comparison, against a decoy no+ * caller can hold, and then fails unconditionally — so "no such webhook" costs+ * the same as "wrong secret" and answers with the same 401.*/- private verifySecret(req: IncomingMessage): boolean {+ private verifySecret(req: IncomingMessage, endpoint: WebhookEndpoint | null): boolean {const provided = req.headers['x-md-webhook-secret'];if (typeof provided !== 'string') return false;const a = Buffer.from(provided);- const b = Buffer.from(this.secret);+ const b = Buffer.from(endpoint ? endpoint.secret : this.decoySecret);if (a.length !== b.length) return false;- return timingSafeEqual(a, b);+ const equal = timingSafeEqual(a, b);+ return endpoint ? equal : false;}}+/**+ * The endpoint id from the request path: `/foo` → `foo`, bare `/` → `legacy`.+ * A deeper path (`/a/b`) resolves to null = "no such endpoint", which is then+ * answered exactly like a wrong secret / unknown token.+ */+function readEndpointId(req: IncomingMessage): string | null {+ let pathname: string;+ try { pathname = new URL(req.url ?? '/', 'http://localhost').pathname; }+ catch { return null; }+ const segments = pathname.split('/').filter((s) => s.length > 0);+ if (segments.length === 0) return LEGACY_ENDPOINT_ID;+ if (segments.length > 1) return null;+ try { return decodeURIComponent(segments[0]); } catch { return segments[0]; }+}++/** Parse the endpoint's stored schema. An unparseable one yields `undefined`,+ * which `validateAgainstSchema` treats as "accept" — a mistyped schema must not+ * lock a caller out of an endpoint they hold a valid secret for. */+function parseSchema(schema: string): unknown {+ if (typeof schema !== 'string' || !schema.trim()) return undefined;+ try { return JSON.parse(schema); } catch { return undefined; }+}+/** Pull the capability token from the `x-md-webhook-token` header, falling back* to a `?token=` query param. Header is preferred (kept out of URL/access logs). */function readToken(req: IncomingMessage): string {diff --git a/src/preload/index.ts b/src/preload/index.tsindex d90bd95e..d1b60db7 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -6,6 +6,12 @@ import type { IntegrationRecord, IntegrationTemplate } from '../shared/integratiexport type { IntegrationRecord, IntegrationTemplate } from '../shared/integrations';import type { UpdateStatus } from '../shared/updateState';export type { UpdateStatus } from '../shared/updateState';+import type {+ ContextRule, ContextTriggerConfig, OrgTriggerConfig, TriggerHistoryEntry, WebhookTrigger+} from '../shared/triggers';+export type {+ ContextRule, ContextTriggerConfig, OrgTriggerConfig, TriggerHistoryEntry, WebhookTrigger+} from '../shared/triggers';/** Renderer-visible integration record: the secretRef handle is redacted to a* presence boolean. Matches main `integrations.listRecordsRedacted()` — the@@ -1067,6 +1073,70 @@ const api = {}): Promise<{ ok: boolean }> =>ipcRenderer.invoke('webhook:setConfig', patch),+ // ─── Triggers: context (auto-compact / auto-clear) ──────────────────────────+ /** The two context rules (cadence + pressure gate + message), deep-filled. */+ getContextTrigger: (): Promise<ContextTriggerConfig> =>+ ipcRenderer.invoke('triggers:getContext'),+ /** Persist both rules and RE-ARM main's timers; resolves to what was stored+ * (main clamps the cadence/percentages, so the echo is authoritative). */+ setContextTrigger: (cfg: ContextTriggerConfig): Promise<ContextTriggerConfig> =>+ ipcRenderer.invoke('triggers:setContext', cfg),+ /** Fires when a context rule comes due. `rule` rides along because main owns+ * only the CADENCE — the renderer applies the per-agent pressure gate and+ * queues the command for each agent that qualifies. */+ onContextTrigger: (cb: (evt: { action: 'compact' | 'clear'; rule: ContextRule }) => void): (() => void) => {+ const listener = (_e: IpcRendererEvent, payload: { action: 'compact' | 'clear'; rule: ContextRule }) => cb(payload);+ ipcRenderer.on('trigger:context', listener);+ return () => ipcRenderer.removeListener('trigger:context', listener);+ },++ // ─── Triggers: webhook endpoints (many endpoints, one server + tunnel) ──────+ /** Every configured endpoint, enabled or not. */+ listWebhooks: (): Promise<WebhookTrigger[]> => ipcRenderer.invoke('webhooks:list'),+ /** Replace the whole list; main normalises each row (a blank secret keeps the+ * stored one, an unknown mode keeps the stored one) and hot-swaps the running+ * server's endpoints WITHOUT a restart, so no other caller's URL changes. */+ saveWebhooks: (list: WebhookTrigger[]): Promise<WebhookTrigger[]> =>+ ipcRenderer.invoke('webhooks:save', list),+ /** Revoke one endpoint; resolves to the remaining list. */+ deleteWebhook: (id: string): Promise<WebhookTrigger[]> =>+ ipcRenderer.invoke('webhooks:delete', id),+ /** Mint a 256-bit secret for the operator to paste into their caller. Not+ * persisted until the endpoint carrying it is saved. */+ generateWebhookSecret: (): Promise<string> => ipcRenderer.invoke('webhooks:generateSecret'),+ /** Server state, the tunnel root, and each endpoint's full public URL (`url` is+ * '' until a tunnel has come up). */+ webhooksStatus: (): Promise<{ running: boolean; url?: string; endpoints: { id: string; url: string }[] }> =>+ ipcRenderer.invoke('webhooks:status'),++ // ─── Triggers: organisation (clone-node peer messaging) ─────────────────────+ /** PERSISTENCE ONLY — the peer transport does not exist yet, so setting this+ * stores the key and mode and starts nothing. */+ getOrgTrigger: (): Promise<OrgTriggerConfig> => ipcRenderer.invoke('org:getTrigger'),+ setOrgTrigger: (cfg: OrgTriggerConfig): Promise<OrgTriggerConfig> =>+ ipcRenderer.invoke('org:setTrigger', cfg),++ // ─── Triggers: history ledger + approval gate ───────────────────────────────+ /** The whole ledger, newest first (both directions, both sources). */+ listTriggerHistory: (): Promise<TriggerHistoryEntry[]> =>+ ipcRenderer.invoke('triggerHistory:list'),+ /** Answer a held message. 'approved' RELEASES it to the hive (card + god+ * request, the same path an auto-allowed message takes); 'rejected' only flips+ * the verdict. Deciding an already-decided entry is a no-op, never a second+ * dispatch. Resolves to the updated row, or null when the id is gone. */+ decideTriggerHistory: (arg: { id: string; decision: 'approved' | 'rejected' }): Promise<TriggerHistoryEntry | null> =>+ ipcRenderer.invoke('triggerHistory:decide', arg),+ /** Wipe the ledger, or just one source's half of it. */+ clearTriggerHistory: (source?: 'webhook' | 'org'): Promise<void> =>+ ipcRenderer.invoke('triggerHistory:clear', source),+ /** Fires whenever the ledger changes (an inbound arrived, a verdict landed, a+ * reply was paired), so the history tab live-refreshes. */+ onTriggerHistoryUpdated: (cb: () => void): (() => void) => {+ const listener = (): void => cb();+ ipcRenderer.on('triggerHistory:updated', listener);+ return () => ipcRenderer.removeListener('triggerHistory:updated', listener);+ },+// ─── Free Flow (voice dictation → message queue) ─────────────────────────────/** Persist Free Flow settings (flag / Groq key / model). The Groq key is stored* in main config; entry point B (hold-Option) is renderer-side, no hotkey here. */diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsxindex 5d7aa1b5..9ac4f7ff 100644--- a/src/renderer/src/App.tsx+++ b/src/renderer/src/App.tsx@@ -2,6 +2,7 @@ import { useEffect, useState } from 'react';import { useStore, selectedAgent } from '@/store/store';import { startMockLoop, stopMockLoop } from '@/store/mockEvents';import type { HarnessConfig } from '@/store/config';+import { DEFAULT_ORG_TRIGGER } from '@shared/triggers';import { OfficeFloor } from '@/scene/office/OfficeFloor';import { useHive } from '@/hooks/useHive';import { MemoryPanel } from '@/components/MemoryPanel';@@ -82,6 +83,16 @@ export function App() {// Mirror the active office theme so OfficeFloor renders it (gated on the// tvShowOffices flag; off = always the office). Settings keeps this synced.useStore.getState().setOfficeTheme(c.tvShowOffices ? (c.officeTheme ?? 'office') : 'office');+ // Mirror the triggers so Settings → Connections and the Command Center's+ // Triggers tab read one list, not two copies that drift — whichever surface+ // saves calls these same setters and the other repaints. No extra IPC: main+ // deep-fills both fields on every config read (withTriggerDefaults), so+ // getConfig() already serves what listWebhooks()/getOrgTrigger() would.+ // `c` is typed as the PRELOAD's HarnessConfig, which hasn't picked the two+ // fields up yet (another lane's file); the renderer mirror type declares them.+ const withTriggers = c as HarnessConfig;+ useStore.getState().setWebhookTriggers(withTriggers.webhookTriggers ?? []);+ useStore.getState().setOrgTrigger(withTriggers.orgTrigger ?? DEFAULT_ORG_TRIGGER);});// Mirror BYOK OpenAI key presence (boolean only; the key never leaves main) so the// Realtime Michael voice toggle can gate on it. Lives in the secret broker, notdiff --git a/src/renderer/src/components/CommandCenterPanel.tsx b/src/renderer/src/components/CommandCenterPanel.tsxindex f59501cc..9353d608 100644--- a/src/renderer/src/components/CommandCenterPanel.tsx+++ b/src/renderer/src/components/CommandCenterPanel.tsx@@ -7,7 +7,8 @@ import { PtyTerminalView } from './PtyTerminalView';import { MessageQueueComposer } from './MessageQueueComposer';import { TasksKanban } from './TasksKanban';import { AskMeTab } from './AskMeTab';-import { SchedulesTab } from './SchedulesTab';+import { TriggersTab } from './triggers/TriggersTab';+import { TriggerHistoryTab } from './triggers/TriggerHistoryTab';import { WorkersTab } from './WorkersTab';import { acquireTerminal, disposeTerminal, resetTerminal } from './terminalPool';import { terminalInstanceKey } from './terminalRecovery';@@ -15,7 +16,7 @@ import { Icon } from './Icon';import { MemoryGraphPanel } from './MemoryGraphPanel';import { useFleetTelemetry } from '@/hooks/useTelemetry';import { COMMAND_GROUPS } from '@shared/claudeCommands';-import { useStore, type Agent } from '@/store/store';+import { useStore, triggerHistoryVisible, type Agent } from '@/store/store';import { usePtyParser } from '@/hooks/usePtyParser';import {buildSpawnCommand,@@ -37,9 +38,11 @@ import { canReceiveInbox } from '@shared/agentProvider';* per-agent model + dispatch + assistant access), a memory view, and a live* activity feed / board / usage meter. */-// Both the AskMe (#human) tab and the Schedules (#50) tab live here. The inline-// SCHEDULES section + its ScheduledMission/relTime helpers moved into SchedulesTab.-type CCTab = 'terminal' | 'floor' | 'tasks' | 'human' | 'schedules' | 'memory' | 'graph' | 'activity' | 'handbook' | 'workers';+// Both the AskMe (#human) tab and the Triggers tab live here. Triggers replaced+// the old Schedules tab: schedules are now one of four trigger types, and the+// whole surface lives in ./triggers (see src/shared/triggers.ts for the contract).+type CCTab = 'terminal' | 'floor' | 'tasks' | 'human' | 'triggers' | 'trigger-history'+ | 'memory' | 'graph' | 'activity' | 'handbook' | 'workers';/** Fallback denominator for the per-agent token meter when no floor token budget* is configured — so the bar reads as a budget estimate (filled + remaining)@@ -56,12 +59,14 @@ interface GHIssue {assignees: string[];}+/** Canonical tab order. Not every entry is always shown — see `visibleTabs`. */const TABS: { key: CCTab; label: string; icon: Parameters<typeof Icon>[0]['name'] }[] = [{ key: 'terminal', label: 'terminal', icon: 'terminal' },{ key: 'floor', label: 'monitor', icon: 'mcp' },{ key: 'tasks', label: 'tasks', icon: 'check' },{ key: 'human', label: 'ask me', icon: 'bell' },- { key: 'schedules', label: 'schedules', icon: 'clock' },+ { key: 'triggers', label: 'triggers', icon: 'clock' },+ { key: 'trigger-history', label: 'history', icon: 'ledger' },{ key: 'memory', label: 'memory', icon: 'sparkle' },{ key: 'graph', label: 'graph', icon: 'web' },{ key: 'activity', label: 'activity', icon: 'bell' },@@ -75,14 +80,31 @@ const TABS: { key: CCTab; label: string; icon: Parameters<typeof Icon>[0]['name'* cols/rows and corrupt the display. */export function CommandCenterPanel({ agent, fullscreen = false }: { agent: Agent; fullscreen?: boolean }) {const [tab, setTab] = useState<CCTab>('terminal');+ // The trigger-history ledger has nothing to say until an outside party can+ // reach us, so its tab appears only once an org key or a webhook exists. This+ // is the first config-gated tab in the panel: TABS stays the canonical order+ // and the gate is applied at render, so nothing else has to know about it.+ // The rule itself lives in the store (`triggerHistoryVisible`) beside the two+ // mirrors it reads — a second copy here would drift from Settings.+ const showHistory = useStore(triggerHistoryVisible);+ // Never leave the panel parked on a tab that has just been hidden.+ useEffect(() => {+ if (!showHistory && tab === 'trigger-history') setTab('terminal');+ }, [showHistory, tab]);+ const visibleTabs = TABS.filter((t) => t.key !== 'trigger-history' || showHistory);+// External tab requests (the office task board → 'tasks', the boss-room- // calendar → 'schedules'). seq-keyed so clicking again re-opens the tab even+ // calendar → 'triggers'). seq-keyed so clicking again re-opens the tab even// if it was already requested.const ccTabRequest = useStore((s) => s.ccTabRequest);useEffect(() => {- if (ccTabRequest && TABS.some((t) => t.key === ccTabRequest.tab)) {- setTab(ccTabRequest.tab as CCTab);- }+ if (!ccTabRequest) return;+ const key = ccTabRequest.tab as CCTab;+ if (!TABS.some((t) => t.key === key)) return;+ // Read the gate live rather than depending on it — as a dependency it would+ // re-fire a stale request the moment the tab appeared.+ if (key === 'trigger-history' && !triggerHistoryVisible(useStore.getState())) return;+ setTab(key);}, [ccTabRequest]);// A task-detail "assign" pre-fills the Floor dispatch box and jumps to it.// Seeded via the store one-shot (the detail overlay lives app-wide now);@@ -193,7 +215,7 @@ export function CommandCenterPanel({ agent, fullscreen = false }: { agent: Agentpadding: '6px 8px', background: 'var(--cth-cream-100)',borderBottom: '1px solid var(--cth-ink-700)', flexShrink: 0}}>- {TABS.map((t) => (+ {visibleTabs.map((t) => (<buttonkey={t.key}onClick={() => setTab(t.key)}@@ -247,7 +269,8 @@ export function CommandCenterPanel({ agent, fullscreen = false }: { agent: Agent{tab === 'floor' && <FloorTab seed={dispatchSeed} />}{tab === 'tasks' && <TasksKanban />}{tab === 'human' && <AskMeTab />}- {tab === 'schedules' && <SchedulesTab />}+ {tab === 'triggers' && <TriggersTab />}+ {tab === 'trigger-history' && <TriggerHistoryTab />}{tab === 'memory' && (<MemoryTab godId={agent.id} who={selectedMemoryAgent ?? undefined} onWho={setSelectedMemoryAgent} />)}diff --git a/src/renderer/src/components/FullscreenTerminal.tsx b/src/renderer/src/components/FullscreenTerminal.tsxindex a7b85d81..2056d7d7 100644--- a/src/renderer/src/components/FullscreenTerminal.tsx+++ b/src/renderer/src/components/FullscreenTerminal.tsx@@ -453,7 +453,7 @@ export function FullscreenTerminal({ config }: FullscreenTerminalProps) {}}>{agent.isGod ? (// Michael runs the floor from the command center — its tabs (tasks,- // ask me, schedules, memory, graph…) are the whole point of selecting+ // ask me, triggers, memory, graph…) are the whole point of selecting// him, and fullscreen used to drop them for a bare terminal.// Column so the panel's `height: 100%` resolves against a definite// height and `align-items: stretch` gives it the full width.diff --git a/src/renderer/src/components/HivePicker.tsx b/src/renderer/src/components/HivePicker.tsxindex c5905caf..d57819fb 100644--- a/src/renderer/src/components/HivePicker.tsx+++ b/src/renderer/src/components/HivePicker.tsx@@ -78,7 +78,7 @@ export function HivePicker({ config, onOpenCurrent }: HivePickerProps) {<div style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 14 }}><p style={{ margin: 0, fontSize: 12, lineHeight: '19px', color: 'var(--cth-ink-700)' }}>A <strong>harness config</strong> is the folder where the app keeps everything for one- workspace — its settings, your agents and their memory, tasks, schedules, and history.+ workspace — its settings, your agents and their memory, tasks, triggers, and history.Each config is separate and self-contained, so you can run different setups side by side.Open the one you were working in, switch to another, or start a new one.</p>diff --git a/src/renderer/src/components/Icon.tsx b/src/renderer/src/components/Icon.tsxindex 61eaeaea..ee841b3c 100644--- a/src/renderer/src/components/Icon.tsx+++ b/src/renderer/src/components/Icon.tsx@@ -6,7 +6,7 @@ import { CSSProperties } from 'react';export type IconName =| 'gear' | 'plus' | 'x' | 'check' | 'arrow-right' | 'pause' | 'play'| 'bell' | 'folder' | 'terminal' | 'code' | 'web' | 'mcp' | 'sparkle'- | 'expand' | 'minimize' | 'clock' | 'mic';+ | 'expand' | 'minimize' | 'clock' | 'mic' | 'ledger';interface IconDef {ink: string; // primary color path d@@ -88,6 +88,12 @@ const paths: Record<IconName, IconDef> = {accentColor: 'var(--cth-lemon)',ink: 'M5 1h6v1h2v2h1v2h1v4h-1v2h-1v2h-2v1H5v-1H3v-2H2V8H1V6h1V4h1V2h2V1zm0 2H4v1H3v2H2v4h1v2h1v1h1v1h6v-1h1v-1h1v-2h1V6h-1V4h-1V3h-1V2H5v1zm2 1h2v4h2v1h1v1h-1v1h-1v-1H9v1H7V4z'},+ // Ruled page — the trigger-history ledger. Frame as an evenodd cutout, three+ // written lines inside it (the last one short, like a part-filled entry).+ ledger: {+ accentColor: 'var(--cth-lemon)',+ ink: 'M2 1h12v14H2V1zM3 2v12h10V2H3zM5 4h6v1H5zM5 7h6v1H5zM5 10h4v1H5z'+ },// Microphone: a solid capsule head, an open cradle, a stem, and a base.mic: {accentColor: 'var(--cth-coral)',diff --git a/src/renderer/src/components/OnboardingWizard.tsx b/src/renderer/src/components/OnboardingWizard.tsxindex 0f33b316..04a9632a 100644--- a/src/renderer/src/components/OnboardingWizard.tsx+++ b/src/renderer/src/components/OnboardingWizard.tsx@@ -50,8 +50,8 @@ const FEATURES: Feature[] = [{icon: 'terminal',label: 'COMMAND CENTER',- desc: 'Terminal · Floor · Memory · Activity · Tasks · Schedules in one control surface.',- descPlain: "One dashboard to watch the work, the agents' memory, tasks, and schedules.",+ desc: 'Terminal · Floor · Memory · Activity · Tasks · Triggers in one control surface.',+ descPlain: "One dashboard to watch the work, the agents' memory, tasks, and triggers.",tint: 'var(--cth-lemon-light)', edge: 'var(--cth-lemon)'},{@@ -216,7 +216,7 @@ export function OnboardingWizard({ onComplete }: OnboardingWizardProps) {Munder Difflin lets you run an office of long-running, highly capable AIagents that can take on almost any task. It uses the CLI agents you alreadyhave and manages everything around them — their context, memory, tasks,- schedules, webhooks, environment, files, and integrations.+ triggers, environment, files, and integrations.<span style={{ color: 'var(--cth-ink-500)' }}> (We call this harnessing your agents.)</span></div></div>diff --git a/src/renderer/src/components/SchedulesTab.tsx b/src/renderer/src/components/SchedulesTab.tsxdeleted file mode 100644index 10a953ef..00000000--- a/src/renderer/src/components/SchedulesTab.tsx+++ /dev/null@@ -1,212 +0,0 @@-import { useEffect, useState } from 'react';-import { PixelButton } from './PixelButton';-import { useStore } from '@/store/store';--/**- * SCHEDULES — recurring auto-dispatched missions, as their own Command-Center- * tab (they used to be buried in the monitor tab's long scroll). Also the- * landing spot for the calendar hanging in the boss's office.- */--interface ScheduledMission {- id: string;- label: string;- intervalMs: number;- to: string;- body: string;- enabled: boolean;- autoCompact?: boolean;- lastFiredAt?: number;- kind?: 'dispatch' | 'heartbeat' | 'compact';- quietThresholdMs?: number;-}--const INTERVAL_OPTS: { ms: number; label: string }[] = [- { ms: 3600000, label: '1h' },- { ms: 21600000, label: '6h' },- { ms: 86400000, label: '24h' },- { ms: 604800000, label: 'weekly' }-];--function relTime(ms: number): string {- const past = ms >= 0;- const a = Math.abs(ms);- if (a < 45_000) return 'just now';- const mins = Math.round(a / 60_000);- const unit = mins < 60 ? `${mins}m` : mins < 1440 ? `${Math.round(mins / 60)}h` : `${Math.round(mins / 1440)}d`;- return past ? `${unit} ago` : `in ${unit}`;-}--const inputStyle: React.CSSProperties = {- width: '100%', boxSizing: 'border-box', padding: '6px 8px', resize: 'vertical',- background: 'var(--cth-paper-100)', border: 'none',- boxShadow: 'inset 0 0 0 1px var(--cth-ink-100)',- fontFamily: 'var(--cth-font-mono)', fontSize: 12, lineHeight: '17px',- color: 'var(--cth-ink-900)', outline: 'none'-};--const selectStyle: React.CSSProperties = {- padding: '4px 6px', background: 'var(--cth-paper-100)', border: 'none',- boxShadow: 'inset 0 0 0 1px var(--cth-ink-100)', fontFamily: 'var(--cth-font-ui)',- fontSize: 12, color: 'var(--cth-ink-900)', cursor: 'pointer'-};--export function SchedulesTab() {- const agents = useStore((s) => s.agents);- const [missions, setMissions] = useState<ScheduledMission[]>([]);- const [mLabel, setMLabel] = useState('');- const [mInterval, setMInterval] = useState<string>(String(INTERVAL_OPTS[0].ms));- const [mTo, setMTo] = useState<string>('god');- const [mBody, setMBody] = useState('');-- useEffect(() => {- window.cth.listMissions().then(setMissions).catch(() => { /* noop */ });- // Refresh "last fired" when the scheduler stamps a beat/dispatch (#2.3).- const off = window.cth.onMissionsUpdated(() => {- window.cth.listMissions().then(setMissions).catch(() => { /* noop */ });- });- return off;- }, []);-- const persistMissions = async (next: ScheduledMission[]) => {- setMissions(next);- await window.cth.saveMissions(next).catch(() => { /* noop */ });- };- const toggleMission = (id: string) =>- persistMissions(missions.map((m) => (m.id === id ? { ...m, enabled: !m.enabled } : m)));- const updateInterval = (id: string, intervalMs: number) =>- persistMissions(missions.map((m) => (m.id === id ? { ...m, intervalMs } : m)));- // The backend merge in missions:save keeps only the missions the renderer- // sends back, so deletion is just "save the list without it".- const deleteMission = (id: string) =>- persistMissions(missions.filter((m) => m.id !== id));- const addMission = () => {- if (!mLabel.trim() || !mBody.trim()) return;- const next: ScheduledMission = {- id: `m_${Date.now().toString(36)}`,- label: mLabel.trim(),- intervalMs: Number(mInterval),- to: mTo,- body: mBody.trim(),- enabled: true- };- persistMissions([...missions, next]);- setMLabel(''); setMBody('');- };- const targetName = (to: string) =>- to === 'broadcast' ? 'everyone' : to === 'god' ? 'Michael' : agents.find((a) => a.id === to)?.name ?? to;- const intervalLabel = (ms: number) => INTERVAL_OPTS.find((o) => o.ms === ms)?.label ?? `${Math.round(ms / 3600000)}h`;-- return (- <div style={{ flex: 1, minHeight: 0, overflowY: 'auto', background: 'var(--cth-paper-200)', padding: 10, display: 'flex', flexDirection: 'column', gap: 6 }}>- {missions.length === 0 && (- <div style={{ fontSize: 12, color: 'var(--cth-ink-300)', textAlign: 'center', padding: '12px 0' }}>- No scheduled missions.- </div>- )}- {missions.map((m) => {- const hb = m.kind === 'heartbeat';- const isCompact = m.kind === 'compact' || m.id === 'compact-maintenance';- const fired = m.lastFiredAt ? `fired ${relTime(Date.now() - m.lastFiredAt)}` : 'not yet fired';- const next = m.enabled && m.lastFiredAt- ? ` · next ${relTime(Date.now() - (m.lastFiredAt + m.intervalMs))}` : '';- return (- <div key={m.id} style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>- <div style={{- display: 'flex', alignItems: 'center', gap: 6, padding: 6,- background: 'var(--cth-paper-100)',- boxShadow: `inset 0 0 0 1px ${isCompact && !m.enabled ? 'var(--cth-coral)' : 'var(--cth-ink-300)'}`- }}>- <span style={{- fontFamily: 'var(--cth-font-display)', fontSize: 9, padding: '2px 5px 1px',- background: hb || isCompact ? 'var(--cth-lemon)' : 'var(--cth-cream-200)',- boxShadow: `inset 0 0 0 1px ${hb || isCompact ? 'var(--cth-ink-900)' : 'var(--cth-ink-700)'}`,- color: 'var(--cth-ink-900)', flexShrink: 0- }}>{isCompact ? '⚙ compact' : hb ? '♥ beat' : intervalLabel(m.intervalMs)}</span>- <div style={{ flex: 1, minWidth: 0 }}>- <div style={{ fontSize: 12, color: 'var(--cth-ink-900)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{m.label}</div>- <div style={{ fontSize: 11, color: 'var(--cth-ink-500)' }}>- {isCompact- ? `every ${intervalLabel(m.intervalMs)} · keeps every agent's terminal context lean`- : <>→ {targetName(m.to)}{hb ? ` · adaptive ~${intervalLabel(m.intervalMs)} · auto digest` : ''}</>}- </div>- <div style={{ fontSize: 10, color: 'var(--cth-ink-500)' }}>{fired}{next}</div>- </div>- {isCompact && (- <select- value={String(m.intervalMs)}- onChange={(e) => updateInterval(m.id, Number(e.target.value))}- title="How often to compact every agent"- style={selectStyle}- >- {INTERVAL_OPTS.map((o) => <option key={o.ms} value={String(o.ms)}>{o.label}</option>)}- </select>- )}- <button- onClick={() => toggleMission(m.id)}- style={{- padding: '2px 8px 1px', border: 'none', cursor: 'pointer', flexShrink: 0,- background: m.enabled ? 'var(--cth-lemon)' : 'var(--cth-cream-200)',- boxShadow: `inset 0 0 0 1px ${m.enabled ? 'var(--cth-ink-900)' : 'var(--cth-ink-700)'}`,- fontFamily: 'var(--cth-font-ui)', fontSize: 12, color: 'var(--cth-ink-900)'- }}- >{m.enabled ? 'on' : 'off'}</button>- <button- onClick={() => deleteMission(m.id)}- title={isCompact ? 'Delete (it reappears disabled on next launch — auto-compact is required)' : 'Delete this scheduled mission'}- style={{- padding: '2px 6px 1px', border: 'none', cursor: 'pointer', flexShrink: 0,- background: 'var(--cth-cream-200)',- boxShadow: 'inset 0 0 0 1px var(--cth-ink-100)',- fontFamily: 'var(--cth-font-ui)', fontSize: 12, color: 'var(--cth-coral)'- }}- >✕</button>- </div>- {isCompact && !m.enabled && (- <div style={{- fontSize: 11, lineHeight: '15px', color: 'var(--cth-ink-900)',- padding: '6px 8px', background: 'var(--cth-coral-light, #f7dcd6)',- boxShadow: 'inset 0 0 0 1px var(--cth-coral)'- }}>- ⚠ Auto-compact is OFF. Long-running agents need this — without it each- agent's terminal context grows until it overflows and the agent fails.- Turn it back on unless you're compacting another way.- </div>- )}- </div>- );- })}-- <div style={{ display: 'flex', gap: 6, marginTop: 6 }}>- <input- value={mLabel}- onChange={(e) => setMLabel(e.target.value)}- placeholder="mission label"- style={{ ...inputStyle, flex: 1, fontFamily: 'var(--cth-font-ui)' }}- />- <select value={mInterval} onChange={(e) => setMInterval(e.target.value)} style={selectStyle}>- {INTERVAL_OPTS.map((o) => <option key={o.ms} value={String(o.ms)}>{o.label}</option>)}- </select>- <select value={mTo} onChange={(e) => setMTo(e.target.value)} style={selectStyle}>- <option value="broadcast">everyone</option>- <option value="god">Michael</option>- {agents.filter((a) => !a.isGod).map((a) => (- <option key={a.id} value={a.id}>{a.name}</option>- ))}- </select>- </div>- <textarea- value={mBody}- onChange={(e) => setMBody(e.target.value)}- rows={2}- placeholder="Recurring task body… (dispatched on each interval)"- style={inputStyle}- />- <div>- <PixelButton variant="primary" size="sm" onClick={addMission} disabled={!mLabel.trim() || !mBody.trim()}>- add mission- </PixelButton>- </div>- </div>- );-}diff --git a/src/renderer/src/components/SettingsModal.tsx b/src/renderer/src/components/SettingsModal.tsxindex 6aed9253..c1641557 100644--- a/src/renderer/src/components/SettingsModal.tsx+++ b/src/renderer/src/components/SettingsModal.tsx@@ -1,6 +1,15 @@import { useState, useEffect, type CSSProperties } from 'react';import { AGENT_MODELS, type HarnessConfig } from '@/store/config';import { useStore } from '@/store/store';+import {+ CLONE_NODE_BLURB,+ DEFAULT_TRIGGER_MODE,+ DEFAULT_WEBHOOK_SCHEMA,+ TRIGGER_MODES,+ type OrgTriggerConfig,+ type TriggerMode,+ type WebhookTrigger+} from '@shared/triggers';import { PixelPanel } from './PixelPanel';import { PixelButton } from './PixelButton';import { Icon } from './Icon';@@ -16,19 +25,29 @@ export interface SettingsModalProps {onClose: () => void;}-/** Slack fields live on the main-process config; the renderer mirror type doesn't- * declare them yet (same as `notifications`), so read them off a widened view. */-type SlackConfig = HarnessConfig & {- slackEnabled?: boolean;- slackSigningSecret?: string;- slackBotToken?: string;- slackChannelId?: string;- slackPort?: number;- slackProactivePosting?: boolean;- webhookEnabled?: boolean;- webhookSecret?: string;- webhookPort?: number;-};+/**+ * The triggers IPC surface. `src/preload/index.ts` is owned by another lane and+ * these methods are landing there in parallel, so `CthApi` doesn't declare them+ * yet — read them off a narrow local view instead of widening the preload+ * contract from the renderer. Every call site wraps them in try/catch, which also+ * covers the window in which a method is still missing at runtime.+ */+interface TriggersApi {+ listWebhooks: () => Promise<WebhookTrigger[]>;+ saveWebhooks: (list: WebhookTrigger[]) => Promise<{ ok: boolean; error?: string }>;+ deleteWebhook: (id: string) => Promise<{ ok: boolean; error?: string }>;+ generateWebhookSecret: () => Promise<{ ok: boolean; secret?: string }>;+ webhooksStatus: () => Promise<{ running: boolean; url?: string }>;+ getOrgTrigger: () => Promise<OrgTriggerConfig>;+ setOrgTrigger: (cfg: OrgTriggerConfig) => Promise<{ ok: boolean; error?: string }>;+}+const triggersApi = (): TriggersApi => window.cth as unknown as TriggersApi;++/** Process-unique id for a new webhook — it is the path segment callers POST to,+ * so it must be stable and collision-free across renames. */+function newWebhookId(): string {+ return `wh-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;+}/** Pixel-aesthetic text input, mirroring AddAgentModal's inputStyle. */const slackInputStyle: CSSProperties = {@@ -81,24 +100,38 @@ const SLACK_CONNECT_STEPS = `Connect Munder Difflin to Slack8. Save Changes, reinstall if Slack prompts, then invite the botto your channel: /invite @MunderDifflin`;-/** The request/response contract shown behind the webhook i icon. `<endpoint>` is the- * public URL printed once the server starts; the secret/token go in headers so- * they stay out of URLs and access logs. */-const WEBHOOK_API_DOC = `Generic webhook API+/** The request/response contract shown behind the webhook i icon. Every webhook+ * shares one server and one tunnel and is told apart by its id in the path, so+ * `<tunnel>` is the public base URL and `<webhookId>` picks the endpoint. The+ * secret/token go in headers so they stay out of URLs and access logs. */+const WEBHOOK_API_DOC = `Webhook API-Trigger work (POST <endpoint>):- header x-md-webhook-secret: <your secret>- body {"message": "do X for me", "title": "optional short title"}+Every webhook has its own URL, its own secret and its own mode. They share one+server and one tunnel; the id in the path says which one you are calling.++Trigger work (POST <tunnel>/<webhookId>):+ header x-md-webhook-secret: <that webhook's secret>+ body {"message": "do X for me", "title": "optional short title",+ "kind": "directive" | "communication", "from": "who is calling"}-> 200 {"ok": true, "token": "<capability token>", "taskId": "<card id>"}+ -> 202 {"ok": true, "status": "awaiting approval"}-Check status (GET <endpoint>):+Check status (GET <tunnel>/<webhookId>):header x-md-webhook-token: <token> (or ?token=<token>)-> 200 {"ok": true, "status": "todo|doing|blocked|done","title": "...", "result": "<summary or null>"}-The secret authorizes new work; the returned token is a read-only handle to-that one task's status (it reveals nothing else). Keep both private. The-endpoint URL rotates every time you press Start.`;+The mode decides which of the two answers you get:+ allow all routes straight through -> 200+ communication only chatter routes; a directive gets 202 awaiting approval+ strict everything gets 202 awaiting approval++A 202 means the message is parked in Trigger History until you approve it; the+token you were handed still reads that task once it is routed. The secret+authorizes new work, the token only reads one task's status. Keep both private.++Each webhook checks bodies against its own JSON schema — edit that in the+Triggers tab of Michael's Command Center.`;/** Clear every renderer-side persisted key so a relaunch starts truly empty. */function clearLocalState(): void {@@ -238,15 +271,14 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {};// --- Slack integration ---- const slackCfg = config as SlackConfig;- const [slackEnabled, setSlackEnabled] = useState(slackCfg.slackEnabled ?? false);- const [slackSecret, setSlackSecret] = useState(slackCfg.slackSigningSecret ?? '');- const [slackBotToken, setSlackBotToken] = useState(slackCfg.slackBotToken ?? '');- const [slackChannel, setSlackChannel] = useState(slackCfg.slackChannelId ?? '');- const [slackPort, setSlackPort] = useState(String(slackCfg.slackPort ?? 3847));+ const [slackEnabled, setSlackEnabled] = useState(config.slackEnabled ?? false);+ const [slackSecret, setSlackSecret] = useState(config.slackSigningSecret ?? '');+ const [slackBotToken, setSlackBotToken] = useState(config.slackBotToken ?? '');+ const [slackChannel, setSlackChannel] = useState(config.slackChannelId ?? '');+ const [slackPort, setSlackPort] = useState(String(config.slackPort ?? 3847));// App/voice-initiated proactive posting (the "queued" ack). Default OFF —// the Slack-origin done-reply round-trip is unaffected by this toggle.- const [slackProactivePosting, setSlackProactivePosting] = useState(slackCfg.slackProactivePosting ?? false);+ const [slackProactivePosting, setSlackProactivePosting] = useState(config.slackProactivePosting ?? false);const [tunnelUrl, setTunnelUrl] = useState('');const [slackBusy, setSlackBusy] = useState(false);const [slackNote, setSlackNote] = useState('');@@ -256,17 +288,30 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {// Whether the connect-steps help panel is expanded.const [showSlackHelp, setShowSlackHelp] = useState(false);- // --- Generic webhook + status API ---- const [webhookEnabled, setWebhookEnabled] = useState(slackCfg.webhookEnabled ?? false);- const [webhookSecret, setWebhookSecret] = useState(slackCfg.webhookSecret ?? '');- const [webhookPort, setWebhookPort] = useState(String(slackCfg.webhookPort ?? 3849));+ // --- Webhook triggers (a LIST; src/shared/triggers.ts owns the type) ---------+ // The list itself lives in the store, not in local state: the Triggers tab+ // edits the same webhooks, and one of the two surfaces holding a private copy+ // is exactly the drift this feature exists to prevent.+ const webhookTriggers = useStore((s) => s.webhookTriggers);+ const setWebhookTriggersStore = useStore((s) => s.setWebhookTriggers);+ /** Public base URL of the shared tunnel; each webhook's endpoint is `<base>/<id>`. */const [webhookUrl, setWebhookUrl] = useState('');const [webhookRunning, setWebhookRunning] = useState(false);const [webhookBusy, setWebhookBusy] = useState(false);const [webhookNote, setWebhookNote] = useState('');- const [showWebhookSecret, setShowWebhookSecret] = useState(false);+ /** Which secrets the user has unmasked, by webhook id. Reset on every reopen. */+ const [shownSecrets, setShownSecrets] = useState<Record<string, boolean>>({});+ /** Webhook awaiting a second delete click — deleting one revokes a live caller. */+ const [pendingDelete, setPendingDelete] = useState<string | null>(null);const [showWebhookHelp, setShowWebhookHelp] = useState(false);+ // --- Organisation trigger (peer messaging; configuration only for now) ------+ const orgTrigger = useStore((s) => s.orgTrigger);+ const setOrgTriggerStore = useStore((s) => s.setOrgTrigger);+ const [showOrgKey, setShowOrgKey] = useState(false);+ const [orgBusy, setOrgBusy] = useState(false);+ const [orgNote, setOrgNote] = useState('');+// ─── Knowledge Graph (enterprise multimodal context for agents) ───────────const [kgEnabled, setKgEnabled] = useState<boolean>((config as HarnessConfig & { knowledgeGraph?: { enabled?: boolean } }).knowledgeGraph?.enabled === true@@ -303,8 +348,8 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {};// ─── Scheduled auto-compact — the compact-maintenance mission's enabled flag.- // The mission itself stays the single source of truth (SchedulesTab edits the- // same field); this is just a General-section shortcut. Default OFF (v0.3.4).+ // The mission itself stays the single source of truth (the Triggers tab edits+ // the same field); this is just a General-section shortcut. Default OFF (v0.3.4).const [autoCompactOn, setAutoCompactOn] = useState<boolean>((config.missions ?? []).some((m) => m.id === 'compact-maintenance' && m.enabled));@@ -337,9 +382,9 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {const hasOpenAiKey = useStore((s) => s.hasOpenAiKey);// v0.3.4 fix: the config default is ON ('now on by default', 0.2.7) — seeding// with `?? false` displayed OFF while the feature was actually running.- const [freeflowEnabled, setFreeflowEnabled] = useState(slackCfg.freeflowEnabled !== false);- const [groqKey, setGroqKey] = useState(slackCfg.groqApiKey ?? '');- const [freeflowModel, setFreeflowModel] = useState(slackCfg.freeflowModel ?? 'whisper-large-v3-turbo');+ const [freeflowEnabled, setFreeflowEnabled] = useState(config.freeflowEnabled !== false);+ const [groqKey, setGroqKey] = useState(config.groqApiKey ?? '');+ const [freeflowModel, setFreeflowModel] = useState(config.freeflowModel ?? 'whisper-large-v3-turbo');const [showGroqKey, setShowGroqKey] = useState(false);const [freeflowBusy, setFreeflowBusy] = useState(false);const [freeflowNote, setFreeflowNote] = useState('');@@ -355,7 +400,7 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {let alive = true;window.cth.getConfig().then((c) => {if (!alive) return;- const cc = c as BreakerCfgView & SlackConfig & { notifications?: boolean };+ const cc = c as BreakerCfgView;setNotifications(cc.notifications === true);setAgentBudget(cc.costCapTokens != null ? String(cc.costCapTokens) : '');setVelocityCeiling(cc.circuitBreaker?.tokenVelocityPerMin != null ? String(cc.circuitBreaker.tokenVelocityPerMin) : '');@@ -365,9 +410,6 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {setSlackChannel(cc.slackChannelId ?? '');setSlackPort(String(cc.slackPort ?? 3847));setSlackProactivePosting(cc.slackProactivePosting ?? false);- setWebhookEnabled(cc.webhookEnabled ?? false);- setWebhookSecret(cc.webhookSecret ?? '');- setWebhookPort(String(cc.webhookPort ?? 3849));const kgOn = (cc as { knowledgeGraph?: { enabled?: boolean } }).knowledgeGraph?.enabled === true;setKgEnabled(kgOn);setFreeflowEnabled(cc.freeflowEnabled !== false);@@ -384,11 +426,26 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {setRunning(s.running);if (s.url) setTunnelUrl(s.url);}).catch(() => { /* status unavailable - assume not running */ });- window.cth.webhookStatus().then((s) => {- if (!alive) return;- setWebhookRunning(s.running);- if (s.url) setWebhookUrl(s.url);- }).catch(() => { /* status unavailable - assume not running */ });+ // Triggers: re-read main and push the result into the shared mirror. App+ // already seeded it at launch; this catches anything the Triggers tab (or+ // another window) changed since, and is the ONLY place Settings reads them —+ // every render below comes off the store.+ void (async () => {+ try {+ const list = await triggersApi().listWebhooks();+ if (alive && Array.isArray(list)) useStore.getState().setWebhookTriggers(list);+ } catch { /* keep the mirror App seeded from getConfig() */ }+ try {+ const org = await triggersApi().getOrgTrigger();+ if (alive && org) useStore.getState().setOrgTrigger(org);+ } catch { /* ditto */ }+ try {+ const s = await triggersApi().webhooksStatus();+ if (!alive) return;+ setWebhookRunning(s.running);+ if (s.url) setWebhookUrl(s.url);+ } catch { /* status unavailable - assume not listening */ }+ })();return () => { alive = false; };}, []);@@ -440,64 +497,105 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {finally { setSlackBusy(false); }};- // --- Generic webhook handlers ---- const webhookPatch = (enabled: boolean) => ({- secret: webhookSecret,- port: Number(webhookPort) || 3849,- enabled- });-- const saveWebhook = async () => {+ // --- Webhook trigger handlers ---+ /** The one write path. Updates the shared mirror FIRST so the Triggers tab+ * repaints immediately, then persists. Pass `persist: false` for keystroke+ * edits (a rename) — the blur commits them. */+ const applyWebhooks = async (list: WebhookTrigger[], persist = true) => {+ setWebhookTriggersStore(list);+ if (!persist) return;setWebhookBusy(true); setWebhookNote('');try {- await window.cth.webhookSetConfig(webhookPatch(webhookEnabled));+ const res = await triggersApi().saveWebhooks(list);+ if (res && res.ok === false) { setWebhookNote(res.error ?? 'could not save'); return; }setWebhookNote('saved');+ setTimeout(() => setWebhookNote(''), 1500);} catch (e) {setWebhookNote(e instanceof Error ? e.message : String(e));} finally { setWebhookBusy(false); }};- /** Mint a fresh secret in main (256-bit) and show it for copying. */- const generateWebhookSecret = async () => {+ /** Replace one entry by id (the shape every per-row control uses). */+ const patchWebhook = (id: string, patch: Partial<WebhookTrigger>, persist = true) =>+ applyWebhooks(webhookTriggers.map((w) => (w.id === id ? { ...w, ...patch } : w)), persist);++ /** New endpoint: main mints the secret (256-bit), and it ships DISABLED —+ * turning on a public surface is always an explicit second click. */+ const addWebhook = async () => {setWebhookBusy(true); setWebhookNote('');+ let secret = '';try {- const res = await window.cth.webhookGenerateSecret();- if (res.ok && res.secret) { setWebhookSecret(res.secret); setShowWebhookSecret(true); setWebhookNote('new secret - copy it now'); }- else setWebhookNote('could not generate secret');+ const res = await triggersApi().generateWebhookSecret();+ secret = res.ok && res.secret ? res.secret : '';} catch (e) {setWebhookNote(e instanceof Error ? e.message : String(e));} finally { setWebhookBusy(false); }+ if (!secret) { setWebhookNote('could not generate a secret'); return; }+ const entry: WebhookTrigger = {+ id: newWebhookId(),+ name: `Webhook ${webhookTriggers.length + 1}`,+ secret,+ enabled: false,+ mode: DEFAULT_TRIGGER_MODE,+ schema: DEFAULT_WEBHOOK_SCHEMA,+ createdAt: Date.now()+ };+ setShownSecrets((s) => ({ ...s, [entry.id]: true })); // show it once, to copy+ await applyWebhooks([...webhookTriggers, entry]);};- const startWebhook = async () => {+ /** Mint a fresh secret for ONE endpoint. The old one stops working at once —+ * that is the point, and it never disturbs the other webhooks. */+ const rotateWebhookSecret = async (id: string) => {setWebhookBusy(true); setWebhookNote('');+ let secret = '';try {- await window.cth.webhookSetConfig(webhookPatch(true));- setWebhookEnabled(true);- const res = await window.cth.webhookStart();- if (res.ok) {- setWebhookRunning(true);- if (res.url) setWebhookUrl(res.url);- setWebhookNote(res.url ? 'listening' : (res.error ?? 'started, but tunnel unavailable'));- } else {- setWebhookNote(res.error ?? 'failed to start');- }+ const res = await triggersApi().generateWebhookSecret();+ secret = res.ok && res.secret ? res.secret : '';} catch (e) {setWebhookNote(e instanceof Error ? e.message : String(e));} finally { setWebhookBusy(false); }+ if (!secret) { setWebhookNote('could not generate a secret'); return; }+ setShownSecrets((s) => ({ ...s, [id]: true }));+ await patchWebhook(id, { secret });+ setWebhookNote('new secret — copy it now');};- const stopWebhook = async () => {+ const removeWebhook = async (id: string) => {+ setPendingDelete(null);setWebhookBusy(true); setWebhookNote('');- try { await window.cth.webhookStop(); setWebhookRunning(false); setWebhookNote('stopped'); }- catch (e) { setWebhookNote(e instanceof Error ? e.message : String(e)); }- finally { setWebhookBusy(false); }+ try {+ await triggersApi().deleteWebhook(id);+ setWebhookNote('deleted');+ setTimeout(() => setWebhookNote(''), 1500);+ } catch (e) {+ setWebhookNote(e instanceof Error ? e.message : String(e));+ } finally { setWebhookBusy(false); }+ // Mirror the removal either way: if main rejected it, the next open re-reads.+ setWebhookTriggersStore(webhookTriggers.filter((w) => w.id !== id));};- const copyWebhookUrl = () => { void window.cth.copyToClipboard(webhookUrl); };- const copyWebhookSecret = () => { void window.cth.copyToClipboard(webhookSecret); };+ /** Endpoint URL for one webhook: every entry shares the tunnel, the id picks it. */+ const webhookEndpoint = (id: string) => (webhookUrl ? `${webhookUrl.replace(/\/$/, '')}/${id}` : '');const copyTunnel = () => { void window.cth.copyToClipboard(tunnelUrl); };+ // --- Organisation trigger handlers ---+ /** Same contract as webhooks: mirror first (so the Triggers tab is live), then+ * persist. Keystroke edits pass `persist: false` and commit on blur. */+ const applyOrg = async (next: OrgTriggerConfig, persist = true) => {+ setOrgTriggerStore(next);+ if (!persist) return;+ setOrgBusy(true); setOrgNote('');+ try {+ const res = await triggersApi().setOrgTrigger(next);+ if (res && res.ok === false) { setOrgNote(res.error ?? 'could not save'); return; }+ setOrgNote('saved');+ setTimeout(() => setOrgNote(''), 1500);+ } catch (e) {+ setOrgNote(e instanceof Error ? e.message : String(e));+ } finally { setOrgBusy(false); }+ };+// --- Free Flow handlers ---/** Persist Free Flow settings; main re-arms the global hotkey. Also mirror the* flag into the store so the composer mic button appears/disappears live. */@@ -833,7 +931,7 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {</span><span style={{ fontSize: 12, lineHeight: '16px', color: 'var(--cth-ink-500)' }}>Queue /compact for every agent on a schedule (hourly by default; interval- in the Schedules tab). Off by default — long-running agents may overflow+ in the Triggers tab). Off by default — long-running agents may overflowtheir context without it.</span></div>@@ -1300,18 +1398,21 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {<div style={{ height: 2, background: 'var(--cth-ink-300)' }} />- {/* Generic webhook + status API */}+ {/* Webhook triggers — a LIST of endpoints, one per caller.+ Everything renders off the store mirror, so a change made+ in the Triggers tab lands here without a refetch (and the+ other way round). */}<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}><div style={{fontFamily: 'var(--cth-font-display)', fontSize: 8, lineHeight: '12px',color: 'var(--cth-ink-500)', textTransform: 'uppercase', marginBottom: 2}}>- Webhook API+ Webhook triggers</div><div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}><div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}><span style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, lineHeight: '20px', color: 'var(--cth-ink-900)' }}>- Webhook API+ Webhook triggers<buttontype="button"aria-label="Show webhook API format"@@ -1328,7 +1429,8 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {>i</button></span><span style={{ fontSize: 12, lineHeight: '16px', color: 'var(--cth-ink-500)' }}>- A secret-gated HTTP endpoint: POST to start work and get a token, GET the token for status.+ One endpoint per caller, each with its own secret and mode. They all share+ one server, so another webhook costs nothing.</span></div><div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>@@ -1336,14 +1438,10 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {fontSize: 12, lineHeight: '16px',color: webhookRunning ? 'var(--cth-mint-700, #1f7a4d)' : 'var(--cth-ink-500)'}}>- {webhookRunning ? '● Connected' : '○ Not connected'}+ {webhookRunning ? '● Listening' : '○ Not listening'}</span>- <PixelButton- variant={webhookEnabled ? 'primary' : 'secondary'}- size="sm"- onClick={() => setWebhookEnabled((v) => !v)}- >- {webhookEnabled ? 'on' : 'off'}+ <PixelButton variant="primary" size="sm" onClick={addWebhook} disabled={webhookBusy}>+ add webhook</PixelButton></div></div>@@ -1358,75 +1456,237 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {}}>{WEBHOOK_API_DOC}</pre>)}- {webhookEnabled && (- <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>- {/* Public surface warning. Loud, not buried. */}- <span style={{ fontSize: 12, lineHeight: '16px', color: '#6E1423' }}>- This opens a PUBLIC endpoint anyone with the secret can post to. It stays off until you press Start.- </span>+ {/* Public surface warning. Loud, not buried. */}+ <span style={{ fontSize: 12, lineHeight: '16px', color: '#6E1423' }}>+ Every webhook you switch on is a PUBLIC endpoint anyone holding its secret can post to.+ New ones arrive off.+ </span>- <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>- <span style={slackLabelStyle}>Secret key</span>- <div style={{ display: 'flex', gap: 6 }}>- <input- type={showWebhookSecret ? 'text' : 'password'}- value={webhookSecret}- onChange={(e) => setWebhookSecret(e.target.value)}- placeholder="press Generate, or paste your own"- style={{ ...slackInputStyle, fontFamily: 'var(--cth-font-mono)' }}- />- <PixelButton variant="secondary" size="sm" onClick={() => setShowWebhookSecret((v) => !v)} disabled={!webhookSecret}>- {showWebhookSecret ? 'hide' : 'show'}- </PixelButton>- <PixelButton variant="secondary" size="sm" onClick={copyWebhookSecret} disabled={!webhookSecret}>copy</PixelButton>- <PixelButton variant="ghost" size="sm" onClick={generateWebhookSecret} disabled={webhookBusy}>generate</PixelButton>- </div>- </label>+ {webhookTriggers.length === 0 ? (+ <span style={{ fontSize: 12, lineHeight: '16px', color: 'var(--cth-ink-500)' }}>+ No webhooks yet. Add one to give a tool a URL it can hand work to.+ </span>+ ) : (+ <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>+ {webhookTriggers.map((w) => {+ const shown = shownSecrets[w.id] === true;+ const endpoint = webhookEndpoint(w.id);+ const modeBlurb = TRIGGER_MODES.find((m) => m.value === w.mode)?.blurb ?? '';+ return (+ <div+ key={w.id}+ style={{+ display: 'flex', flexDirection: 'column', gap: 8,+ padding: '10px 12px',+ background: 'var(--cth-cream-100)',+ boxShadow: `inset 0 0 0 ${w.enabled ? 1.5 : 1}px ${w.enabled ? 'var(--cth-ink-500)' : 'var(--cth-ink-100)'}`+ }}+ >+ {/* Name, on/off, delete. Renaming is live in the+ mirror on every keystroke and persists on blur. */}+ <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>+ <input+ value={w.name}+ onChange={(e) => { void patchWebhook(w.id, { name: e.target.value }, false); }}+ onBlur={() => { void applyWebhooks(webhookTriggers); }}+ placeholder="what calls this?"+ style={{ ...slackInputStyle, flex: 1 }}+ />+ <PixelButton+ variant={w.enabled ? 'primary' : 'secondary'}+ size="sm"+ onClick={() => { void patchWebhook(w.id, { enabled: !w.enabled }); }}+ disabled={webhookBusy}+ >+ {w.enabled ? 'on' : 'off'}+ </PixelButton>+ {/* Two clicks: deleting revokes a caller's access for good. */}+ <PixelButton+ variant={pendingDelete === w.id ? 'destructive' : 'ghost'}+ size="sm"+ onClick={() => {+ if (pendingDelete === w.id) void removeWebhook(w.id);+ else setPendingDelete(w.id);+ }}+ disabled={webhookBusy}+ >+ {pendingDelete === w.id ? 'sure?' : 'delete'}+ </PixelButton>+ </div>++ <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>+ <span style={{ ...slackLabelStyle, width: 56, flexShrink: 0 }}>URL</span>+ <input+ readOnly+ value={endpoint || 'starts once the webhook server is listening'}+ onFocus={(e) => e.currentTarget.select()}+ style={{+ ...slackInputStyle, fontFamily: 'var(--cth-font-mono)', fontSize: 12,+ color: endpoint ? 'var(--cth-ink-900)' : 'var(--cth-ink-500)'+ }}+ />+ <PixelButton+ variant="secondary"+ size="sm"+ onClick={() => { void window.cth.copyToClipboard(endpoint); }}+ disabled={!endpoint}+ >+ copy+ </PixelButton>+ </div>++ {/* Masked by default; never in a title attribute. */}+ <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>+ <span style={{ ...slackLabelStyle, width: 56, flexShrink: 0 }}>Secret</span>+ <input+ type={shown ? 'text' : 'password'}+ readOnly+ value={w.secret}+ onFocus={(e) => e.currentTarget.select()}+ style={{ ...slackInputStyle, fontFamily: 'var(--cth-font-mono)' }}+ />+ <PixelButton+ variant="secondary"+ size="sm"+ onClick={() => setShownSecrets((s) => ({ ...s, [w.id]: !shown }))}+ >+ {shown ? 'hide' : 'show'}+ </PixelButton>+ <PixelButton+ variant="secondary"+ size="sm"+ onClick={() => { void window.cth.copyToClipboard(w.secret); }}+ >+ copy+ </PixelButton>+ <PixelButton+ variant="ghost"+ size="sm"+ onClick={() => { void rotateWebhookSecret(w.id); }}+ disabled={webhookBusy}+ >+ rotate+ </PixelButton>+ </div>++ <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>+ <span style={{ ...slackLabelStyle, width: 56, flexShrink: 0 }}>Mode</span>+ <select+ value={w.mode}+ onChange={(e) => { void patchWebhook(w.id, { mode: e.target.value as TriggerMode }); }}+ style={{ ...slackInputStyle, width: 160, flexShrink: 0 }}+ >+ {TRIGGER_MODES.map((m) => (+ <option key={m.value} value={m.value}>{m.label}</option>+ ))}+ </select>+ <span style={{ fontSize: 12, lineHeight: '16px', color: 'var(--cth-ink-500)' }}>+ {modeBlurb}+ </span>+ </div>+ </div>+ );+ })}+ </div>+ )}- <label style={{ display: 'flex', flexDirection: 'column', gap: 4, width: 100 }}>- <span style={slackLabelStyle}>Port</span>- <input- type="number"- value={webhookPort}- onChange={(e) => setWebhookPort(e.target.value)}- placeholder="3849"- style={{ ...slackInputStyle, fontFamily: 'var(--cth-font-mono)' }}- />- </label>+ <span style={{ fontSize: 12, lineHeight: '16px', color: 'var(--cth-ink-500)' }}>+ Callers POST to a webhook's URL with its secret in the{' '}+ <code>x-md-webhook-secret</code> header. Each one checks bodies against its own JSON+ schema — edit that in the Triggers tab of Michael's Command Center, where the history+ of everything that arrived lives too.+ </span>- <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>- <PixelButton variant="primary" size="sm" onClick={startWebhook} disabled={webhookBusy || !webhookSecret.trim() || webhookRunning}>- {webhookBusy ? '...' : webhookRunning ? 'connected' : 'start'}- </PixelButton>- <PixelButton variant="secondary" size="sm" onClick={stopWebhook} disabled={webhookBusy || !webhookRunning}>- stop- </PixelButton>- <PixelButton variant="ghost" size="sm" onClick={saveWebhook} disabled={webhookBusy}>- save- </PixelButton>- {webhookNote && (- <span style={{ fontSize: 12, color: 'var(--cth-ink-500)' }}>{webhookNote}</span>- )}- </div>+ {webhookNote && (+ <span style={{ fontSize: 12, color: 'var(--cth-ink-500)' }}>{webhookNote}</span>+ )}+ </div>- {(webhookRunning || webhookUrl) && (- <div style={{ display: 'flex', flexDirection: 'column', gap: 4, opacity: webhookRunning ? 1 : 0.55 }}>- <span style={slackLabelStyle}>- {webhookRunning ? 'Endpoint URL - POST work / GET status here' : 'last endpoint URL - rotates on next Start'}- </span>- <div style={{ display: 'flex', gap: 6 }}>- <input- readOnly- value={webhookUrl}- onFocus={(e) => e.currentTarget.select()}- style={{ ...slackInputStyle, fontFamily: 'var(--cth-font-mono)', fontSize: 12 }}- />- <PixelButton variant="secondary" size="sm" onClick={copyWebhookUrl} disabled={!webhookUrl}>copy</PixelButton>- </div>- </div>- )}+ <div style={{ height: 2, background: 'var(--cth-ink-300)' }} />++ {/* Organisation trigger — teammates messaging this clone node.+ Persisted + mirrored; no transport reads the key yet. */}+ <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>+ <div style={{+ fontFamily: 'var(--cth-font-display)', fontSize: 8, lineHeight: '12px',+ color: 'var(--cth-ink-500)', textTransform: 'uppercase', marginBottom: 2+ }}>+ Organisation+ </div>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>+ <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>+ <span style={{ fontSize: 13, lineHeight: '20px', color: 'var(--cth-ink-900)' }}>+ Organisation key+ </span>+ <span style={{ fontSize: 12, lineHeight: '16px', color: 'var(--cth-ink-500)' }}>+ How a teammate's install addresses yours.+ </span></div>- )}+ <PixelButton+ variant={orgTrigger.enabled ? 'primary' : 'secondary'}+ size="sm"+ onClick={() => { void applyOrg({ ...orgTrigger, enabled: !orgTrigger.enabled }); }}+ disabled={orgBusy}+ >+ {orgTrigger.enabled ? 'on' : 'off'}+ </PixelButton>+ </div>++ <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>+ <span style={slackLabelStyle}>API key</span>+ <div style={{ display: 'flex', gap: 6 }}>+ <input+ type={showOrgKey ? 'text' : 'password'}+ value={orgTrigger.apiKey}+ onChange={(e) => { void applyOrg({ ...orgTrigger, apiKey: e.target.value }, false); }}+ onBlur={() => { void applyOrg(orgTrigger); }}+ placeholder="paste your organisation key"+ style={{ ...slackInputStyle, fontFamily: 'var(--cth-font-mono)' }}+ />+ <PixelButton+ variant="secondary"+ size="sm"+ onClick={() => setShowOrgKey((v) => !v)}+ disabled={!orgTrigger.apiKey}+ >+ {showOrgKey ? 'hide' : 'show'}+ </PixelButton>+ </div>+ </label>++ <span style={{ fontSize: 12, lineHeight: '16px', color: 'var(--cth-ink-500)' }}>+ {CLONE_NODE_BLURB}+ </span>++ <label style={{ display: 'flex', flexDirection: 'column', gap: 4, width: 200 }}>+ <span style={slackLabelStyle}>Mode</span>+ <select+ value={orgTrigger.mode}+ onChange={(e) => { void applyOrg({ ...orgTrigger, mode: e.target.value as TriggerMode }); }}+ style={slackInputStyle}+ >+ {TRIGGER_MODES.map((m) => (+ <option key={m.value} value={m.value}>{m.label}</option>+ ))}+ </select>+ </label>+ <span style={{ fontSize: 12, lineHeight: '16px', color: 'var(--cth-ink-500)' }}>+ {TRIGGER_MODES.find((m) => m.value === orgTrigger.mode)?.blurb ?? ''}+ </span>++ <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>+ <PixelButton variant="ghost" size="sm" onClick={() => { void applyOrg(orgTrigger); }} disabled={orgBusy}>+ save+ </PixelButton>+ {orgNote && (+ <span style={{ fontSize: 12, color: 'var(--cth-ink-500)' }}>{orgNote}</span>+ )}+ </div>++ <span style={{ fontSize: 12, lineHeight: '16px', color: 'var(--cth-ink-500)' }}>+ Configuration only for now. The organisation messaging service does not exist yet, so a+ key here starts no transport — it is saved, shown in the Triggers tab, and waits.+ </span></div></>diff --git a/src/renderer/src/components/triggers/ContextSection.tsx b/src/renderer/src/components/triggers/ContextSection.tsxnew file mode 100644index 00000000..228ef021--- /dev/null+++ b/src/renderer/src/components/triggers/ContextSection.tsx@@ -0,0 +1,156 @@+import { useEffect, useRef, useState, type ReactNode } from 'react';+import type { ContextRule, ContextTriggerConfig } from '@shared/triggers';+import { getContextTrigger, setContextTrigger } from './api';+import {+ Callout, Field, Hint, IntervalPicker, Muted, PctField, SubCard, SubHeader, Toggle,+ fmtInterval, textareaStyle+} from './ui';++/**+ * CONTEXT — the trigger that fires on an agent's own terminal filling up rather+ * than on the clock alone. Two rules, and they are not the same operation:+ * compaction SUMMARISES the context, clearing THROWS IT AWAY.+ */++const WRITE_DEBOUNCE_MS = 400;++export function ContextSection({ onSummary }: { onSummary?: (s: string) => void }) {+ const [cfg, setCfg] = useState<ContextTriggerConfig | null>(null);+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);++ useEffect(() => {+ let alive = true;+ getContextTrigger().then((c) => { if (alive) setCfg(c); }).catch(() => { /* defaults */ });+ return () => {+ alive = false;+ if (timer.current) clearTimeout(timer.current);+ };+ }, []);++ useEffect(() => {+ if (!cfg) return;+ const on = [cfg.compact.enabled ? 'compact' : null, cfg.clear.enabled ? 'clear' : null].filter(Boolean);+ onSummary?.(on.length ? on.join(' + ') : 'both off');+ }, [cfg, onSummary]);++ // Optimistic + debounced: the controls answer instantly, and a burst of typing+ // in the message box collapses into one write instead of one per keystroke.+ const commit = (next: ContextTriggerConfig) => {+ setCfg(next);+ if (timer.current) clearTimeout(timer.current);+ timer.current = setTimeout(() => setContextTrigger(next), WRITE_DEBOUNCE_MS);+ };+ const patch = (key: 'compact' | 'clear', fields: Partial<ContextRule>) => {+ if (!cfg) return;+ commit({ ...cfg, [key]: { ...cfg[key], ...fields } });+ };++ if (!cfg) return <Muted>One sec…</Muted>;++ return (+ <>+ <Muted>+ A rule fires only when both halves agree: the gap since its last run has passed, AND that+ agent's context is at least as full as the bar. A bar of 0% means the clock alone.+ </Muted>+ <div style={{ height: 8 }} />++ <RuleCard+ title="Compact"+ blurb="Summarises the context so the thread keeps going."+ rule={cfg.compact}+ messageLabel="EXTRA FOCUS"+ messageHint="Appended to the provider's compaction command. Empty sends the bare command."+ messagePlaceholder="What the summary must keep…"+ onPatch={(fields) => patch('compact', fields)}+ />++ <RuleCard+ title="Clear"+ blurb="Discards the context. Nothing is summarised."+ rule={cfg.clear}+ messageLabel="COMMAND"+ messageHint="Sent literally. Empty sends the bare clear command."+ messagePlaceholder="/clear"+ caution={+ <>+ Clearing throws context away — it is not a smaller version of compaction. An agent+ mid-task forgets what it was doing. Leave this off unless you keep context another way.+ </>+ }+ onPatch={(fields) => patch('clear', fields)}+ />+ </>+ );+}++function RuleCard({ title, blurb, rule, messageLabel, messageHint, messagePlaceholder, caution, onPatch }: {+ title: string;+ blurb: string;+ rule: ContextRule;+ messageLabel: string;+ messageHint: string;+ messagePlaceholder: string;+ caution?: ReactNode;+ onPatch: (fields: Partial<ContextRule>) => void;+}) {+ const [open, setOpen] = useState(false);+ return (+ <SubCard>+ <SubHeader+ open={open}+ onToggle={() => setOpen((o) => !o)}+ title={title}+ sub={blurb}+ right={<Toggle on={rule.enabled} onClick={() => onPatch({ enabled: !rule.enabled })} />}+ />+ {/* The caution is always on screen — it is why this ships off — but it only+ goes coral once the destructive rule is actually armed. A red box over a+ switched-off setting is crying wolf. */}+ {caution && <Callout tone={rule.enabled ? 'warn' : 'note'}>{caution}</Callout>}+ {!open && (+ <Hint>+ {rule.enabled+ ? <>Every {fmtInterval(rule.everyMs)}, once context passes {rule.minContextPct}%.</>+ : <>Off.</>}+ </Hint>+ )}+ {open && (+ <div style={{ marginTop: 4 }}>+ <Field label="NO SOONER THAN EVERY">+ {/* Main clamps a context cadence to 1 minute … 24 hours, so the+ picker offers exactly that range and never labels a value it+ cannot actually store. */}+ <IntervalPicker+ value={rule.everyMs}+ onChange={(everyMs) => onPatch({ everyMs })}+ minMs={60_000}+ maxMs={86_400_000}+ />+ </Field>+ <Field label="CONTEXT BAR">+ <PctField value={rule.minContextPct} onChange={(minContextPct) => onPatch({ minContextPct })} />+ <Hint>How full the window must be before this may run. 0% = time alone.</Hint>+ </Field>+ <Field label="BAR ON BIG WINDOWS">+ <PctField+ value={rule.minContextPctLargeWindow}+ onChange={(minContextPctLargeWindow) => onPatch({ minContextPctLargeWindow })}+ />+ <Hint>Used on ~1M-token windows, where a smaller slice is still an enormous amount of text.</Hint>+ </Field>+ <Field label={messageLabel}>+ <textarea+ value={rule.message}+ onChange={(e) => onPatch({ message: e.target.value })}+ rows={3}+ placeholder={messagePlaceholder}+ style={textareaStyle}+ />+ <Hint>{messageHint}</Hint>+ </Field>+ </div>+ )}+ </SubCard>+ );+}diff --git a/src/renderer/src/components/triggers/JsonEditor.tsx b/src/renderer/src/components/triggers/JsonEditor.tsxnew file mode 100644index 00000000..ab83b594--- /dev/null+++ b/src/renderer/src/components/triggers/JsonEditor.tsx@@ -0,0 +1,59 @@+import CodeMirror from '@uiw/react-codemirror';+import { EditorView } from '@codemirror/view';+import { HighlightStyle, syntaxHighlighting } from '@codemirror/language';+import { tags } from '@lezer/highlight';+import { json } from '@codemirror/lang-json';++/**+ * A small JSON editor for a webhook's schema. Same CodeMirror the IDE uses, cut+ * down for a sidebar: no line numbers, no fold gutter, no search bar — those eat+ * a third of the width here and none of them help edit twenty lines of schema.+ * Colors come from `--cth-*` tokens so it follows the theme like everything else.+ */++const editorTheme = EditorView.theme({+ '&': {+ background: 'var(--cth-paper-100)',+ color: 'var(--cth-ink-900)',+ fontFamily: 'var(--cth-font-mono)',+ fontSize: '13px'+ },+ '&.cm-focused': { outline: 'none' },+ '.cm-content': { padding: '6px 8px' },+ '.cm-cursor, .cm-dropCursor': { borderLeftColor: 'var(--cth-coral)', borderLeftWidth: '2px' },+ '.cm-scroller': { fontFamily: 'inherit', lineHeight: '17px' },+ '.cm-gutters': { display: 'none' },+ '.cm-activeLine': { background: 'transparent' },+ '.cm-selectionBackground, ::selection': { background: 'var(--cth-lemon-light) !important' }+});++const editorSyntax = HighlightStyle.define([+ { tag: tags.propertyName, color: 'var(--cth-ink-700)' },+ { tag: tags.string, color: 'var(--cth-mint)' },+ { tag: [tags.number, tags.bool, tags.null], color: 'var(--cth-coral)' },+ { tag: tags.punctuation, color: 'var(--cth-ink-500)' }+]);++const extensions = [json(), EditorView.lineWrapping, editorTheme, syntaxHighlighting(editorSyntax)];++export function JsonEditor({ value, onChange }: { value: string; onChange: (v: string) => void }) {+ return (+ <div style={{ background: 'var(--cth-paper-100)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-100)' }}>+ <CodeMirror+ value={value}+ onChange={onChange}+ height="180px"+ extensions={extensions}+ basicSetup={{+ lineNumbers: false,+ foldGutter: false,+ highlightActiveLine: false,+ highlightActiveLineGutter: false,+ autocompletion: false,+ searchKeymap: false,+ highlightSelectionMatches: false+ }}+ />+ </div>+ );+}diff --git a/src/renderer/src/components/triggers/OrgSection.tsx b/src/renderer/src/components/triggers/OrgSection.tsxnew file mode 100644index 00000000..a9181640--- /dev/null+++ b/src/renderer/src/components/triggers/OrgSection.tsx@@ -0,0 +1,79 @@+import { useEffect, useState } from 'react';+import { useStore } from '@/store/store';+import { CLONE_NODE_BLURB, type OrgTriggerConfig, type TriggerMode } from '@shared/triggers';+import { getOrgTrigger, setOrgTrigger as persistOrgTrigger } from './api';+import { Callout, Field, Hint, ModePicker, SecretField, Toggle } from './ui';++/**+ * ORGANISATION — peer messaging between teammates' clone nodes.+ *+ * Configuration only. There is no transport service yet, so a key saved here+ * starts nothing; it is the setting the service will read once it exists. The+ * copy says exactly that rather than implying a connection.+ *+ * Renders off the store mirror that Settings → Connections also renders off, and+ * follows the same mirror-then-persist rule: typing the key updates the mirror+ * (so Settings stays live) and commits on blur; the toggle and the trust mode+ * persist on the spot.+ */+export function OrgSection({ onSummary }: { onSummary?: (s: string) => void }) {+ const cfg = useStore((s) => s.orgTrigger);+ const mirror = useStore((s) => s.setOrgTrigger);+ const [revealed, setRevealed] = useState(false);++ useEffect(() => {+ // Only when the mirror looks unseeded — adopting unconditionally could+ // clobber a key being typed in Settings this second.+ if (useStore.getState().orgTrigger.apiKey) return;+ void getOrgTrigger().then((c) => {+ if (c && !useStore.getState().orgTrigger.apiKey) mirror(c);+ });+ }, [mirror]);++ useEffect(() => {+ onSummary?.(!cfg.apiKey.trim() ? 'no key' : cfg.enabled ? 'on' : 'off');+ }, [cfg, onSummary]);++ const apply = (next: OrgTriggerConfig, persist = true) => {+ mirror(next);+ if (persist) persistOrgTrigger(next);+ };++ const hasKey = cfg.apiKey.trim().length > 0;++ return (+ <>+ <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>+ <span style={{ flex: 1, fontSize: 12, color: 'var(--cth-ink-700)' }}>+ Accept messages from your organisation+ </span>+ <Toggle on={cfg.enabled} onClick={() => apply({ ...cfg, enabled: !cfg.enabled })} />+ </div>++ <Field label="ORGANISATION KEY">+ <SecretField+ value={cfg.apiKey}+ revealed={revealed}+ onReveal={() => setRevealed((r) => !r)}+ placeholder="paste your key"+ onChange={(apiKey) => apply({ ...cfg, apiKey }, false)}+ onBlur={() => apply(cfg)}+ />+ <Hint>{CLONE_NODE_BLURB}</Hint>+ </Field>++ <Field label="TRUST">+ <ModePicker value={cfg.mode} onChange={(mode: TriggerMode) => apply({ ...cfg, mode })} />+ </Field>++ <Callout tone="note">+ Settings only, for now. The org messaging service does not exist yet, so a key here starts no+ connection and nothing is sent or received. It is stored ready for when it does.+ </Callout>++ {cfg.enabled && !hasKey && (+ <Callout>This is switched on with no key set, so no teammate can reach you yet.</Callout>+ )}+ </>+ );+}diff --git a/src/renderer/src/components/triggers/SchedulesSection.tsx b/src/renderer/src/components/triggers/SchedulesSection.tsxnew file mode 100644index 00000000..9fd263e6--- /dev/null+++ b/src/renderer/src/components/triggers/SchedulesSection.tsx@@ -0,0 +1,273 @@+import { useEffect, useState } from 'react';+import { PixelButton } from '../PixelButton';+import { useStore } from '@/store/store';+import {+ Chip, Field, Hint, IntervalPicker, MiniButton, Muted, Select, SubCard, SubHeader,+ Toggle, fmtInterval, inputStyle, textareaStyle+} from './ui';++/**+ * SCHEDULES — recurring auto-dispatched missions. The oldest trigger type, and+ * until now the whole of this tab.+ *+ * Two gaps closed on the way over: a mission's PROMPT (`body`) is now visible on+ * the row and editable when the row is expanded — the seeded missions used to+ * dispatch text nobody could read — and the frequency is editable on every+ * mission, not just the retired compact one.+ */++/** Mirrors `ScheduledMission` in src/main/config.ts (and preload). Declared here+ * so this component owns no cross-package import. */+interface ScheduledMission {+ id: string;+ label: string;+ intervalMs: number;+ to: string;+ body: string;+ enabled: boolean;+ autoCompact?: boolean;+ lastFiredAt?: number;+ kind?: 'dispatch' | 'heartbeat' | 'compact';+ quietThresholdMs?: number;+}++const DEFAULT_INTERVAL_MS = 3_600_000;++function relTime(ms: number): string {+ const past = ms >= 0;+ const a = Math.abs(ms);+ if (a < 45_000) return 'just now';+ const mins = Math.round(a / 60_000);+ const unit = mins < 60 ? `${mins}m` : mins < 1440 ? `${Math.round(mins / 60)}h` : `${Math.round(mins / 1440)}d`;+ return past ? `${unit} ago` : `in ${unit}`;+}++export function SchedulesSection({ onSummary }: { onSummary?: (s: string) => void }) {+ const agents = useStore((s) => s.agents);+ const [missions, setMissions] = useState<ScheduledMission[]>([]);+ const [adding, setAdding] = useState(false);+ const [mLabel, setMLabel] = useState('');+ const [mInterval, setMInterval] = useState<number>(DEFAULT_INTERVAL_MS);+ const [mTo, setMTo] = useState<string>('god');+ const [mBody, setMBody] = useState('');++ useEffect(() => {+ const load = () => { window.cth.listMissions().then(setMissions).catch(() => { /* noop */ }); };+ load();+ // Refresh "last fired" when the scheduler stamps a beat/dispatch.+ return window.cth.onMissionsUpdated(load);+ }, []);++ useEffect(() => {+ const on = missions.filter((m) => m.enabled).length;+ onSummary?.(missions.length === 0 ? 'none' : `${on} of ${missions.length} on`);+ }, [missions, onSummary]);++ // Optimistic: the list is the truth on screen the moment you click, and the+ // write is fire-and-forget (the house pattern across the Command Center).+ const persist = (next: ScheduledMission[]) => {+ setMissions(next);+ void window.cth.saveMissions(next).catch(() => { /* noop */ });+ };+ const patch = (id: string, fields: Partial<ScheduledMission>) =>+ persist(missions.map((m) => (m.id === id ? { ...m, ...fields } : m)));+ // The backend merge in missions:save keeps only what the renderer sends back,+ // so deleting is "save the list without it".+ const remove = (id: string) => persist(missions.filter((m) => m.id !== id));++ const add = () => {+ if (!mLabel.trim() || !mBody.trim()) return;+ persist([...missions, {+ id: `m_${Date.now().toString(36)}`,+ label: mLabel.trim(),+ intervalMs: mInterval,+ to: mTo,+ body: mBody.trim(),+ enabled: true+ }]);+ setMLabel(''); setMBody(''); setAdding(false);+ };++ const targetName = (to: string) =>+ to === 'broadcast' ? 'everyone' : to === 'god' ? 'Michael' : agents.find((a) => a.id === to)?.name ?? to;++ return (+ <>+ {missions.length === 0 && <Muted>Nothing is scheduled yet.</Muted>}+ {missions.map((m) => (+ <MissionRow+ key={m.id}+ mission={m}+ targetName={targetName}+ agents={agents}+ onPatch={(fields) => patch(m.id, fields)}+ onDelete={() => remove(m.id)}+ />+ ))}++ {!adding && (+ <div style={{ marginTop: 8 }}>+ <PixelButton variant="secondary" size="sm" onClick={() => setAdding(true)}>add a schedule</PixelButton>+ </div>+ )}+ {adding && (+ <SubCard>+ <div style={{ fontFamily: 'var(--cth-font-display)', fontSize: 8, color: 'var(--cth-ink-500)' }}>NEW SCHEDULE</div>+ <Field label="LABEL">+ <input+ value={mLabel}+ onChange={(e) => setMLabel(e.target.value)}+ placeholder="What this run is for"+ style={inputStyle}+ />+ </Field>+ <Field label="GOES TO">+ <Select value={mTo} onChange={setMTo} style={{ width: '100%' }}>+ <option value="broadcast">everyone</option>+ <option value="god">Michael</option>+ {agents.filter((a) => !a.isGod).map((a) => <option key={a.id} value={a.id}>{a.name}</option>)}+ </Select>+ </Field>+ <Field label="EVERY">+ <IntervalPicker value={mInterval} onChange={setMInterval} />+ </Field>+ <Field label="PROMPT">+ <textarea+ value={mBody}+ onChange={(e) => setMBody(e.target.value)}+ rows={3}+ placeholder="Sent word for word on every run."+ style={textareaStyle}+ />+ </Field>+ <div style={{ display: 'flex', gap: 6, marginTop: 8 }}>+ <PixelButton variant="primary" size="sm" onClick={add} disabled={!mLabel.trim() || !mBody.trim()}>+ add+ </PixelButton>+ <PixelButton variant="ghost" size="sm" onClick={() => { setAdding(false); setMLabel(''); setMBody(''); }}>+ cancel+ </PixelButton>+ </div>+ </SubCard>+ )}+ </>+ );+}++/* ─────────────────────────────── one mission ─────────────────────────────── */++interface RosterAgent { id: string; name: string; isGod?: boolean }++function MissionRow({ mission, targetName, agents, onPatch, onDelete }: {+ mission: ScheduledMission;+ targetName: (to: string) => string;+ agents: RosterAgent[];+ onPatch: (fields: Partial<ScheduledMission>) => void;+ onDelete: () => void;+}) {+ const [open, setOpen] = useState(false);+ const [label, setLabel] = useState(mission.label);+ const [to, setTo] = useState(mission.to);+ const [intervalMs, setIntervalMs] = useState(mission.intervalMs);+ const [body, setBody] = useState(mission.body);+ const [saved, setSaved] = useState(false);++ // Seed the draft when the row opens — never on every render, or the scheduler+ // stamping `lastFiredAt` mid-edit would wipe what you are typing.+ useEffect(() => {+ if (!open) return;+ setLabel(mission.label);+ setTo(mission.to);+ setIntervalMs(mission.intervalMs);+ setBody(mission.body);+ setSaved(false);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [open]);++ const heartbeat = mission.kind === 'heartbeat';+ const dirty = label !== mission.label || to !== mission.to+ || intervalMs !== mission.intervalMs || body !== mission.body;++ const fired = mission.lastFiredAt ? `fired ${relTime(Date.now() - mission.lastFiredAt)}` : 'not yet fired';+ const next = mission.enabled && mission.lastFiredAt+ ? ` · next ${relTime(Date.now() - (mission.lastFiredAt + mission.intervalMs))}`+ : '';++ const save = () => {+ const trimmed = label.trim();+ if (!trimmed) return;+ // Fold the trim back into the draft too, or the row would read as still+ // dirty against a label that was only ever going to be stored trimmed.+ setLabel(trimmed);+ onPatch({ label: trimmed, to, intervalMs, body });+ setSaved(true);+ setTimeout(() => setSaved(false), 1300);+ };++ return (+ <SubCard>+ <SubHeader+ open={open}+ onToggle={() => setOpen((o) => !o)}+ title={+ <span style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}>+ <Chip tone={mission.enabled ? 'on' : 'off'}>+ {heartbeat ? '♥ beat' : fmtInterval(mission.intervalMs)}+ </Chip>+ <span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>+ {mission.label}+ </span>+ </span>+ }+ sub={<>→ {targetName(mission.to)} · {fired}{next}</>}+ right={<Toggle on={mission.enabled} onClick={() => onPatch({ enabled: !mission.enabled })} />}+ />++ {/* The prompt is the mission. Closed, you get the first line of it; open,+ you get the whole thing in an editor. It used to be invisible. */}+ {!open && (+ <div style={{+ marginTop: 6, padding: '4px 6px',+ background: 'var(--cth-paper-100)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-100)',+ fontFamily: 'var(--cth-font-mono)', fontSize: 11, lineHeight: '15px',+ color: 'var(--cth-ink-700)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap'+ }}>{mission.body.trim() || 'No prompt set.'}</div>+ )}++ {open && (+ <div style={{ marginTop: 4 }}>+ <Field label="LABEL">+ <input value={label} onChange={(e) => setLabel(e.target.value)} style={inputStyle} />+ </Field>+ <Field label="GOES TO">+ <Select value={to} onChange={setTo} style={{ width: '100%' }}>+ <option value="broadcast">everyone</option>+ <option value="god">Michael</option>+ {agents.filter((a) => !a.isGod).map((a) => <option key={a.id} value={a.id}>{a.name}</option>)}+ </Select>+ </Field>+ <Field label="EVERY">+ <IntervalPicker value={intervalMs} onChange={setIntervalMs} />+ {heartbeat && <Hint>The beat adapts to how quiet the floor is, so this is the ceiling, not the exact gap.</Hint>}+ </Field>+ <Field label="PROMPT">+ <textarea+ value={body}+ onChange={(e) => setBody(e.target.value)}+ rows={4}+ placeholder="Sent word for word on every run."+ style={textareaStyle}+ />+ </Field>+ <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 8 }}>+ <PixelButton variant="primary" size="sm" onClick={save} disabled={!dirty || !label.trim()}>+ {saved && !dirty ? 'saved' : 'save'}+ </PixelButton>+ <span style={{ flex: 1 }} />+ <MiniButton tone="danger" onClick={onDelete}>delete</MiniButton>+ </div>+ </div>+ )}+ </SubCard>+ );+}diff --git a/src/renderer/src/components/triggers/TriggerHistoryTab.tsx b/src/renderer/src/components/triggers/TriggerHistoryTab.tsxnew file mode 100644index 00000000..81c94cce--- /dev/null+++ b/src/renderer/src/components/triggers/TriggerHistoryTab.tsx@@ -0,0 +1,564 @@+import { useCallback, useEffect, useMemo, useState, type CSSProperties } from 'react';+import { PixelButton } from '../PixelButton';+import type { TriggerHistoryEntry } from '@shared/triggers';++/**+ * TRIGGER HISTORY — the ledger of everything an outside party said to this hive+ * and everything we said back, read as conversations rather than log lines.+ *+ * The ledger is flat (one row per message, newest first). The operator's actual+ * question is never "what rows exist" but "what did they ask, and what did we+ * answer" — so rows are folded into EXCHANGES by `correlationId` here, in the+ * renderer, and drawn as one card per exchange with both bodies in full.+ *+ * Two sources share the ledger (webhook, org) and they are switched, not+ * stacked: this lives in a ~360px sidebar, so two full lists on one scroll+ * would bury whichever one you came for.+ *+ * The only actionable rows are inbound messages a `strict` /+ * `communication-only` trigger mode held back (`decision: 'pending'`). Those+ * float to the top of their section, because approving one dispatches real+ * work into the hive and a held message that scrolls out of sight is a message+ * that never gets answered.+ */++/* ─────────────────────────────── ipc surface ─────────────────────────────── */++/**+ * The trigger-history IPC lands with the main-process change that owns preload;+ * the typed `window.cth` members arrive with it. Until then this narrow local+ * surface + one cast keeps the tab compiling without touching preload — and+ * needs no edit once the real types show up, since the shapes match.+ */+interface TriggerHistoryApi {+ listTriggerHistory?: () => Promise<TriggerHistoryEntry[]>;+ onTriggerHistoryUpdated?: (cb: () => void) => () => void;+ decideTriggerHistory?: (input: {+ id: string;+ decision: 'approved' | 'rejected';+ }) => Promise<{ ok?: boolean; error?: string } | undefined>;+ clearTriggerHistory?: (source?: 'webhook' | 'org') => Promise<unknown>;+}++/** Read lazily: `window.cth` is installed by preload, not by module load order. */+function api(): TriggerHistoryApi {+ return (window.cth ?? {}) as unknown as TriggerHistoryApi;+}++/* ─────────────────────────────── exchanges ───────────────────────────────── */++type Source = 'webhook' | 'org';++interface Exchange {+ key: string;+ /** Oldest first — an exchange reads downward, the way the conversation happened. */+ msgs: TriggerHistoryEntry[];+ /** Whose name and peer label the card: the inbound that started it, else the lone outbound. */+ head: TriggerHistoryEntry;+ /** The inbound still held for the operator, if any. */+ pending: TriggerHistoryEntry | null;+ answered: boolean;+ latestAt: number;+}++/**+ * Fold the flat ledger into exchanges.+ *+ * `correlationId` is the pairing key. Rows without one cannot be paired with+ * anything, so each becomes its own one-sided exchange keyed by its id — an+ * un-correlated inbound still deserves a card (it may be pending), and an+ * un-correlated outbound is a message we sent that simply has no recorded+ * prompt. A correlation group may also hold more than two rows (a follow-up, a+ * second reply); those render in time order rather than being dropped.+ *+ * Pending exchanges sort to the top; everything else stays newest-first.+ */+function buildExchanges(rows: TriggerHistoryEntry[]): Exchange[] {+ const buckets = new Map<string, TriggerHistoryEntry[]>();+ const order: string[] = [];+ for (const e of rows) {+ const key = e.correlationId ? `c:${e.correlationId}` : `e:${e.id}`;+ const bucket = buckets.get(key);+ if (bucket) bucket.push(e);+ else { buckets.set(key, [e]); order.push(key); }+ }+ const list = order.map<Exchange>((key) => {+ const msgs = (buckets.get(key) ?? []).slice().sort((a, b) => a.at - b.at);+ const inbound = msgs.find((m) => m.direction === 'inbound');+ return {+ key,+ msgs,+ head: inbound ?? msgs[0],+ pending: msgs.find((m) => m.direction === 'inbound' && m.decision === 'pending') ?? null,+ answered: msgs.some((m) => m.direction === 'outbound'),+ latestAt: msgs.reduce((max, m) => Math.max(max, m.at), 0)+ };+ });+ return list.sort((a, b) => {+ if (!!a.pending !== !!b.pending) return a.pending ? -1 : 1;+ return b.latestAt - a.latestAt;+ });+}++/* ──────────────────────────────── helpers ────────────────────────────────── */++// Copied, not imported: SchedulesTab.tsx is being deleted.+function relTime(ms: number): string {+ const past = ms >= 0;+ const a = Math.abs(ms);+ if (a < 45_000) return 'just now';+ const mins = Math.round(a / 60_000);+ const unit = mins < 60 ? `${mins}m` : mins < 1440 ? `${Math.round(mins / 60)}h` : `${Math.round(mins / 1440)}d`;+ return past ? `${unit} ago` : `in ${unit}`;+}++const CLAMP_CHARS = 320;+const CLAMP_LINES = 8;++/** Collapse a long body for the resting state. Expanding always shows all of it. */+function clampBody(body: string): { text: string; clipped: boolean } {+ const lines = body.split('\n');+ if (body.length <= CLAMP_CHARS && lines.length <= CLAMP_LINES) return { text: body, clipped: false };+ const head = lines.slice(0, CLAMP_LINES).join('\n');+ const cut = head.length > CLAMP_CHARS ? head.slice(0, CLAMP_CHARS).replace(/\s+\S*$/, '') : head;+ return { text: `${cut.trimEnd()}…`, clipped: true };+}++/* ───────────────────────────────── styles ────────────────────────────────── */++const tinyCaps: CSSProperties = {+ fontFamily: 'var(--cth-font-display)', fontSize: 9, lineHeight: '12px',+ color: 'var(--cth-ink-500)'+};+const uiText: CSSProperties = {+ fontFamily: 'var(--cth-font-ui)', fontSize: 12, lineHeight: '17px',+ color: 'var(--cth-ink-900)'+};+const muted: CSSProperties = { ...uiText, color: 'var(--cth-ink-500)' };+const ellipsis: CSSProperties = { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' };++const cardStyle: CSSProperties = {+ background: 'var(--cth-paper-100)',+ boxShadow: 'inset 0 0 0 1px var(--cth-ink-100)',+ padding: 8, display: 'flex', flexDirection: 'column', gap: 8, minWidth: 0+};+const pendingCardStyle: CSSProperties = {+ ...cardStyle,+ background: 'var(--cth-cream-100)',+ boxShadow: 'inset 0 0 0 2px var(--cth-lemon)'+};+const bodyBox: CSSProperties = {+ background: 'var(--cth-cream-200)',+ boxShadow: 'inset 0 0 0 1px var(--cth-ink-100)',+ padding: '6px 8px',+ fontFamily: 'var(--cth-font-mono)', fontSize: 12, lineHeight: '17px',+ color: 'var(--cth-ink-900)',+ whiteSpace: 'pre-wrap', overflowWrap: 'anywhere', wordBreak: 'break-word'+};+const linkButton: CSSProperties = {+ background: 'none', border: 'none', padding: 0, cursor: 'pointer',+ fontFamily: 'var(--cth-font-ui)', fontSize: 11, lineHeight: '16px',+ color: 'var(--cth-ink-700)', textDecoration: 'underline', textAlign: 'left'+};++function badgeStyle(fill: string, line: string): CSSProperties {+ return {+ fontFamily: 'var(--cth-font-display)', fontSize: 9, lineHeight: '12px',+ padding: '3px 5px 2px', background: fill, boxShadow: `inset 0 0 0 1px ${line}`,+ color: 'var(--cth-ink-900)', flexShrink: 0+ };+}++function Badge({ fill, line, children }: { fill: string; line: string; children: string }) {+ return <span style={badgeStyle(fill, line)}>{children}</span>;+}++function KindBadge({ kind }: { kind: TriggerHistoryEntry['kind'] }) {+ return kind === 'directive'+ ? <Badge fill="var(--cth-lemon-light)" line="var(--cth-lemon)">directive</Badge>+ : <Badge fill="var(--cth-sky-light)" line="var(--cth-sky)">communication</Badge>;+}++function DecisionBadge({ decision }: { decision: NonNullable<TriggerHistoryEntry['decision']> }) {+ switch (decision) {+ case 'pending':+ return <Badge fill="var(--cth-lemon-light)" line="var(--cth-lemon)">needs you</Badge>;+ case 'approved':+ return <Badge fill="var(--cth-mint-light)" line="var(--cth-mint)">approved</Badge>;+ case 'rejected':+ return <Badge fill="var(--cth-coral-light)" line="var(--cth-coral)">rejected</Badge>;+ default:+ return <Badge fill="var(--cth-cream-200)" line="var(--cth-ink-300)">auto-allowed</Badge>;+ }+}++/* ─────────────────────────────── one message ─────────────────────────────── */++function MessageBlock({+ msg,+ label,+ expanded,+ onToggle+}: {+ msg: TriggerHistoryEntry;+ label: string;+ expanded: boolean;+ onToggle: () => void;+}) {+ const body = msg.body ?? '';+ const { text, clipped } = useMemo(() => clampBody(body), [body]);+ return (+ <div style={{ display: 'flex', flexDirection: 'column', gap: 4, minWidth: 0 }}>+ <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, justifyContent: 'space-between' }}>+ <span style={tinyCaps}>{label}</span>+ <span style={{ ...tinyCaps, flexShrink: 0 }}>{relTime(Date.now() - msg.at)}</span>+ </div>+ <div style={bodyBox}>{body.trim() ? (expanded ? body : text) : '(empty message)'}</div>+ {clipped && (+ <button type="button" onClick={onToggle} style={linkButton}>+ {expanded ? 'show less' : `show all ${body.length} characters`}+ </button>+ )}+ </div>+ );+}++/* ────────────────────────────── one exchange ─────────────────────────────── */++function ExchangeCard({+ ex,+ expanded,+ toggle,+ busy,+ onDecide+}: {+ ex: Exchange;+ expanded: Record<string, boolean>;+ toggle: (id: string) => void;+ busy: Record<string, boolean>;+ onDecide: (id: string, decision: 'approved' | 'rejected') => void;+}) {+ const head = ex.head;+ const hasInbound = ex.msgs.some((m) => m.direction === 'inbound');+ const decision = head.decision;+ const pending = ex.pending;+ const taskId = ex.msgs.find((m) => m.taskId)?.taskId;++ // The trailing line for an exchange with nothing sent back yet. Silence here+ // is normal — it is a message still in flight, never a failure.+ const tail = (() => {+ if (pending || ex.answered) return null;+ if (decision === 'rejected') return 'You turned this down. Nothing was sent to the hive.';+ return 'No reply yet. Michael has this one.';+ })();++ return (+ <div style={pending ? pendingCardStyle : cardStyle}>+ {pending && (+ <div style={{+ background: 'var(--cth-lemon-light)', boxShadow: 'inset 0 0 0 1px var(--cth-lemon)',+ padding: '4px 6px 3px', ...tinyCaps, color: 'var(--cth-ink-900)'+ }}>+ WAITING FOR YOU+ </div>+ )}++ <div style={{ display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 }}>+ <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, justifyContent: 'space-between' }}>+ <span style={{ ...uiText, ...ellipsis, minWidth: 0 }} title={head.sourceName}>+ {head.sourceName || 'unnamed source'}+ </span>+ <span style={{ ...tinyCaps, flexShrink: 0 }}>{relTime(Date.now() - ex.latestAt)}</span>+ </div>+ <div style={{ ...muted, ...ellipsis, fontSize: 11 }} title={head.peer}>+ {hasInbound ? 'from' : 'to'} {head.peer || 'unknown'}+ </div>+ {head.title && (+ <div style={{ ...uiText, ...ellipsis, color: 'var(--cth-ink-700)' }} title={head.title}>+ {head.title}+ </div>+ )}+ </div>++ <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>+ <KindBadge kind={head.kind} />+ {decision && <DecisionBadge decision={decision} />}+ </div>++ {ex.msgs.map((m) => (+ <MessageBlock+ key={m.id}+ msg={m}+ label={m.direction === 'inbound' ? 'THEY SENT' : hasInbound ? 'WE REPLIED' : 'WE SENT'}+ expanded={!!expanded[m.id]}+ onToggle={() => toggle(m.id)}+ />+ ))}++ {pending && (+ <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>+ <div style={{ ...uiText, fontSize: 11, lineHeight: '16px', color: 'var(--cth-ink-700)' }}>+ {pending.kind === 'directive'+ ? 'Approve and this goes to Michael, who will put the hive to work on it. Reject and it is dropped — nothing runs.'+ : 'Approve and Michael reads this. Reject and it is dropped — nothing runs.'}+ </div>+ <div style={{ display: 'flex', gap: 6 }}>+ <PixelButton+ variant="primary"+ size="sm"+ disabled={!!busy[pending.id]}+ onClick={() => onDecide(pending.id, 'approved')}+ title="Send this message through to Michael"+ >+ {busy[pending.id] ? 'one sec…' : 'approve'}+ </PixelButton>+ <PixelButton+ variant="secondary"+ size="sm"+ disabled={!!busy[pending.id]}+ onClick={() => onDecide(pending.id, 'rejected')}+ title="Drop this message. Nothing is sent"+ >+ reject+ </PixelButton>+ </div>+ </div>+ )}++ {tail && <div style={{ ...muted, fontSize: 11 }}>{tail}</div>}++ {taskId && (+ <div style={{ ...tinyCaps, ...ellipsis }} title={taskId}>TASK {taskId}</div>+ )}+ </div>+ );+}++/* ───────────────────────────── empty states ──────────────────────────────── */++function EmptyState({ title, body }: { title: string; body: string }) {+ return (+ <div style={{ ...cardStyle, gap: 4 }}>+ <div style={uiText}>{title}</div>+ <div style={{ ...muted, fontSize: 11, lineHeight: '16px' }}>{body}</div>+ </div>+ );+}++const SECTIONS: { key: Source; label: string; blurb: string }[] = [+ {+ key: 'webhook',+ label: 'Webhooks',+ blurb: 'Everything posted to your webhook endpoints, next to what Michael sent back.'+ },+ {+ key: 'org',+ label: 'Organization',+ blurb: 'Messages from your teammates’ clone nodes, next to what Michael sent back.'+ }+];++/* ──────────────────────────────── the tab ────────────────────────────────── */++export function TriggerHistoryTab() {+ const [entries, setEntries] = useState<TriggerHistoryEntry[]>([]);+ const [source, setSource] = useState<Source>('webhook');+ const [expanded, setExpanded] = useState<Record<string, boolean>>({});+ const [busy, setBusy] = useState<Record<string, boolean>>({});+ const [confirmClear, setConfirmClear] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const load = useCallback(() => {+ const list = api().listTriggerHistory;+ if (!list) return;+ list()+ .then((rows) => setEntries(Array.isArray(rows) ? rows : []))+ .catch(() => { /* main not ready; the update event will bring us back */ });+ }, []);++ useEffect(() => {+ load();+ // Same shape as onMissionsUpdated: subscribe, get an unsubscribe back.+ const off = api().onTriggerHistoryUpdated?.(load);+ return () => { if (typeof off === 'function') off(); };+ }, [load]);++ const toggle = useCallback((id: string) => {+ setExpanded((e) => ({ ...e, [id]: !e[id] }));+ }, []);++ const decide = useCallback((id: string, decision: 'approved' | 'rejected') => {+ const call = api().decideTriggerHistory;+ if (!call) return;+ setBusy((b) => ({ ...b, [id]: true }));+ setError(null);+ // Optimistic: the row's verdict is the operator's own input, so it should+ // land the instant they click. The update event reconciles either way.+ setEntries((rows) => rows.map((r) => (r.id === id ? { ...r, decision } : r)));+ call({ id, decision })+ .then((res) => {+ if (res && res.ok === false) {+ setError(res.error || 'That did not go through. Try again.');+ load();+ }+ })+ .catch(() => { setError('That did not go through. Try again.'); load(); })+ .finally(() => setBusy((b) => { const n = { ...b }; delete n[id]; return n; }));+ }, [load]);++ const clear = useCallback(() => {+ const call = api().clearTriggerHistory;+ setConfirmClear(false);+ if (!call) return;+ setEntries((rows) => rows.filter((r) => r.source !== source));+ call(source).catch(() => { setError('Could not clear it. Try again.'); load(); });+ }, [source, load]);++ const counts = useMemo(() => {+ const c: Record<Source, { total: number; pending: number }> = {+ webhook: { total: 0, pending: 0 },+ org: { total: 0, pending: 0 }+ };+ for (const e of entries) {+ const bucket = c[e.source];+ if (!bucket) continue;+ bucket.total += 1;+ if (e.direction === 'inbound' && e.decision === 'pending') bucket.pending += 1;+ }+ return c;+ }, [entries]);++ const exchanges = useMemo(+ () => buildExchanges(entries.filter((e) => e.source === source)),+ [entries, source]+ );++ const section = SECTIONS.find((s) => s.key === source) ?? SECTIONS[0];+ const pendingCount = counts[source].pending;++ return (+ <div style={{+ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column',+ background: 'var(--cth-paper-200)'+ }}>+ {/* Section switcher — the panel is too narrow to stack both lists. */}+ <div style={{+ display: 'flex', flexShrink: 0,+ background: 'var(--cth-cream-200)', boxShadow: 'inset 0 -1px 0 var(--cth-ink-300)'+ }}>+ {SECTIONS.map((s) => {+ const active = s.key === source;+ const p = counts[s.key].pending;+ return (+ <button+ key={s.key}+ type="button"+ onClick={() => { setSource(s.key); setConfirmClear(false); setError(null); }}+ style={{+ flex: 1, height: 32, padding: '0 8px', border: 'none', cursor: 'pointer',+ background: active ? 'var(--cth-paper-200)' : 'transparent',+ boxShadow: active ? 'inset 0 -2px 0 var(--cth-ink-900)' : 'none',+ fontFamily: 'var(--cth-font-display)', fontSize: 9, lineHeight: '12px',+ color: active ? 'var(--cth-ink-900)' : 'var(--cth-ink-500)',+ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 4,+ minWidth: 0+ }}+ >+ <span style={ellipsis}>{s.label.toUpperCase()}</span>+ {p > 0 && (+ <span style={{+ ...badgeStyle('var(--cth-lemon-light)', 'var(--cth-lemon)'),+ padding: '2px 4px 1px'+ }}>{p}</span>+ )}+ </button>+ );+ })}+ </div>++ <div style={{+ flex: 1, minHeight: 0, overflowY: 'auto', overflowX: 'hidden',+ padding: 8, display: 'flex', flexDirection: 'column', gap: 8+ }}>+ <div style={{ ...muted, fontSize: 11, lineHeight: '16px' }}>{section.blurb}</div>++ {pendingCount > 0 && (+ <div style={{+ background: 'var(--cth-lemon-light)', boxShadow: 'inset 0 0 0 1px var(--cth-lemon)',+ padding: '6px 8px', ...uiText, fontSize: 11, lineHeight: '16px'+ }}>+ {pendingCount === 1+ ? 'One message is held, waiting on your yes or no.'+ : `${pendingCount} messages are held, waiting on your yes or no.`}+ </div>+ )}++ {error && (+ <div style={{+ background: 'var(--cth-coral-light)', boxShadow: 'inset 0 0 0 1px var(--cth-coral)',+ padding: '6px 8px', ...uiText, fontSize: 11, lineHeight: '16px'+ }}>{error}</div>+ )}++ {exchanges.length === 0 ? (+ source === 'org' ? (+ <EmptyState+ title="Nothing here yet, and nothing is broken."+ body={'Teammate messaging is not built yet. You can set an org key and pick a mode '+ + 'today, but no one’s clone node can reach yours until the transport ships. '+ + 'When it does, their messages and our replies land here.'}+ />+ ) : (+ <EmptyState+ title="No webhook messages yet."+ body={'When something posts to one of your endpoints, it lands here with Michael’s '+ + 'reply underneath. Nothing has called in so far. Add an endpoint under Webhooks to '+ + 'get a URL you can hand out.'}+ />+ )+ ) : (+ exchanges.map((ex) => (+ <ExchangeCard+ key={ex.key}+ ex={ex}+ expanded={expanded}+ toggle={toggle}+ busy={busy}+ onDecide={decide}+ />+ ))+ )}++ {counts[source].total > 0 && (+ <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginTop: 4 }}>+ {confirmClear ? (+ <>+ <div style={{ ...muted, fontSize: 11, lineHeight: '16px' }}>+ Delete all {counts[source].total} {section.label.toLowerCase()} messages? The record+ is gone for good.+ </div>+ <div style={{ display: 'flex', gap: 6 }}>+ <PixelButton variant="destructive" size="sm" onClick={clear}>delete them</PixelButton>+ <PixelButton variant="ghost" size="sm" onClick={() => setConfirmClear(false)}>+ keep them+ </PixelButton>+ </div>+ </>+ ) : (+ <div>+ <PixelButton+ variant="ghost"+ size="sm"+ onClick={() => setConfirmClear(true)}+ title="Delete this section’s history"+ >+ clear history+ </PixelButton>+ </div>+ )}+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/src/renderer/src/components/triggers/TriggersTab.tsx b/src/renderer/src/components/triggers/TriggersTab.tsxnew file mode 100644index 00000000..83b57a3a--- /dev/null+++ b/src/renderer/src/components/triggers/TriggersTab.tsx@@ -0,0 +1,64 @@+import { useState } from 'react';+import { SchedulesSection } from './SchedulesSection';+import { ContextSection } from './ContextSection';+import { WebhooksSection } from './WebhooksSection';+import { OrgSection } from './OrgSection';+import { Muted, Scroll, TriggerCard } from './ui';++/**+ * TRIGGERS — every way the floor gets woken up without a human typing, in one+ * tab. Four types (src/shared/triggers.ts is the contract): schedules, context,+ * webhooks and organisation. Schedules is the oldest and used to BE this tab.+ *+ * This panel is a sidebar, so four flat forms would open as a wall. Each type is+ * a collapsed card carrying its name, a one-line "what this is", and a live+ * summary chip; schedules opens expanded because it is the incumbent and the+ * office calendar deep-links here. Inside a card, each row collapses the same+ * way, so nothing is more than two disclosures from legible.+ */+export function TriggersTab() {+ const [schedulesSummary, setSchedulesSummary] = useState('');+ const [contextSummary, setContextSummary] = useState('');+ const [webhooksSummary, setWebhooksSummary] = useState('');+ const [orgSummary, setOrgSummary] = useState('');++ return (+ <Scroll>+ <Muted>Everything that can start work without you typing.</Muted>+ <div style={{ height: 8 }} />++ <TriggerCard+ title="SCHEDULES"+ blurb="Run a prompt on a repeating clock."+ summary={schedulesSummary}+ defaultOpen+ >+ <SchedulesSection onSummary={setSchedulesSummary} />+ </TriggerCard>++ <TriggerCard+ title="CONTEXT"+ blurb="Compact or clear an agent as its context fills."+ summary={contextSummary}+ >+ <ContextSection onSummary={setContextSummary} />+ </TriggerCard>++ <TriggerCard+ title="WEBHOOKS"+ blurb="Let an outside system post work in."+ summary={webhooksSummary}+ >+ <WebhooksSection onSummary={setWebhooksSummary} />+ </TriggerCard>++ <TriggerCard+ title="ORGANISATION"+ blurb="Let a teammate's Munder Difflin message yours."+ summary={orgSummary}+ >+ <OrgSection onSummary={setOrgSummary} />+ </TriggerCard>+ </Scroll>+ );+}diff --git a/src/renderer/src/components/triggers/WebhooksSection.tsx b/src/renderer/src/components/triggers/WebhooksSection.tsxnew file mode 100644index 00000000..bf952c19--- /dev/null+++ b/src/renderer/src/components/triggers/WebhooksSection.tsx@@ -0,0 +1,276 @@+import { useEffect, useRef, useState } from 'react';+import { PixelButton } from '../PixelButton';+import { useStore } from '@/store/store';+import { TRIGGER_MODES, type TriggerMode, type WebhookTrigger } from '@shared/triggers';+import {+ deleteWebhook, generateWebhookSecret, listWebhooks, newWebhook, saveWebhooks,+ webhooksStatus, type WebhooksStatus+} from './api';+import { JsonEditor } from './JsonEditor';+import {+ Callout, Field, Hint, MiniButton, ModePicker, Muted, SecretField, SubCard, SubHeader,+ Toggle, inputStyle+} from './ui';++/**+ * WEBHOOKS — one inbound HTTP endpoint per caller. Several share one port and+ * one tunnel and are told apart by the id in the path, so the URL you hand out+ * is per endpoint, never the tunnel root.+ *+ * The list lives in the store, not here. Settings → Connections edits the same+ * endpoints off the same mirror, so a save on either surface repaints the other+ * with no refetch — two local copies would drift the moment either one wrote.+ *+ * MIRROR-THEN-PERSIST: keystroke edits (a name) update the mirror only, so the+ * other surface stays live while you type without a disk write per character;+ * everything discrete (toggle, mode, schema, add, delete) persists on the spot.+ */++const STATUS_POLL_MS = 5000;++export function WebhooksSection({ onSummary }: { onSummary?: (s: string) => void }) {+ const hooks = useStore((s) => s.webhookTriggers);+ const setHooks = useStore((s) => s.setWebhookTriggers);+ const [status, setStatus] = useState<WebhooksStatus>({ running: false, endpoints: [] });+ const [minting, setMinting] = useState(false);++ useEffect(() => {+ let alive = true;+ // App seeds the mirror from getConfig() at boot, and both editing surfaces+ // keep it current — so this read only covers the case where it was never+ // seeded. Adopting unconditionally could clobber an edit being typed in+ // Settings right now.+ if (useStore.getState().webhookTriggers.length === 0) {+ void listWebhooks().then((l) => {+ if (alive && l && useStore.getState().webhookTriggers.length === 0) setHooks(l);+ });+ }+ const poll = () => { void webhooksStatus().then((s) => { if (alive) setStatus(s); }); };+ poll();+ const t = setInterval(poll, STATUS_POLL_MS);+ return () => { alive = false; clearInterval(t); };+ }, [setHooks]);++ useEffect(() => {+ onSummary?.(hooks.length === 0 ? 'none' : `${hooks.length} · ${status.running ? 'live' : 'offline'}`);+ }, [hooks, status.running, onSummary]);++ /** Update the shared mirror; optionally write it through. Main sanitises what+ * it stores (it will not enable a secretless endpoint), so we adopt its+ * answer when it comes back rather than assuming ours was accepted. */+ const apply = (next: WebhookTrigger[], persist = true) => {+ setHooks(next);+ if (!persist) return;+ void saveWebhooks(next).then((canonical) => { if (canonical) setHooks(canonical); });+ };+ const patch = (id: string, fields: Partial<WebhookTrigger>, persist = true) =>+ apply(hooks.map((w) => (w.id === id ? { ...w, ...fields } : w)), persist);++ const remove = (id: string) => {+ setHooks(hooks.filter((w) => w.id !== id));+ void deleteWebhook(id).then((canonical) => { if (canonical) setHooks(canonical); });+ };++ const add = async () => {+ setMinting(true);+ try {+ const secret = await generateWebhookSecret();+ apply([...hooks, newWebhook(secret, hooks.length)]);+ } finally {+ setMinting(false);+ }+ };++ const urlFor = (id: string) => status.endpoints.find((e) => e.id === id)?.url ?? '';++ return (+ <>+ <Muted>+ Anyone holding a URL and its secret can post work in. Each endpoint carries its own secret,+ so revoking one caller leaves the others alone.+ </Muted>+ <div style={{ height: 8 }} />++ {hooks.length === 0 && <Muted>No endpoints yet.</Muted>}+ {hooks.map((w) => (+ <WebhookRow+ key={w.id}+ hook={w}+ url={urlFor(w.id)}+ serverRunning={status.running}+ onPatch={(fields, persist) => patch(w.id, fields, persist)}+ onDelete={() => remove(w.id)}+ />+ ))}++ <div style={{ marginTop: 8 }}>+ <PixelButton variant="secondary" size="sm" onClick={() => { void add(); }} disabled={minting}>+ {minting ? 'minting…' : 'add webhook'}+ </PixelButton>+ <Hint>A new endpoint starts switched off. Copy its URL and secret, then turn it on.</Hint>+ </div>+ </>+ );+}++/* ─────────────────────────────── one endpoint ────────────────────────────── */++function WebhookRow({ hook, url, serverRunning, onPatch, onDelete }: {+ hook: WebhookTrigger;+ url: string;+ serverRunning: boolean;+ onPatch: (fields: Partial<WebhookTrigger>, persist?: boolean) => void;+ onDelete: () => void;+}) {+ const [open, setOpen] = useState(false);+ const [revealed, setRevealed] = useState(false);+ const [copied, setCopied] = useState<'url' | 'secret' | null>(null);+ const [schemaOpen, setSchemaOpen] = useState(false);+ const [schemaText, setSchemaText] = useState(hook.schema);+ const [schemaError, setSchemaError] = useState<string | null>(null);+ const [schemaSaved, setSchemaSaved] = useState(false);+ const [confirmDelete, setConfirmDelete] = useState(false);+ const copyTimer = useRef<ReturnType<typeof setTimeout> | null>(null);++ // A closed row must not keep a revealed secret on screen, and re-opening the+ // schema editor should start from what is actually stored.+ useEffect(() => {+ if (open) return;+ setRevealed(false);+ setSchemaOpen(false);+ setConfirmDelete(false);+ }, [open]);++ useEffect(() => {+ if (!schemaOpen) return;+ setSchemaText(hook.schema);+ setSchemaError(null);+ setSchemaSaved(false);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [schemaOpen]);++ useEffect(() => () => { if (copyTimer.current) clearTimeout(copyTimer.current); }, []);++ const copy = (what: 'url' | 'secret', text: string) => {+ void window.cth.copyToClipboard(text).catch(() => { /* noop */ });+ setCopied(what);+ if (copyTimer.current) clearTimeout(copyTimer.current);+ copyTimer.current = setTimeout(() => setCopied(null), 1300);+ };++ const saveSchema = () => {+ try {+ JSON.parse(schemaText);+ } catch (e) {+ // Never persist a schema that cannot be parsed — a broken one would lock+ // the caller out of their own endpoint with nothing on screen to say why.+ setSchemaError(e instanceof Error ? e.message : String(e));+ return;+ }+ setSchemaError(null);+ onPatch({ schema: schemaText });+ setSchemaSaved(true);+ setTimeout(() => setSchemaSaved(false), 1300);+ };++ const modeLabel = TRIGGER_MODES.find((m) => m.value === hook.mode)?.label ?? hook.mode;++ return (+ <SubCard>+ <SubHeader+ open={open}+ onToggle={() => setOpen((o) => !o)}+ title={hook.name || 'unnamed'}+ sub={<>{modeLabel} · {url ? 'reachable' : serverRunning ? 'no URL yet' : 'server offline'}</>}+ right={<Toggle on={hook.enabled} onClick={() => onPatch({ enabled: !hook.enabled })} />}+ />++ {open && (+ <div style={{ marginTop: 4 }}>+ <Field label="NAME">+ {/* Mirror while typing, write through on blur. */}+ <input+ value={hook.name}+ onChange={(e) => onPatch({ name: e.target.value }, false)}+ onBlur={() => onPatch({ name: hook.name })}+ placeholder="Who calls this"+ style={inputStyle}+ />+ </Field>++ <Field label="POST TO">+ {url ? (+ <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>+ <span style={{+ flex: 1, minWidth: 0, padding: '4px 6px',+ background: 'var(--cth-paper-100)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-100)',+ fontFamily: 'var(--cth-font-mono)', fontSize: 11, lineHeight: '15px',+ color: 'var(--cth-ink-900)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap'+ }}>{url}</span>+ <MiniButton onClick={() => copy('url', url)} tone={copied === 'url' ? 'good' : 'plain'}>+ {copied === 'url' ? 'copied' : 'copy'}+ </MiniButton>+ </div>+ ) : (+ <Hint>+ {serverRunning+ ? 'This endpoint has no public address yet. It appears once the tunnel picks it up.'+ : 'The webhook server is not listening, so there is no address to hand out yet.'}+ </Hint>+ )}+ </Field>++ <Field label="SECRET">+ <SecretField+ value={hook.secret}+ revealed={revealed}+ onReveal={() => setRevealed((r) => !r)}+ onCopy={() => copy('secret', hook.secret)}+ copied={copied === 'secret'}+ />+ <Hint>Callers echo this in the x-md-webhook-secret header.</Hint>+ </Field>++ <Field label="TRUST">+ <ModePicker value={hook.mode} onChange={(mode: TriggerMode) => onPatch({ mode })} />+ </Field>++ <Field label="BODY SCHEMA">+ {!schemaOpen && (+ <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>+ <MiniButton onClick={() => setSchemaOpen(true)}>edit schema</MiniButton>+ <span style={{ fontSize: 11, color: 'var(--cth-ink-500)' }}>+ what an inbound body must look like+ </span>+ </div>+ )}+ {schemaOpen && (+ <>+ <JsonEditor value={schemaText} onChange={(v) => { setSchemaText(v); setSchemaError(null); }} />+ {schemaError && <Callout>Not valid JSON — {schemaError}. Nothing was saved.</Callout>}+ <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 6 }}>+ <PixelButton variant="primary" size="sm" onClick={saveSchema}>+ {schemaSaved ? 'saved' : 'save schema'}+ </PixelButton>+ <PixelButton variant="ghost" size="sm" onClick={() => setSchemaOpen(false)}>close</PixelButton>+ </div>+ </>+ )}+ </Field>++ <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 10 }}>+ <span style={{ flex: 1 }} />+ {!confirmDelete && <MiniButton tone="danger" onClick={() => setConfirmDelete(true)}>delete</MiniButton>}+ {confirmDelete && (+ <>+ <span style={{ fontSize: 11, color: 'var(--cth-ink-500)' }}>Sure?</span>+ <MiniButton tone="danger" onClick={onDelete}>delete it</MiniButton>+ <MiniButton onClick={() => setConfirmDelete(false)}>keep</MiniButton>+ </>+ )}+ </div>+ </div>+ )}+ </SubCard>+ );+}diff --git a/src/renderer/src/components/triggers/api.ts b/src/renderer/src/components/triggers/api.tsnew file mode 100644index 00000000..751cabc2--- /dev/null+++ b/src/renderer/src/components/triggers/api.ts@@ -0,0 +1,154 @@+import {+ DEFAULT_CONTEXT_TRIGGER,+ DEFAULT_TRIGGER_MODE,+ DEFAULT_WEBHOOK_SCHEMA,+ type ContextRule,+ type ContextTriggerConfig,+ type OrgTriggerConfig,+ type WebhookTrigger+} from '@shared/triggers';++/**+ * TRIGGER IPC — the renderer's side of the trigger config surface.+ *+ * Thin on purpose: `window.cth` already types every call (preload bridges+ * `triggers:*`, `webhooks:*` and `org:*`), so this module exists only for the+ * three things a raw invoke does not do — deep-fill a half-written context rule+ * before it reaches a number input, turn a rejected read into "keep what you+ * have" rather than "adopt nothing", and mint a new endpoint in the same shape+ * Settings → Connections mints one.+ */++/** Shape flows from preload's `webhooks:status` handler, derived rather than+ * retyped (the WorkersTab convention) so it cannot drift from the real reply. */+export type WebhooksStatus = Awaited<ReturnType<typeof window.cth.webhooksStatus>>;++/* ───────────────────────────── context trigger ───────────────────────────── */++function fillRule(partial: Partial<ContextRule> | undefined, fallback: ContextRule): ContextRule {+ return {+ enabled: partial?.enabled ?? fallback.enabled,+ everyMs: typeof partial?.everyMs === 'number' ? partial.everyMs : fallback.everyMs,+ minContextPct: typeof partial?.minContextPct === 'number' ? partial.minContextPct : fallback.minContextPct,+ minContextPctLargeWindow: typeof partial?.minContextPctLargeWindow === 'number'+ ? partial.minContextPctLargeWindow+ : fallback.minContextPctLargeWindow,+ message: typeof partial?.message === 'string' ? partial.message : fallback.message+ };+}++/** Read the context trigger, deep-filled. A half-written sub-object must never+ * reach the number inputs as `undefined` — React would flip them uncontrolled. */+export async function getContextTrigger(): Promise<ContextTriggerConfig> {+ try {+ const cfg: Partial<ContextTriggerConfig> | null = await window.cth.getContextTrigger();+ return {+ compact: fillRule(cfg?.compact, DEFAULT_CONTEXT_TRIGGER.compact),+ clear: fillRule(cfg?.clear, DEFAULT_CONTEXT_TRIGGER.clear)+ };+ } catch {+ return DEFAULT_CONTEXT_TRIGGER;+ }+}++/** Fire and forget — the controls have already moved, which is the house+ * pattern for config writes across the Command Center. */+export function setContextTrigger(cfg: ContextTriggerConfig): void {+ void window.cth.setContextTrigger(cfg).catch(() => { /* optimistic */ });+}++/* ─────────────────────────────── webhooks ────────────────────────────────── */++/** `null` on failure, never `[]` — a caller would adopt an empty list and wipe+ * a perfectly good store mirror over one dropped IPC. */+export async function listWebhooks(): Promise<WebhookTrigger[] | null> {+ try {+ return (await window.cth.listWebhooks()) ?? null;+ } catch {+ return null;+ }+}++/**+ * Persist and hand back main's canonical list — it sanitises what the renderer+ * sends (trims names, refuses an id that is not URL-safe, forces `enabled: false`+ * on a secretless endpoint), so the saved truth can differ from what was sent.+ */+export async function saveWebhooks(list: WebhookTrigger[]): Promise<WebhookTrigger[] | null> {+ try {+ return (await window.cth.saveWebhooks(list)) ?? null;+ } catch {+ return null;+ }+}++export async function deleteWebhook(id: string): Promise<WebhookTrigger[] | null> {+ try {+ return (await window.cth.deleteWebhook(id)) ?? null;+ } catch {+ return null;+ }+}++export async function webhooksStatus(): Promise<WebhooksStatus> {+ try {+ return await window.cth.webhooksStatus();+ } catch {+ return { running: false, endpoints: [] };+ }+}++/** 256 bits of hex, the shape main mints. Only reached if the mint call fails —+ * a locally minted secret still persists through `saveWebhooks`, so "add+ * webhook" never silently hands out a blank credential. */+function localSecret(): string {+ const bytes = new Uint8Array(32);+ crypto.getRandomValues(bytes);+ return [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('');+}++export async function generateWebhookSecret(): Promise<string> {+ try {+ const secret = await window.cth.generateWebhookSecret();+ if (secret) return secret;+ } catch { /* fall through to a local mint */ }+ return localSecret();+}++/**+ * A fresh endpoint. Two deliberate choices, both matched to Settings → Connections+ * so an endpoint made in either surface is the same thing:+ *+ * - the id shape is `wh-<base36 time>-<rand>`. It becomes a public URL path+ * segment, so it is stable for the endpoint's whole life (never renumbered on+ * save) and stays inside main's URL-safe charset.+ * - it arrives DISABLED. The operator copies the URL and the secret, then opts+ * in — an endpoint that went live the instant it was created would be open+ * before anyone had been told the address.+ */+export function newWebhook(secret: string, index: number): WebhookTrigger {+ return {+ id: `wh-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,+ name: index === 0 ? 'inbound' : `inbound ${index + 1}`,+ secret,+ enabled: false,+ mode: DEFAULT_TRIGGER_MODE,+ schema: DEFAULT_WEBHOOK_SCHEMA,+ createdAt: Date.now()+ };+}++/* ───────────────────────────── organisation ──────────────────────────────── */++/** `null` on failure; the store mirror stands. */+export async function getOrgTrigger(): Promise<OrgTriggerConfig | null> {+ try {+ return (await window.cth.getOrgTrigger()) ?? null;+ } catch {+ return null;+ }+}++export function setOrgTrigger(cfg: OrgTriggerConfig): void {+ void window.cth.setOrgTrigger(cfg).catch(() => { /* optimistic */ });+}diff --git a/src/renderer/src/components/triggers/ui.tsx b/src/renderer/src/components/triggers/ui.tsxnew file mode 100644index 00000000..2b0a70dc--- /dev/null+++ b/src/renderer/src/components/triggers/ui.tsx@@ -0,0 +1,389 @@+import { useState, type CSSProperties, type ReactNode } from 'react';+import { TRIGGER_MODES, type TriggerMode } from '@shared/triggers';++/**+ * Shared chrome for the Triggers tab.+ *+ * The Command Center's own `Section`/`Scroll`/`Muted` are module-private to+ * `CommandCenterPanel.tsx`, so these mirror them exactly (same paddings, same+ * fonts, same `inset` hairlines) and add the collapse behaviour this tab needs —+ * four types of dense config do not fit down a sidebar as flat forms.+ */++/* ───────────────────────────── shared styles ─────────────────────────────── */++export const inputStyle: CSSProperties = {+ width: '100%', boxSizing: 'border-box', padding: '6px 8px',+ background: 'var(--cth-paper-100)', border: 'none',+ boxShadow: 'inset 0 0 0 1px var(--cth-ink-100)',+ fontFamily: 'var(--cth-font-ui)', fontSize: 12, lineHeight: '17px',+ color: 'var(--cth-ink-900)', outline: 'none'+};++export const monoInputStyle: CSSProperties = {+ ...inputStyle,+ fontFamily: 'var(--cth-font-mono)'+};++export const textareaStyle: CSSProperties = {+ ...monoInputStyle,+ resize: 'vertical'+};++export const selectStyle: CSSProperties = {+ padding: '3px 6px', background: 'var(--cth-paper-100)', border: 'none',+ boxShadow: 'inset 0 0 0 1px var(--cth-ink-100)',+ fontFamily: 'var(--cth-font-ui)', fontSize: 12, color: 'var(--cth-ink-900)',+ cursor: 'pointer', minWidth: 0, maxWidth: '100%'+};++/* ───────────────────────────── text helpers ──────────────────────────────── */++export function Muted({ children }: { children: ReactNode }) {+ return <div style={{ fontSize: 12, lineHeight: '16px', color: 'var(--cth-ink-500)' }}>{children}</div>;+}++/** One line of explanation under a control. Smaller than Muted, never a tooltip —+ * a sidebar hides tooltips behind the window edge half the time. */+export function Hint({ children }: { children: ReactNode }) {+ return <div style={{ fontSize: 11, lineHeight: '15px', color: 'var(--cth-ink-500)', marginTop: 3 }}>{children}</div>;+}++export function Chip({ children, tone = 'plain' }: { children: ReactNode; tone?: 'plain' | 'on' | 'off' }) {+ const bg = tone === 'on' ? 'var(--cth-lemon)' : tone === 'off' ? 'var(--cth-cream-200)' : 'var(--cth-cream-100)';+ const line = tone === 'on' ? 'var(--cth-ink-900)' : 'var(--cth-ink-100)';+ return (+ <span style={{+ flexShrink: 0, padding: '2px 5px 1px',+ fontFamily: 'var(--cth-font-display)', fontSize: 8, lineHeight: '12px',+ background: bg, boxShadow: `inset 0 0 0 1px ${line}`, color: 'var(--cth-ink-900)'+ }}>{children}</span>+ );+}++export function Callout({ children, tone = 'warn' }: { children: ReactNode; tone?: 'warn' | 'note' }) {+ const warn = tone === 'warn';+ return (+ <div style={{+ marginTop: 6, padding: '6px 8px',+ fontSize: 11, lineHeight: '15px', color: 'var(--cth-ink-900)',+ background: warn ? 'var(--cth-coral-light)' : 'var(--cth-cream-200)',+ boxShadow: `inset 0 0 0 1px ${warn ? 'var(--cth-coral)' : 'var(--cth-ink-100)'}`+ }}>{children}</div>+ );+}++/* ─────────────────────────────── controls ────────────────────────────────── */++export function Toggle({ on, onClick, onLabel = 'on', offLabel = 'off' }: {+ on: boolean; onClick: () => void; onLabel?: string; offLabel?: string;+}) {+ return (+ <button+ onClick={onClick}+ style={{+ padding: '2px 8px 1px', border: 'none', cursor: 'pointer', flexShrink: 0,+ background: on ? 'var(--cth-lemon)' : 'var(--cth-cream-200)',+ boxShadow: `inset 0 0 0 1px ${on ? 'var(--cth-ink-900)' : 'var(--cth-ink-700)'}`,+ fontFamily: 'var(--cth-font-ui)', fontSize: 12, color: 'var(--cth-ink-900)'+ }}+ >{on ? onLabel : offLabel}</button>+ );+}++export function MiniButton({ children, onClick, tone = 'plain', disabled }: {+ children: ReactNode; onClick: () => void; tone?: 'plain' | 'danger' | 'good'; disabled?: boolean;+}) {+ return (+ <button+ onClick={onClick}+ disabled={disabled}+ style={{+ flexShrink: 0, padding: '2px 7px 1px', border: 'none',+ cursor: disabled ? 'default' : 'pointer',+ background: tone === 'good' ? 'var(--cth-mint)' : 'var(--cth-cream-200)',+ boxShadow: 'inset 0 0 0 1px var(--cth-ink-100)',+ fontFamily: 'var(--cth-font-ui)', fontSize: 11,+ color: disabled ? 'var(--cth-ink-300)' : tone === 'danger' ? 'var(--cth-coral)' : 'var(--cth-ink-900)'+ }}+ >{children}</button>+ );+}++export function Select({ value, onChange, children, style }: {+ value: string; onChange: (v: string) => void; children: ReactNode; style?: CSSProperties;+}) {+ return (+ <select+ value={value}+ onChange={(e) => onChange(e.target.value)}+ style={{ ...selectStyle, ...style }}+ >{children}</select>+ );+}++/** Label above a control. Stacked, never side-by-side — the sidebar is too+ * narrow for a label column that does not truncate the thing it labels. */+export function Field({ label, children }: { label: string; children: ReactNode }) {+ return (+ <div style={{ marginTop: 8 }}>+ <div style={{+ fontFamily: 'var(--cth-font-display)', fontSize: 8, lineHeight: '12px',+ color: 'var(--cth-ink-500)', marginBottom: 4+ }}>{label}</div>+ {children}+ </div>+ );+}++/* ───────────────────────────── containers ───────────────────────────────── */++export function Scroll({ children }: { children: ReactNode }) {+ return (+ <div style={{+ flex: 1, minWidth: 0, minHeight: 0, overflowY: 'auto', overflowX: 'hidden',+ padding: 10, background: 'var(--cth-paper-200)'+ }}>{children}</div>+ );+}++/**+ * One of the four trigger types. Collapsed it is a title, a one-line "what this+ * is", and a live summary — so opening the tab reads as four kinds of trigger+ * rather than a wall of forms.+ *+ * Children stay MOUNTED while collapsed (hidden, not unmounted) for two reasons:+ * the summary chip is fed by the section itself and would go blank the moment+ * you closed it, and a section's own open rows survive collapsing its parent.+ */+export function TriggerCard({ title, blurb, summary, defaultOpen = false, children }: {+ title: string; blurb: string; summary?: ReactNode; defaultOpen?: boolean; children: ReactNode;+}) {+ const [open, setOpen] = useState(defaultOpen);+ return (+ <div style={{ marginBottom: 8, background: 'var(--cth-paper-100)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-100)' }}>+ <button+ onClick={() => setOpen((o) => !o)}+ style={{+ width: '100%', display: 'flex', alignItems: 'flex-start', gap: 6, textAlign: 'left',+ padding: '8px 10px', border: 'none', cursor: 'pointer',+ background: 'var(--cth-cream-200)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-100)'+ }}+ >+ <span style={{ flexShrink: 0, width: 8, fontSize: 11, lineHeight: '13px', color: 'var(--cth-ink-500)' }}>+ {open ? '▾' : '▸'}+ </span>+ <span style={{ flex: 1, minWidth: 0 }}>+ <span style={{+ display: 'block', fontFamily: 'var(--cth-font-display)', fontSize: 9, lineHeight: '13px',+ color: 'var(--cth-ink-900)'+ }}>{title}</span>+ <span style={{ display: 'block', fontFamily: 'var(--cth-font-ui)', fontSize: 12, lineHeight: '16px', color: 'var(--cth-ink-500)', marginTop: 2 }}>+ {blurb}+ </span>+ </span>+ {summary !== undefined && <Chip>{summary}</Chip>}+ </button>+ <div style={{ display: open ? 'block' : 'none', padding: '8px 10px 10px' }}>{children}</div>+ </div>+ );+}++/** A card inside a card — one webhook, one context rule. */+export function SubCard({ children }: { children: ReactNode }) {+ return (+ <div style={{+ marginBottom: 6, padding: '8px 10px 10px',+ background: 'var(--cth-cream-100)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-100)'+ }}>{children}</div>+ );+}++/** Header row inside a SubCard: a disclosure caret, a title, and controls. */+export function SubHeader({ open, onToggle, title, sub, right }: {+ open: boolean; onToggle: () => void; title: ReactNode; sub?: ReactNode; right?: ReactNode;+}) {+ return (+ <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>+ <button+ onClick={onToggle}+ style={{+ flex: 1, minWidth: 0, display: 'flex', alignItems: 'center', gap: 6, textAlign: 'left',+ padding: 0, border: 'none', background: 'transparent', cursor: 'pointer'+ }}+ >+ <span style={{ flexShrink: 0, width: 8, fontSize: 11, color: 'var(--cth-ink-500)' }}>{open ? '▾' : '▸'}</span>+ <span style={{ flex: 1, minWidth: 0 }}>+ <span style={{+ display: 'block', fontFamily: 'var(--cth-font-ui)', fontSize: 12, lineHeight: '16px',+ color: 'var(--cth-ink-900)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap'+ }}>{title}</span>+ {sub !== undefined && (+ <span style={{+ display: 'block', fontSize: 11, lineHeight: '15px', color: 'var(--cth-ink-500)',+ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap'+ }}>{sub}</span>+ )}+ </span>+ </button>+ {right}+ </div>+ );+}++/* ──────────────────────────── trigger mode ───────────────────────────────── */++/** The shared `strict / allow-all / communication-only` gate. Labels and blurbs+ * come from `TRIGGER_MODES` so webhooks and org can never drift apart. */+export function ModePicker({ value, onChange }: { value: TriggerMode; onChange: (m: TriggerMode) => void }) {+ const current = TRIGGER_MODES.find((m) => m.value === value) ?? TRIGGER_MODES[0];+ return (+ <>+ <Select value={value} onChange={(v) => onChange(v as TriggerMode)} style={{ width: '100%' }}>+ {TRIGGER_MODES.map((m) => <option key={m.value} value={m.value}>{m.label}</option>)}+ </Select>+ <Hint>{current.blurb}</Hint>+ </>+ );+}++/* ──────────────────────────── interval picker ────────────────────────────── */++const MINUTE = 60_000;+const HOUR = 3_600_000;+const DAY = 86_400_000;+const WEEK = 604_800_000;++export const INTERVAL_OPTS: { ms: number; label: string }[] = [+ { ms: 15 * MINUTE, label: '15m' },+ { ms: 30 * MINUTE, label: '30m' },+ { ms: HOUR, label: '1h' },+ { ms: 2 * HOUR, label: '2h' },+ { ms: 6 * HOUR, label: '6h' },+ { ms: 12 * HOUR, label: '12h' },+ { ms: DAY, label: '24h' },+ { ms: WEEK, label: 'weekly' }+];++/** A truthful label for ANY stored interval, preset or not. Arbitrary intervals+ * persist now, so the label is computed rather than looked up — a select that+ * falls back to the nearest preset would quietly lie about the stored value. */+export function fmtInterval(ms: number): string {+ if (!Number.isFinite(ms) || ms <= 0) return 'off';+ if (ms === WEEK) return 'weekly';+ if (ms % WEEK === 0) return `${ms / WEEK}w`;+ if (ms % DAY === 0) return `${ms / DAY}d`;+ if (ms % HOUR === 0) return `${ms / HOUR}h`;+ if (ms % MINUTE === 0) return `${ms / MINUTE}m`;+ return `${Math.round(ms / 1000)}s`;+}++const CUSTOM = '__custom';++/**+ * @param minMs/maxMs the range MAIN will actually store. Context rules are+ * clamped to 1 minute … 24 hours on the way in, so offering "weekly" there would+ * put a label on screen that the saved value does not match. Schedules take any+ * interval and pass the default range.+ */+export function IntervalPicker({ value, onChange, minMs = MINUTE, maxMs = Number.POSITIVE_INFINITY }: {+ value: number; onChange: (ms: number) => void; minMs?: number; maxMs?: number;+}) {+ const opts = INTERVAL_OPTS.filter((o) => o.ms >= minMs && o.ms <= maxMs);+ const preset = opts.some((o) => o.ms === value);+ const [custom, setCustom] = useState(!preset);+ const showCustom = custom || !preset;+ const clamp = (ms: number) => Math.min(maxMs, Math.max(minMs, ms));+ return (+ <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>+ <Select+ value={showCustom ? CUSTOM : String(value)}+ onChange={(v) => {+ if (v === CUSTOM) { setCustom(true); return; }+ setCustom(false);+ onChange(Number(v));+ }}+ >+ {!preset && <option value={CUSTOM}>{fmtInterval(value)} (custom)</option>}+ {opts.map((o) => <option key={o.ms} value={String(o.ms)}>{o.label}</option>)}+ {preset && <option value={CUSTOM}>custom…</option>}+ </Select>+ {showCustom && (+ <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>+ <input+ type="number"+ min={Math.max(1, Math.round(minMs / MINUTE))}+ max={Number.isFinite(maxMs) ? Math.round(maxMs / MINUTE) : undefined}+ value={Math.max(1, Math.round(value / MINUTE))}+ onChange={(e) => {+ const mins = Number(e.target.value);+ if (Number.isFinite(mins) && mins > 0) onChange(clamp(Math.round(mins) * MINUTE));+ }}+ style={{ ...monoInputStyle, width: 68, padding: '3px 5px' }}+ />+ <span style={{ fontSize: 11, color: 'var(--cth-ink-500)' }}>min</span>+ </span>+ )}+ </div>+ );+}++/* ───────────────────────────── percent field ─────────────────────────────── */++export function PctField({ value, onChange }: { value: number; onChange: (pct: number) => void }) {+ const pct = Math.max(0, Math.min(100, Math.round(value)));+ return (+ <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>+ <input+ type="number"+ min={0}+ max={100}+ value={pct}+ onChange={(e) => {+ const n = Number(e.target.value);+ onChange(Number.isFinite(n) ? Math.max(0, Math.min(100, Math.round(n))) : 0);+ }}+ style={{ ...monoInputStyle, width: 60, padding: '3px 5px' }}+ />+ <span style={{ fontSize: 11, color: 'var(--cth-ink-500)' }}>%</span>+ <div style={{+ flex: 1, minWidth: 40, height: 8,+ background: 'var(--cth-cream-200)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-100)'+ }}>+ <div style={{ width: `${pct}%`, height: '100%', background: pct === 0 ? 'var(--cth-ink-300)' : 'var(--cth-lemon)' }} />+ </div>+ </div>+ );+}++/* ────────────────────────────── secret field ─────────────────────────────── */++/** Masked by default; reveals only on demand. The value never lands in a+ * `title`/tooltip — those leak into screenshots and accessibility trees. */+export function SecretField({ value, revealed, onReveal, onCopy, copied, placeholder, onChange, onBlur }: {+ value: string;+ revealed: boolean;+ onReveal: () => void;+ onCopy?: () => void;+ copied?: boolean;+ placeholder?: string;+ onChange?: (v: string) => void;+ onBlur?: () => void;+}) {+ const readOnly = !onChange;+ return (+ <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>+ <input+ type={revealed ? 'text' : 'password'}+ value={value}+ readOnly={readOnly}+ placeholder={placeholder}+ onChange={(e) => onChange?.(e.target.value)}+ onBlur={onBlur}+ style={{ ...monoInputStyle, flex: 1, minWidth: 0, padding: '4px 6px' }}+ />+ <MiniButton onClick={onReveal}>{revealed ? 'hide' : 'show'}</MiniButton>+ {onCopy && <MiniButton onClick={onCopy} tone={copied ? 'good' : 'plain'}>{copied ? 'copied' : 'copy'}</MiniButton>}+ </div>+ );+}diff --git a/src/renderer/src/hooks/useHive.ts b/src/renderer/src/hooks/useHive.tsindex 40bb9b00..c7b10fd3 100644--- a/src/renderer/src/hooks/useHive.ts+++ b/src/renderer/src/hooks/useHive.ts@@ -9,10 +9,12 @@ import {type HarnessConfig} from '@/store/config';import {+ clearCommandForProvider,compactionCommandForProvider,remoteControlCommandForProvider,terminalReadyToReceive} from '../../../shared/providerAutomation';+import { DEFAULT_CONTEXT_TRIGGER, type ContextRule } from '../../../shared/triggers';import type { AgentProvider } from '../../../shared/agentProvider';import { acquireTerminal, resetTerminal, isTerminalAutomationSafe } from '@/components/terminalPool';import { deliverWithAcknowledgement } from './queueDelivery';@@ -199,6 +201,50 @@ function stationForTool(tool: string): { station: StationKind; carry?: ToolKindreturn { station: 'desk' };}+/** At/above this window size an agent counts as "large context" and is judged+ * against `minContextPctLargeWindow` instead. Sits between the two real-world+ * window sizes the app ever sees (200k and 1M) so neither lands ambiguously. */+const LARGE_CONTEXT_WINDOW = 500_000;++/**+ * How full this agent's context window is, 0-100, or null when we have no+ * reading at all.+ *+ * Two sources feed the store and only one is exact: the status-line shim pushes+ * real `contextTokens` + `contextLimit` (effect 2d), while the transcript poll+ * (2c) backfills tokens ONLY. So an agent can legitimately know its token count+ * without knowing its window — infer the window the same way 2c does rather+ * than throwing the token reading away.+ */+function contextFillPct(a: Agent): number | null {+ if (a.contextTokens === undefined || !Number.isFinite(a.contextTokens)) return null;+ const limit = a.contextLimit && a.contextLimit > 0+ ? a.contextLimit+ : (/1m/i.test(a.model ?? '') ? 1_000_000 : 200_000);+ return (a.contextTokens / limit) * 100;+}++/**+ * The context-pressure gate: is this agent full enough to be worth interrupting?+ *+ * `minContextPct` of 0 disables the gate (the rule's cadence alone fires it).+ *+ * FAIL-OPEN when we have no reading. That is the deliberate choice: context+ * telemetry arrives over the Claude status-line/hook path, so most non-Claude+ * providers report nothing at all. Failing closed there would silently reinstate+ * the very bug this replaces — a fleet that never compacts — only harder to+ * notice. An unmetered agent therefore falls back to time-only firing, which is+ * exactly the old behaviour and no worse.+ */+function passesContextPressure(a: Agent, rule: ContextRule): boolean {+ const large = (a.contextLimit ?? 0) >= LARGE_CONTEXT_WINDOW;+ const bar = large ? rule.minContextPctLargeWindow : rule.minContextPct;+ if (!(bar > 0)) return true;+ const pct = contextFillPct(a);+ if (pct === null) return true;+ return pct >= bar;+}+/*** The renderer-side glue for the hive:* 1. spawns the god agent into Michael's room when none is running,@@ -876,24 +922,65 @@ export function useHive(config: HarnessConfig | null): void {});}, [config?.onboardingComplete]);- // 6) Auto-compact (scheduled standup). Main fires this per tick; we queue a- // /compact for each live agent so the drain (#4) delivers it only when the- // agent is idle — never jamming a working terminal. Deduped: if a /compact- // is already queued for an agent, skip it (no second one piles up).+ // 6) CONTEXT TRIGGERS (compact / clear). Main decides WHEN — cadence, and which+ // half of the rule fired — and pushes `{action, rule}`; this decides WHO, then+ // queues the provider's own command so the drain (#4) delivers it only at an+ // idle prompt, never jamming a working terminal.+ //+ // THE PRESSURE GATE. main/config.ts has long DOCUMENTED that auto-compact+ // "only compacts agents whose context has filled past a threshold (30% for+ // ~250k windows, 20% for ~1M windows)". No such check was ever implemented:+ // every live agent with a resolvable command got compacted on every tick,+ // hourly, however empty its window was. This makes the documented behaviour+ // real — `rule.minContextPct`, or `minContextPctLargeWindow` once the window+ // is >= LARGE_CONTEXT_WINDOW, must be met before an agent is interrupted.+ // (The shipped bars are now 60/40, twice the stale doc's numbers; see+ // DEFAULT_CONTEXT_TRIGGER. The doc comment in config.ts is still stale.)+ //+ // Dedupe generalises to both actions: keyed on the command's own verb, so a+ // queued `/compact` blocks a second compact without blocking a `/clear`.useEffect(() => {if (!config?.onboardingComplete) return;- return window.cth.onAutoCompact(() => {++ const fire = (action: 'compact' | 'clear', rule: ContextRule): void => {const { agents, messageQueues, enqueueMessage } = useStore.getState();for (const a of agents) {if (!a.ptyId) continue;const provider = inferAgentProvider(a.command, a.provider);- const compactCommand = compactionCommandForProvider(provider);- if (!compactCommand) continue;+ const command = action === 'clear'+ ? clearCommandForProvider(provider, rule.message)+ : compactionCommandForProvider(provider, rule.message);+ // No trustworthy command for this CLI (Crush's palette-only TUI, Copilot's+ // print mode, an unknown custom binary) — leave its terminal alone.+ if (!command) continue;+ if (!passesContextPressure(a, rule)) continue;+ const verb = command.trimStart().split(/\s+/)[0];const queued = messageQueues[a.id] ?? [];- if (queued.some((m) => m.text.trimStart().startsWith('/compact'))) continue;- enqueueMessage(a.id, compactCommand);+ if (queued.some((m) => m.text.trimStart().startsWith(verb))) continue;+ enqueueMessage(a.id, command);}+ };++ // The typed `onContextTrigger` arrives with the main-process/preload change+ // that emits it; access it defensively so this lands independently of that.+ const off = (window.cth as unknown as {+ onContextTrigger?: (+ cb: (p: { action: 'compact' | 'clear'; rule: ContextRule }) => void+ ) => () => void;+ }).onContextTrigger?.((p) => {+ if (!p?.rule) return;+ fire(p.action === 'clear' ? 'clear' : 'compact', p.rule);});++ // LEGACY fallback: main still emits the old parameterless auto-compact until+ // it switches over. Treat it as the default compact rule so behaviour is+ // continuous across that landing. Harmless if both fire — the dedupe above+ // drops the duplicate.+ const offLegacy = window.cth.onAutoCompact(+ () => fire('compact', DEFAULT_CONTEXT_TRIGGER.compact)+ );++ return () => { off?.(); offLegacy?.(); };}, [config?.onboardingComplete]);// 7) Auto-revive wedged PTYs after the Mac sleeps/locks. Kevin's main-processdiff --git a/src/renderer/src/realtime/session.ts b/src/renderer/src/realtime/session.tsindex dd16e5a6..f224e864 100644--- a/src/renderer/src/realtime/session.ts+++ b/src/renderer/src/realtime/session.ts@@ -13,7 +13,7 @@* model truncates when the user talks over it).** Phase 1 is a read-only connect→listen→respond round-trip. The agent runs Kevin's- * rt-4 READ-ONLY tools (get_fleet_status / get_tasks / get_cost / get_schedules /+ * rt-4 READ-ONLY tools (get_fleet_status / get_tasks / get_cost / get_triggers /* get_config / get_memory / get_activity) and god's rt-6 "Michael" persona, so the* agent_tool_start/agent_tool_end lifecycle fires and the mic goes idle during a tool* call and resumes — a Phase-1 acceptance criterion. NO hive action-tools yet (rt-5, held).@@ -89,7 +89,7 @@ WHAT YOU CAN LOOK UP. You have live awareness of the WHOLE hive: a floor snapsho- get_memory — read the team's memory. You can ALWAYS answer with this: search across everyone, read ONE agent's notes (active OR archived), or search within a single agent. It never dead-ends.- get_tasks — the kanban board: counts plus the in-progress and blocked cards with their owners.- get_board — the orchestrator's plan narrative, in prose.-- get_schedules — the recurring scheduled missions.+- get_triggers — what fires the hive without a human: today the recurring scheduled missions. Webhooks and inbound organization messages are the other trigger types, but they are configured elsewhere and this tool does not list them.- get_config — non-sensitive settings (autonomy, default model, caps, breaker, which features are on). Never secrets.- get_cost — token usage across the hive.- get_activity — the recent hive activity log: WHAT happened (spawns, archives, messages), as events.diff --git a/src/renderer/src/realtime/tools.ts b/src/renderer/src/realtime/tools.tsindex bea512ab..9fb31071 100644--- a/src/renderer/src/realtime/tools.ts+++ b/src/renderer/src/realtime/tools.ts@@ -232,11 +232,11 @@ export function realtimeReadTools(): ReturnType<typeof tool>[] {}, 'token usage')}),- // ── get_schedules ─────────────────────────────────────────────────────+ // ── get_triggers ──────────────────────────────────────────────────────tool({- name: 'get_schedules',+ name: 'get_triggers',description:- 'The recurring scheduled missions the hive fires on a timer: their labels, cadence, recipient, and when each last fired. Call this when the user asks about schedules, recurring jobs, heartbeats, or automations.',+ 'The triggers that fire the hive without a human typing. Today this reports the schedules: the recurring missions the hive runs on a timer, with their labels, cadence, recipient, and when each last fired. The other trigger types — webhooks and inbound organization messages — are configured elsewhere and are not listed here. Call this when the user asks about triggers, schedules, recurring jobs, heartbeats, or automations.',parameters: { type: 'object', properties: {}, required: [], additionalProperties: false },execute: () =>spoken(async () => {diff --git a/src/renderer/src/scene/office/OfficeFloor.tsx b/src/renderer/src/scene/office/OfficeFloor.tsxindex 7bd5ce68..d65d541e 100644--- a/src/renderer/src/scene/office/OfficeFloor.tsx+++ b/src/renderer/src/scene/office/OfficeFloor.tsx@@ -248,10 +248,10 @@ export function OfficeFloor() {camera.setViewSize(app.screen.width, app.screen.height);camera.fitToScreen();- // ─── The boss's wall calendar → SCHEDULES ──────────────────────────────+ // ─── The boss's wall calendar → TRIGGERS ───────────────────────────────// A little tear-off month page hangs on the CEO office wall. Clicking it- // selects Michael (the god) and opens the Command Center's SCHEDULES tab —- // recurring missions are what's written on the boss's calendar.+ // selects Michael (the god) and opens the Command Center's TRIGGERS tab —+ // everything that wakes the hive without you, schedules first among them.const calTs = mapRenderer.tileSize;const calG = new Graphics();calG.eventMode = 'static';@@ -263,7 +263,7 @@ export function OfficeFloor() {const st = useStore.getState();const god = st.agents.find((a) => a.isGod);if (god) st.select(god.id);- st.requestCommandCenterTab('schedules');+ st.requestCommandCenterTab('triggers');});// nail + ring binding above a white page with a red month headercalG.rect(7, -2, 2, 2).fill(0x4a3b52); // naildiff --git a/src/renderer/src/scene/office/themeRegistry.ts b/src/renderer/src/scene/office/themeRegistry.tsindex a53776fe..86f72247 100644--- a/src/renderer/src/scene/office/themeRegistry.ts+++ b/src/renderer/src/scene/office/themeRegistry.ts@@ -94,7 +94,7 @@ export interface CoffeeConfig {maxCups: number;}-/** Clickable prop anchors (tile coords). calendar → SCHEDULES, boards → TASKS,+/** Clickable prop anchors (tile coords). calendar → TRIGGERS, boards → TASKS,* clock → CLOSING TIME. */export interface AnchorConfig {calendar: Tile;@@ -250,7 +250,7 @@ export const BROOKLYN99_THEME: ThemeConfig = {maxCups: 4,},anchors: {- calendar: { x: 4, y: 1 }, // briefing-room top wall → SCHEDULES+ calendar: { x: 4, y: 1 }, // briefing-room top wall → TRIGGERSboards: { x: 14, y: 1 }, // over the bullpen → TASKSclock: { x: 1, y: 1 }, // top-left corner → CLOSING TIME},diff --git a/src/renderer/src/store/config.ts b/src/renderer/src/store/config.tsindex 5f355270..fbc5f138 100644--- a/src/renderer/src/store/config.ts+++ b/src/renderer/src/store/config.ts@@ -7,6 +7,11 @@ import {isClaudeProvider,type AgentProvider} from '@shared/agentProvider';+import type {+ ContextTriggerConfig,+ OrgTriggerConfig,+ WebhookTrigger+} from '@shared/triggers';export {AGENT_PROVIDER_PRESETS,@@ -116,6 +121,26 @@ export interface HarnessConfig {providerBaseUrls?: Partial<Record<AgentProvider, string>>;/** Per-CLI-provider default model slug, used to pre-fill the model picker. */providerDefaultModels?: Partial<Record<AgentProvider, string>>;+ /** Legacy single-webhook fields (mirrors src/main/config.ts, where they are+ * deprecated in favour of `webhookTriggers` but still read until the server is+ * rewired). Declared here so the surfaces that show them can stop widening this+ * type locally.+ * @deprecated Use `webhookTriggers`. */+ webhookEnabled?: boolean;+ /** @deprecated Use `webhookTriggers[].secret`. */+ webhookSecret?: string;+ /** @deprecated The port belongs to the shared server, not to any one trigger. */+ webhookPort?: number;+ /** Auto-compaction / auto-clearing of agent terminal context. Main deep-fills+ * both halves on read, so the renderer can treat the sub-keys as present+ * (mirrors src/main/config.ts). */+ contextTrigger?: ContextTriggerConfig;+ /** Inbound HTTP endpoints, one per caller — replaces the legacy trio above. */+ webhookTriggers?: WebhookTrigger[];+ /** Peer messaging between teammates' clone nodes (persistence + UI only). */+ orgTrigger?: OrgTriggerConfig;+ /** One-time guard for the main-process triggers migration; read-only here. */+ triggersMigratedV1?: boolean;}/** The Sonnet model with the 1M-token context window — used for Michael's prepdiff --git a/src/renderer/src/store/store.ts b/src/renderer/src/store/store.tsindex 88002744..9933819e 100644--- a/src/renderer/src/store/store.ts+++ b/src/renderer/src/store/store.ts@@ -5,6 +5,7 @@ import type { ThemeId } from '@/scene/office/themeRegistry';import type { StatusKind } from '@/components/PixelBadge';import type { AgentProvider } from '@shared/agentProvider';import type { HireManifest } from '@shared/hire';+import { DEFAULT_ORG_TRIGGER, type OrgTriggerConfig, type WebhookTrigger } from '@shared/triggers';export type ToolKind =| 'Read' | 'Edit' | 'Write' | 'Bash' | 'WebFetch' | 'WebSearch'@@ -225,6 +226,23 @@ interface State {* on switch). OfficeFloor depends on this and rebuilds the scene on change. */officeTheme: ThemeId;setOfficeTheme: (theme: ThemeId) => void;+ /** Mirror of config.webhookTriggers — the inbound HTTP endpoints. Webhooks are+ * editable from BOTH Settings → Connections and the Triggers tab, so neither+ * surface keeps its own copy: both render off this list and both call the+ * setter after persisting, and the other one repaints without a refetch.+ * Seeded by App from getConfig() (main deep-fills the field on every read).+ *+ * Holds per-endpoint secrets, because a secret is what the UI has to show for+ * reveal/copy to mean anything. Renderer memory only — never persisted to+ * localStorage or the roster file, never logged, masked in every surface. */+ webhookTriggers: WebhookTrigger[];+ setWebhookTriggers: (list: WebhookTrigger[]) => void;+ /** Mirror of config.orgTrigger (peer messaging between teammates' clone nodes).+ * Same two-way contract as `webhookTriggers`, and the same handling for+ * `apiKey` — in memory for the two surfaces that display it masked, nowhere+ * else. Configuration only for now: no transport reads the key yet. */+ orgTrigger: OrgTriggerConfig;+ setOrgTrigger: (cfg: OrgTriggerConfig) => void;/** Park a message for an agent. Returns nothing; the flush loop delivers it.* `meta.instruction`, when set, is what gets typed into the PTY instead of* `text` (UI/card surfaces still show `text`). */@@ -691,6 +709,13 @@ export const useStore = create<State>((set) => ({setHasOpenAiKey: (has) => set({ hasOpenAiKey: has }),officeTheme: 'office',setOfficeTheme: (theme) => set({ officeTheme: theme }),+ webhookTriggers: [],+ setWebhookTriggers: (list) => set({ webhookTriggers: list }),+ // A copy, not the shared DEFAULT_ORG_TRIGGER instance — main takes the same+ // care (withTriggerDefaults), and handing the module-level default out is how+ // one careless mutation rewrites the default for everyone.+ orgTrigger: { ...DEFAULT_ORG_TRIGGER },+ setOrgTrigger: (cfg) => set({ orgTrigger: cfg }),enqueueMessage: (agentId, text, meta) =>set((s) => {const trimmed = text.trim();@@ -779,3 +804,11 @@ export const useStore = create<State>((set) => ({export function selectedAgent(s: State): Agent | undefined {return s.agents.find(a => a.id === s.selectedId);}++/** Whether the Command Center's Trigger History tab has anything to be about+ * yet: an organisation key is set, or at least one webhook exists. Derived from+ * the two mirrors rather than stored beside them, so it cannot fall out of step+ * with the thing it describes. Use as `useStore(triggerHistoryVisible)`. */+export function triggerHistoryVisible(s: State): boolean {+ return s.webhookTriggers.length > 0 || s.orgTrigger.apiKey.trim() !== '';+}diff --git a/src/shared/codexCommands.ts b/src/shared/codexCommands.tsindex e48a2711..dea6c326 100644--- a/src/shared/codexCommands.ts+++ b/src/shared/codexCommands.ts@@ -16,6 +16,10 @@ export const CODEX_COMMAND_GROUPS: CmdGroup[] = [title: 'SESSION',items: [{ cmd: '/clear', kind: 'slash', desc: 'Start a fresh chat without quitting — clears the conversation context.' },+ // Verified present in the codex 0.137.0 binary's own command table. It was+ // missing here while providerAutomation sent it, so the two disagreed.+ // Unlike Claude's, this one ignores any trailing focus text.+ { cmd: '/compact', kind: 'slash', desc: 'Summarize the conversation so far to stay under the context limit.' },{ cmd: '/help', kind: 'slash', desc: 'List every available slash command.' },{ cmd: '/copy', kind: 'slash', desc: 'Copy the latest model output to the clipboard.' },{ cmd: '/logout', kind: 'slash', desc: 'Clear locally stored credentials.' },diff --git a/src/shared/providerAutomation.ts b/src/shared/providerAutomation.tsindex f147a6eb..20402df6 100644--- a/src/shared/providerAutomation.ts+++ b/src/shared/providerAutomation.ts@@ -1,36 +1,182 @@import type { AgentProvider } from './agentProvider';+import { DEFAULT_COMPACTION_FOCUS } from './triggers';-const COMPACTION_FOCUS =- 'Summarise exactly what you are currently working on and the next step, ' +- 'so you can resume from the same point — then continue that work after compacting.';+/**+ * Back-compat alias. The compaction focus used to be a private constant here;+ * it now lives in shared/triggers.ts as the DEFAULT VALUE of the user-editable+ * `ContextRule.message`, so the Triggers UI and this module cannot drift apart.+ * Kept exported under the old name for any consumer still reaching for it.+ */+export const COMPACTION_FOCUS = DEFAULT_COMPACTION_FOCUS;-/** Generate only commands that the target provider's interactive TUI supports. */-export function compactionCommandForProvider(provider: AgentProvider): string | null {- switch (provider) {- case 'claude':- return `/compact ${COMPACTION_FOCUS}`;- case 'codex':- // Codex treats trailing text differently across CLI releases. Its stable- // automation form is the bare slash command.- return '/compact';- case 'grok':- // Grok supports `/compact [context]`, including a focus instruction.- return `/compact ${COMPACTION_FOCUS}`;- case 'kimi':- // Kimi Code documents `/compact [<instruction>]`, so preserve the task- // focus in its supported optional instruction.- return `/compact ${COMPACTION_FOCUS}`;- default:- return null;- }+/** What one provider's interactive TUI accepts for each context action. */+export interface ProviderContextCommands {+ /** Summarise-in-place. `null` = no command we can type with confidence. */+ compact: string | null;+ /** Discard-and-restart. `null` = same. */+ clear: string | null;+ /**+ * Whether the TUI parses text AFTER the compact command as a focus+ * instruction. When false the focus is DROPPED rather than typed: a CLI whose+ * slash parser ignores the remainder is harmless, but one that re-reads it as+ * a fresh prompt would silently turn a compaction into a whole extra turn.+ */+ compactTakesFocus: boolean;+}++const NO_CONTEXT_COMMANDS: ProviderContextCommands = {+ compact: null,+ clear: null,+ compactTakesFocus: false+};++/**+ * THE per-provider context-command table.+ *+ * Deliberately a total `Record<AgentProvider, …>` and NOT a switch with a+ * `default:` arm — the previous switch silently answered `null` for seven of the+ * eleven providers, so auto-compaction quietly did nothing for most of the fleet+ * and nobody found out. A total record makes the compiler stop the next person+ * who adds a provider until they have actually looked its commands up.+ *+ * `null` means "we could not establish a command we trust", NOT "we didn't+ * check". A wrong slash command typed into a live terminal is worse than no+ * command: at best it is dead text the model answers, at worst it fires some+ * other verb. Every entry below cites where it was verified — mostly by reading+ * the SHIPPED BINARY of each CLI (its own embedded command table / docs), which+ * outranks web docs because it cannot lag the installed version.+ */+const CONTEXT_COMMANDS: Record<AgentProvider, ProviderContextCommands> = {+ // claudeCommands.ts:34,37 (this repo's own catalog): `/compact` takes a focus+ // ("usage: /compact keep the auth decisions"), `/clear` starts a fresh+ // conversation and reclaims the window.+ claude: { compact: '/compact', clear: '/clear', compactTakesFocus: true },++ // Codex 0.137.0 binary, TUI slash-command description table:+ // "summarize conversation to prevent hitting the context limit" → /compact+ // "clear the terminal and start a new chat" → /clear+ // NOTE this contradicts codexCommands.ts, which lists /clear but NOT /compact.+ // The binary is right and that catalog is incomplete (see report).+ // compactTakesFocus stays FALSE: codex's own `Usage: /…` strings spell out an+ // argument for every command that takes one (/goal, /raw, /mcp, /keymap,+ // /ide, /sandbox-add-read-dir) and /compact has none.+ codex: { compact: '/compact', clear: '/clear', compactTakesFocus: false },++ // Grok binary ships its own docs inline (04-slash-commands.md):+ // "/compact [context] — Compress conversation history… Optionally specify+ // what to preserve", example `/compact keep the auth implementation details`+ // "/new — Start a new session, clearing the current conversation.+ // Aliases: /clear"+ // `/new` is the documented spelling (and what grokCommands.ts:13 already+ // records), so prefer it over the alias.+ grok: { compact: '/compact', clear: '/new', compactTakesFocus: true },++ // Moonshot kimi-cli slash-command reference: `/compact` accepts appended+ // custom instructions ("/compact preserve database-related discussions");+ // `/clear` (alias /reset) "Clear the current session's context and start a+ // new conversation". NB `/new` there forks a session rather than discarding.+ kimi: { compact: '/compact', clear: '/clear', compactTakesFocus: true },++ // antigravity.google/docs/cli/reference (Google's own command table):+ // "/clear (/new) — Clear the terminal and reset active conversation+ // contexts." ← a REAL context reset, and+ // "Ctrl+L cli.clear_screen — Refreshes and clears the visual terminal+ // buffer." ← the screen-only one. The two are different things, so+ // the "agy /clear only clears the screen" worry does not hold.+ // That reference lists NO compaction verb at all (zero hits for compact /+ // compress / summarize), and the shipped `agy` binary has no such literal+ // either — agy compacts AUTOMATICALLY when the window fills ("# Resuming from+ // a compaction"). Nothing to type, so: null.+ antigravity: { compact: null, clear: '/clear', compactTakesFocus: false },++ // qwen-code's bundled cli.js, verbatim:+ // compressCommand = { name:"compress", altNames:["summarize"],+ // description "Compresses the context by replacing it with a summary." }+ // and its action reads `context.invocation?.args` as `customInstructions`+ // (capped at 2000 chars) → it genuinely takes a focus.+ // clearCommand = { name:"clear", altNames:["reset","new"],+ // description "Clear conversation history and free up context." }+ // It is `/compress`, NOT `/compact`: qwen dropped upstream gemini-cli's+ // `compact` altName, so `/compact` would land as plain text here.+ qwen: { compact: '/compress', clear: '/clear', compactTakesFocus: true },++ // opencode binary's command registry, verbatim:+ // { title:"Compact session", value:"session.compact",+ // slash:{ name:"compact", aliases:["summarize"] }, run: … }+ // and its own tip text "Run /compact to summarize long sessions near context+ // limits". That `run()` calls session.summarize({sessionID,model}) and never+ // looks at the invocation args → the focus would be silently dropped, so+ // compactTakesFocus is false.+ // `/clear` does NOT exist in the binary (zero literals); the fresh-session+ // verb is `/new` — matched exactly (`t.trim().toLowerCase()==="/new"`).+ opencode: { compact: '/compact', clear: '/new', compactTakesFocus: false },++ // Crush has NO typed slash commands at all. Its own binary strings show+ // "Summarize Session" / "New Session" as ctrl+p COMMAND-PALETTE rows, and the+ // hint "/ or ctrl+p" means a leading `/` OPENS that palette rather than+ // submitting a command. Typing "/compact" would filter a modal and leave it+ // open, swallowing everything queued behind it. Nothing safe to type: null.+ // (Crush's compact/clear are reachable only over its HTTP API.)+ crush: NO_CONTEXT_COMMANDS,++ // pi's dist/core/slash-commands.js, verbatim:+ // { name:"compact", description:"Manually compact the session context" }+ // { name:"new", description:"Start a new session" }+ // and docs/compaction.md: "trigger manually with `/compact [instructions]`,+ // where optional instructions focus the summary". There is no `/clear`.+ pi: { compact: '/compact', clear: '/new', compactTakesFocus: true },++ // Copilot's INTERACTIVE mode does have `/compact [FOCUS-INSTRUCTIONS]` and+ // `/clear` — but this app never runs it interactively. The preset spawns it in+ // print mode (`initialPromptFlag: '-p'`, `canReceiveInbox: false`), which runs+ // one prompt and EXITS. There is no prompt left alive to type a slash command+ // into, so both are null by construction rather than by ignorance.+ copilot: NO_CONTEXT_COMMANDS,++ // An arbitrary user binary. We cannot know its command surface, and guessing+ // means typing slashes into someone's unknown REPL.+ custom: NO_CONTEXT_COMMANDS+};++/** The full context-command entry for a provider (unknown ids degrade to none). */+export function contextCommandsForProvider(provider: AgentProvider): ProviderContextCommands {+ return CONTEXT_COMMANDS[provider] ?? NO_CONTEXT_COMMANDS;}-/** Safe fallback when a provider has no native context-compaction command. */-export function compactionPromptFallback(): string {- return (- 'Summarise the current task, decisions, and exact next step in your persistent ' +- 'memory, then continue from that checkpoint.'- );+/**+ * The compaction command to type, or null when this provider has none.+ *+ * `message` is the user-editable `ContextRule.message` (default+ * `DEFAULT_COMPACTION_FOCUS`) and is appended only where the provider's parser+ * actually reads it — see `compactTakesFocus`.+ */+export function compactionCommandForProvider(+ provider: AgentProvider,+ message: string = DEFAULT_COMPACTION_FOCUS+): string | null {+ const { compact, compactTakesFocus } = contextCommandsForProvider(provider);+ if (!compact) return null;+ const focus = message.trim();+ return compactTakesFocus && focus ? `${compact} ${focus}` : compact;+}++/**+ * The context-clearing command to type, or null when nothing typed can reach+ * this provider.+ *+ * Per `ContextRule.message`, a non-empty message on the CLEAR rule is "the+ * literal command to send" — an override, not a suffix. That asymmetry with+ * compact is deliberate and useful: it is the operator's escape hatch for the+ * providers this table answers `null` for, and for a CLI that renames its verb+ * between releases. Empty message = the table's own bare command.+ */+export function clearCommandForProvider(+ provider: AgentProvider,+ message: string = ''+): string | null {+ const override = message.trim();+ if (override) return override;+ return contextCommandsForProvider(provider).clear;}/** Claude exposes remote control as a slash command; Codex uses its daemon anddiff --git a/src/shared/triggers.ts b/src/shared/triggers.tsnew file mode 100644index 00000000..47408554--- /dev/null+++ b/src/shared/triggers.ts@@ -0,0 +1,309 @@+/**+ * TRIGGERS — every way the God orchestrator gets woken up without a human typing.+ *+ * This module is the single contract shared by main, preload and renderer. Four+ * trigger types live under one roof:+ *+ * schedules — recurring dispatched missions (the pre-existing `ScheduledMission`;+ * still owned by config.missions, surfaced under Triggers)+ * context — auto-compaction / auto-clearing of agent terminal context+ * webhook — inbound HTTP from arbitrary callers, one entry per endpoint+ * org — inbound peer messages from teammates' clone nodes (UI only for now)+ *+ * The webhook and org types both admit an outside party, so both share one+ * `TriggerMode` gate and both write to one `TriggerHistoryEntry` ledger.+ */++/* ────────────────────────────── behaviour gate ───────────────────────────── */++/**+ * How much an external sender is trusted.+ *+ * strict — every inbound message waits for the operator's approval.+ * allow-all — everything flows straight through: messages, directives+ * and communication alike.+ * communication-only — informational traffic flows; anything that asks the hive+ * to *act* (a directive) waits for approval.+ */+export type TriggerMode = 'strict' | 'allow-all' | 'communication-only';++export const TRIGGER_MODES: { value: TriggerMode; label: string; blurb: string }[] = [+ { value: 'strict', label: 'strict', blurb: 'Ask me before anything reaches the hive.' },+ { value: 'allow-all', label: 'allow all', blurb: 'Messages, directives and communication all flow.' },+ { value: 'communication-only', label: 'communication only', blurb: 'Chatter flows; directives need my approval.' }+];++export const DEFAULT_TRIGGER_MODE: TriggerMode = 'strict';++/**+ * What an inbound message is asking for. A *directive* wants the hive to do work;+ * *communication* is informational (a status question, an FYI, a reply).+ * Senders may declare it; `classifyInboundKind` guesses when they don't.+ */+export type InboundKind = 'directive' | 'communication';++/** Resolve a mode + kind into whether the message may be routed without a human. */+export function isAutoAllowed(mode: TriggerMode, kind: InboundKind): boolean {+ if (mode === 'allow-all') return true;+ if (mode === 'communication-only') return kind === 'communication';+ return false; // strict+}++/**+ * Best-effort guess at intent when the payload doesn't declare `kind`.+ *+ * Deliberately conservative: anything we aren't confident is chatter is treated as+ * a directive, because mis-labelling a directive as communication is what lets+ * unapproved work through in `communication-only` mode. Callers who care should+ * send an explicit `kind`.+ */+export function classifyInboundKind(text: string): InboundKind {+ const t = text.trim().toLowerCase();+ if (!t) return 'communication';+ // A leading question with no imperative reads as someone asking, not tasking.+ const asksOnly = /^(what|how|when|where|who|why|is|are|do|does|did|can|could|status|any)\b/.test(t)+ && t.endsWith('?')+ && !/\b(fix|build|ship|deploy|run|write|create|add|remove|delete|refactor|implement|update|merge|revert)\b/.test(t);+ return asksOnly ? 'communication' : 'directive';+}++/* ──────────────────────────── context trigger ────────────────────────────── */++/**+ * One half of the context trigger (compact, or clear). Both the *message* sent to+ * the agent and the *conditions* that fire it are user-editable — that is the whole+ * point of surfacing this as a trigger rather than leaving it hardcoded.+ *+ * A run fires for an agent when BOTH conditions hold:+ * - at least `everyMs` has elapsed since the last run, and+ * - that agent's context is at least `minContextPct` full.+ * `minContextPct` of 0 disables the pressure gate (time alone fires it).+ */+export interface ContextRule {+ enabled: boolean;+ /** Minimum wall-clock gap between runs. */+ everyMs: number;+ /** Percent (0-100) of the context window that must be used before firing. */+ minContextPct: number;+ /**+ * Separate, lower bar for very large context windows (~1M tokens), where a+ * smaller *fraction* is still an enormous absolute amount of text.+ */+ minContextPctLargeWindow: number;+ /**+ * For `compact`: extra focus text appended to the provider's compaction command,+ * on the providers that read trailing text (codex and opencode ignore it, so it+ * is dropped for them rather than typed as stray input).+ *+ * For `clear`: a literal command that OVERRIDES the provider's own clear verb.+ * That override doubles as the escape hatch for providers we deliberately map to+ * nothing — Crush (palette-only), Copilot (print mode), and custom binaries —+ * where the operator knows their CLI and we don't.+ *+ * Empty string = send the provider's bare command.+ */+ message: string;+}++export interface ContextTriggerConfig {+ compact: ContextRule;+ clear: ContextRule;+}++/**+ * The focus text that has always ridden along with `/compact`. Preserved verbatim+ * as the default so upgrading users see no behaviour change beyond the cadence.+ */+export const DEFAULT_COMPACTION_FOCUS =+ 'Keep the current task, recent decisions, open questions, and file paths in play. Drop resolved tangents.';++/**+ * Defaults are deliberately TWICE the old cadence and TWICE the previously+ * documented pressure bar.+ *+ * History: `main/config.ts` documented a 30% / 20% context gate that was never+ * actually implemented — every live agent got compacted on every tick, hourly.+ * This makes the gate real and sets it at 2x, so compaction now costs an agent+ * half as many interruptions.+ *+ * Auto-clear ships DISABLED. `/clear` is destructive — it discards context rather+ * than summarising it, and the codebase already gates the manual verb behind a+ * spoken confirm word. Turning it on is an explicit operator choice.+ */+export const DEFAULT_CONTEXT_TRIGGER: ContextTriggerConfig = {+ compact: {+ enabled: true,+ everyMs: 7_200_000, // 2h — was 1h+ minContextPct: 60, // was a documented-but-unenforced 30+ minContextPctLargeWindow: 40, // was a documented-but-unenforced 20+ message: DEFAULT_COMPACTION_FOCUS+ },+ clear: {+ enabled: false,+ everyMs: 7_200_000,+ minContextPct: 90,+ minContextPctLargeWindow: 80,+ message: ''+ }+};++/* ──────────────────────────── webhook triggers ───────────────────────────── */++/**+ * One inbound endpoint. Several may exist at once; they are multiplexed over a+ * single HTTP server + tunnel and told apart by the `id` in the request path, so+ * adding a webhook costs no extra port and no extra tunnel.+ *+ * `secret` is per-endpoint: revoking one caller never disturbs the others.+ */+export interface WebhookTrigger {+ id: string;+ name: string;+ /** Shared secret the caller echoes in `x-md-webhook-secret`. Never logged. */+ secret: string;+ enabled: boolean;+ mode: TriggerMode;+ /** User-editable JSON Schema (serialised) that inbound bodies are checked against. */+ schema: string;+ createdAt: number;+}++/**+ * The default contract for an inbound POST. Users may edit this per webhook to+ * match whatever the calling system already emits; `message` is the only field the+ * router truly needs.+ */+export const DEFAULT_WEBHOOK_SCHEMA_OBJECT = {+ type: 'object',+ required: ['message'],+ properties: {+ message: { type: 'string', description: 'What you want the orchestrator to know or do.' },+ title: { type: 'string', description: 'Short label for the kanban card.' },+ kind: {+ type: 'string',+ enum: ['directive', 'communication'],+ description: 'directive = asks the hive to act; communication = informational.'+ },+ from: { type: 'string', description: 'Who is sending, for the trigger history.' }+ }+} as const;++export const DEFAULT_WEBHOOK_SCHEMA = JSON.stringify(DEFAULT_WEBHOOK_SCHEMA_OBJECT, null, 2);++/* ────────────────────────── organisation trigger ─────────────────────────── */++/**+ * Peer-to-peer messaging between teammates' installs. Each teammate runs their own+ * Munder Difflin; setting an org key lets their instance address yours.+ *+ * UI + persistence only for now — the transport service does not exist yet, so+ * nothing reads `apiKey` beyond the settings surfaces that display it.+ */+export interface OrgTriggerConfig {+ apiKey: string;+ enabled: boolean;+ mode: TriggerMode;+}++export const DEFAULT_ORG_TRIGGER: OrgTriggerConfig = {+ apiKey: '',+ enabled: false,+ mode: DEFAULT_TRIGGER_MODE+};++/** Copy shown under the org key field. Kept here so Settings and Triggers agree. */+export const CLONE_NODE_BLURB =+ 'Set an organisation key and your teammates can message your clone node — the copy of '+ + 'Munder Difflin running on your machine. Each teammate runs their own, so an org key '+ + 'is how two installs find each other.';++/* ──────────────────────────── trigger history ────────────────────────────── */++/**+ * One line in the ledger. Both directions are recorded so the operator can read a+ * conversation as a conversation: what they sent us, and what we said back.+ * `correlationId` ties our outbound reply to the inbound that prompted it.+ */+export interface TriggerHistoryEntry {+ id: string;+ source: 'webhook' | 'org';+ /** Which webhook (or which peer) — `WebhookTrigger.id` for webhooks. */+ sourceId: string;+ /** Display name at the time of the event, so history survives a rename/delete. */+ sourceName: string;+ direction: 'inbound' | 'outbound';+ /** The other party: who sent it to us, or who we sent it to. */+ peer: string;+ title?: string;+ /** Full message body — never truncated at rest; the UI decides how much to show. */+ body: string;+ kind: InboundKind;+ decision?: 'auto-allowed' | 'pending' | 'approved' | 'rejected';+ correlationId?: string;+ taskId?: string;+ at: number;+}++/** Ledger cap. Oldest entries are dropped past this so the file can't grow forever. */+export const TRIGGER_HISTORY_LIMIT = 500;++/* ───────────────────────── minimal schema validation ─────────────────────── */++/**+ * A deliberately small JSON-Schema subset checker — `type`, `required`,+ * `properties`, `enum`. The project has no validation dependency and inbound+ * webhook bodies do not justify adding one; anything this doesn't understand is+ * ignored rather than treated as a failure, so an exotic user schema degrades to+ * "accept" instead of locking the caller out of their own endpoint.+ */+export function validateAgainstSchema(+ value: unknown,+ schema: unknown+): { ok: true } | { ok: false; error: string } {+ if (!schema || typeof schema !== 'object') return { ok: true };+ const s = schema as Record<string, unknown>;++ const expected = typeof s.type === 'string' ? s.type : undefined;+ if (expected && !matchesType(value, expected)) {+ return { ok: false, error: `expected ${expected}` };+ }++ if (Array.isArray(s.enum) && !s.enum.some((e) => e === value)) {+ return { ok: false, error: `must be one of ${s.enum.map((e) => String(e)).join(', ')}` };+ }++ if (expected === 'object' || (!expected && isPlainObject(value))) {+ if (!isPlainObject(value)) return { ok: false, error: 'expected object' };+ for (const key of Array.isArray(s.required) ? s.required : []) {+ if (typeof key !== 'string') continue;+ const v = (value as Record<string, unknown>)[key];+ if (v === undefined || v === null || v === '') return { ok: false, error: `${key} required` };+ }+ const props = isPlainObject(s.properties) ? s.properties : {};+ for (const [key, sub] of Object.entries(props)) {+ const v = (value as Record<string, unknown>)[key];+ if (v === undefined) continue; // absent optionals are fine; `required` covers the rest+ const r = validateAgainstSchema(v, sub);+ if (!r.ok) return { ok: false, error: `${key}: ${r.error}` };+ }+ }++ return { ok: true };+}++function matchesType(value: unknown, type: string): boolean {+ switch (type) {+ case 'string': return typeof value === 'string';+ case 'number': return typeof value === 'number' && Number.isFinite(value);+ case 'integer': return typeof value === 'number' && Number.isInteger(value);+ case 'boolean': return typeof value === 'boolean';+ case 'array': return Array.isArray(value);+ case 'object': return isPlainObject(value);+ case 'null': return value === null;+ default: return true; // unknown type keyword — don't fail the caller over it+ }+}++function isPlainObject(v: unknown): v is Record<string, unknown> {+ return typeof v === 'object' && v !== null && !Array.isArray(v);+}diff --git a/test/provider-automation.test.cjs b/test/provider-automation.test.cjsindex 21f3b2e5..9ecc72e6 100644--- a/test/provider-automation.test.cjs+++ b/test/provider-automation.test.cjs@@ -5,26 +5,86 @@ const assert = require('node:assert/strict');const loadTs = require('./load-ts.cjs');const {+ clearCommandForProvider,compactionCommandForProvider,- compactionPromptFallback,+ contextCommandsForProvider,remoteControlCommandForProvider,terminalReadySettleMs,terminalReadyToReceive} = loadTs('src/shared/providerAutomation.ts');+const { DEFAULT_COMPACTION_FOCUS } = loadTs('src/shared/triggers.ts');+const { AGENT_PROVIDER_PRESETS } = loadTs('src/shared/agentProvider.ts');test('each provider receives only its supported compaction syntax', () => {- const claude = compactionCommandForProvider('claude');- const codex = compactionCommandForProvider('codex');- const grok = compactionCommandForProvider('grok');- const kimi = compactionCommandForProvider('kimi');-- assert.match(claude, /^\/compact Summarise exactly/);- assert.equal(codex, '/compact');- assert.match(grok, /^\/compact Summarise exactly/);- assert.match(kimi, /^\/compact Summarise exactly/);- assert.equal(compactionCommandForProvider('antigravity'), null);- assert.equal(compactionCommandForProvider('custom'), null);- assert.match(compactionPromptFallback(), /^Summarise the current task/);+ // Verbs differ per CLI: qwen dropped gemini-cli's /compact alias for /compress.+ assert.equal(compactionCommandForProvider('claude', ''), '/compact');+ assert.equal(compactionCommandForProvider('codex', ''), '/compact');+ assert.equal(compactionCommandForProvider('grok', ''), '/compact');+ assert.equal(compactionCommandForProvider('kimi', ''), '/compact');+ assert.equal(compactionCommandForProvider('qwen', ''), '/compress');+ assert.equal(compactionCommandForProvider('opencode', ''), '/compact');+ assert.equal(compactionCommandForProvider('pi', ''), '/compact');++ // No command we can trust → no keystrokes at all.+ for (const p of ['antigravity', 'crush', 'copilot', 'custom']) {+ assert.equal(compactionCommandForProvider(p), null, p);+ }+});++test('the focus rides along only where the TUI parses it', () => {+ const focus = 'keep the auth decisions';+ assert.equal(compactionCommandForProvider('claude', focus), `/compact ${focus}`);+ assert.equal(compactionCommandForProvider('grok', focus), `/compact ${focus}`);+ assert.equal(compactionCommandForProvider('kimi', focus), `/compact ${focus}`);+ assert.equal(compactionCommandForProvider('pi', focus), `/compact ${focus}`);+ assert.equal(compactionCommandForProvider('qwen', focus), `/compress ${focus}`);++ // codex/opencode ignore trailing text, so it must be dropped, not typed.+ assert.equal(compactionCommandForProvider('codex', focus), '/compact');+ assert.equal(compactionCommandForProvider('opencode', focus), '/compact');++ // Omitting the message keeps the trigger default, not a bare command.+ assert.equal(+ compactionCommandForProvider('claude'),+ `/compact ${DEFAULT_COMPACTION_FOCUS}`+ );+ // A whitespace-only message counts as empty.+ assert.equal(compactionCommandForProvider('claude', ' '), '/compact');+});++test('clearing uses each CLI own verb, not a hardcoded /clear', () => {+ assert.equal(clearCommandForProvider('claude'), '/clear');+ assert.equal(clearCommandForProvider('codex'), '/clear');+ assert.equal(clearCommandForProvider('kimi'), '/clear');+ assert.equal(clearCommandForProvider('qwen'), '/clear');+ // agy's /clear resets the conversation; Ctrl+L is the screen-only one.+ assert.equal(clearCommandForProvider('antigravity'), '/clear');+ // These three start a fresh session instead — '/clear' is not a command there.+ assert.equal(clearCommandForProvider('grok'), '/new');+ assert.equal(clearCommandForProvider('opencode'), '/new');+ assert.equal(clearCommandForProvider('pi'), '/new');+ // Palette-only TUI, print-mode CLI, unknown binary: nothing typed can land.+ for (const p of ['crush', 'copilot', 'custom']) {+ assert.equal(clearCommandForProvider(p), null, p);+ }+});++test('a non-empty clear message overrides the table verbatim', () => {+ assert.equal(clearCommandForProvider('grok', '/clear'), '/clear');+ // The operator escape hatch for providers the table answers null for.+ assert.equal(clearCommandForProvider('crush', '/reset'), '/reset');+});++test('every provider preset has a considered context-command entry', () => {+ // Guards the whole point of the table: a new provider must be looked up, not+ // silently defaulted. A missing key would fall back to the all-null entry.+ for (const preset of AGENT_PROVIDER_PRESETS) {+ const entry = contextCommandsForProvider(preset.id);+ assert.ok(entry, preset.id);+ assert.ok(entry.compact === null || entry.compact.startsWith('/'), preset.id);+ assert.ok(entry.clear === null || entry.clear.startsWith('/'), preset.id);+ assert.equal(typeof entry.compactTakesFocus, 'boolean', preset.id);+ }});test('Claude alone receives a remote-control slash command', () => {diff --git a/test/webhook-endpoints.test.cjs b/test/webhook-endpoints.test.cjsnew file mode 100644index 00000000..170f3062--- /dev/null+++ b/test/webhook-endpoints.test.cjs@@ -0,0 +1,257 @@+'use strict';++/**+ * Multi-endpoint webhook server — the routing + isolation rules that a single+ * shared public surface lives or dies on:+ *+ * 1. one server, many endpoints, told apart by the id in the path (and bare+ * `POST /` still means the pre-multi-endpoint `legacy` endpoint);+ * 2. each endpoint is gated by ITS OWN secret, so revoking one caller cannot+ * open or close another's door;+ * 3. an unknown id is answered EXACTLY like a wrong secret, so the surface+ * can't be walked to discover which webhooks exist;+ * 4. the endpoint list is swappable at runtime — a revoked endpoint stops+ * resolving on the very next request, with no restart (a restart would+ * rotate the tunnel URL and break every OTHER caller);+ * 5. per-endpoint rate limiting, so one noisy caller burns its own budget;+ * 6. a held message answers 202 (accepted, not started) with its token.+ *+ * The HTTP handler is driven directly with stub req/res objects: `start()` opens+ * a real tunnel, and a unit test must never reach the network.+ */++const test = require('node:test');+const assert = require('node:assert/strict');+const { EventEmitter } = require('node:events');+const loadTs = require('./load-ts.cjs');++const { WebhookServer, LEGACY_ENDPOINT_ID } = loadTs('src/main/webhook.ts');++const SECRET_A = 'a'.repeat(64);+const SECRET_B = 'b'.repeat(64);+const SCHEMA = JSON.stringify({+ type: 'object',+ required: ['message'],+ properties: { message: { type: 'string' }, count: { type: 'number' } }+});++function endpoints() {+ return [+ { id: 'alpha', name: 'Alpha', secret: SECRET_A, schema: SCHEMA },+ { id: LEGACY_ENDPOINT_ID, name: 'Default webhook', secret: SECRET_B, schema: SCHEMA }+ ];+}++/** A server whose callbacks record what they were handed. */+function makeServer(overrides = {}) {+ const seen = [];+ const server = new WebhookServer({+ port: 0,+ endpoints: endpoints(),+ onMessage: (msg, endpoint) => {+ seen.push({ msg, endpoint });+ if (overrides.pending) return { token: 'tok-pending', pending: true };+ return { token: `tok-${endpoint.id}`, taskId: `webhook-${endpoint.id}`, pending: false };+ },+ lookupStatus: (token) =>+ token === 'good-token' ? { status: 'todo', title: 'a card' } : null,+ ...overrides.opts+ });+ return { server, seen };+}++/** Fire one request through the handler and resolve with `{status, body}`. */+function request(server, { method = 'POST', url = '/', headers = {}, body = undefined }) {+ return new Promise((resolve) => {+ const req = new EventEmitter();+ req.method = method;+ req.url = url;+ req.headers = headers;+ req.destroy = () => { /* no socket to tear down */ };+ const res = {+ writeHead(status) { res._status = status; return res; },+ end(payload) {+ let parsed = null;+ try { parsed = payload ? JSON.parse(payload) : null; } catch { parsed = payload; }+ resolve({ status: res._status, body: parsed });+ }+ };+ server.handleRequest(req, res);+ if (method === 'POST') {+ if (body !== undefined) req.emit('data', Buffer.from(body));+ req.emit('end');+ }+ });+}++const auth = (secret) => ({ 'x-md-webhook-secret': secret });+const post = (msg) => JSON.stringify(msg);++test('each endpoint is gated by its OWN secret', async () => {+ const { server, seen } = makeServer();+ const ok = await request(server, {+ url: '/alpha', headers: auth(SECRET_A), body: post({ message: 'hello' })+ });+ assert.equal(ok.status, 200);+ assert.equal(ok.body.token, 'tok-alpha');+ assert.equal(seen[0].endpoint.id, 'alpha');+ // The handler is handed the endpoint's identity ONLY — never its secret, which+ // must not be able to reach a card, a hive message or the history ledger.+ assert.deepEqual(Object.keys(seen[0].endpoint).sort(), ['id', 'name']);++ // Alpha's door does not open with the other endpoint's key.+ const wrong = await request(server, {+ url: '/alpha', headers: auth(SECRET_B), body: post({ message: 'hello' })+ });+ assert.equal(wrong.status, 401);+});++test('an unknown id is indistinguishable from a wrong secret', async () => {+ const { server, seen } = makeServer();+ const unknown = await request(server, {+ url: '/does-not-exist', headers: auth(SECRET_A), body: post({ message: 'hi' })+ });+ const wrongSecret = await request(server, {+ url: '/alpha', headers: auth(SECRET_B), body: post({ message: 'hi' })+ });+ assert.equal(unknown.status, wrongSecret.status);+ assert.deepEqual(unknown.body, wrongSecret.body);+ assert.deepEqual(unknown.body, { ok: false, error: 'unauthorized' });+ assert.equal(seen.length, 0, 'neither request may reach the dispatch handler');+});++test('bare POST / still means the legacy endpoint', async () => {+ const { server, seen } = makeServer();+ const res = await request(server, {+ url: '/', headers: auth(SECRET_B), body: post({ message: 'legacy caller' })+ });+ assert.equal(res.status, 200);+ assert.equal(seen[0].endpoint.id, LEGACY_ENDPOINT_ID);+});++test('a nested path is not an endpoint', async () => {+ const { server } = makeServer();+ const res = await request(server, {+ url: '/alpha/extra', headers: auth(SECRET_A), body: post({ message: 'hi' })+ });+ assert.equal(res.status, 401);+});++test('setEndpoints revokes one endpoint without touching the others', async () => {+ const { server } = makeServer();+ server.setEndpoints([{ id: LEGACY_ENDPOINT_ID, name: 'Default webhook', secret: SECRET_B, schema: SCHEMA }]);++ const revoked = await request(server, {+ url: '/alpha', headers: auth(SECRET_A), body: post({ message: 'hi' })+ });+ assert.equal(revoked.status, 401, 'the revoked endpoint stops resolving immediately');++ const survivor = await request(server, {+ url: '/legacy', headers: auth(SECRET_B), body: post({ message: 'hi' })+ });+ assert.equal(survivor.status, 200, 'every other endpoint is undisturbed');+});++test('the body is validated against THAT endpoint schema', async () => {+ const { server } = makeServer();+ const bad = await request(server, {+ url: '/alpha', headers: auth(SECRET_A), body: post({ message: 'hi', count: 'seven' })+ });+ assert.equal(bad.status, 400);+ assert.match(bad.body.error, /count/);++ const missing = await request(server, {+ url: '/alpha', headers: auth(SECRET_A), body: post({ title: 'no message here' })+ });+ assert.equal(missing.status, 400);++ const junk = await request(server, {+ url: '/alpha', headers: auth(SECRET_A), body: 'not json at all'+ });+ assert.equal(junk.status, 400);+ assert.equal(junk.body.error, 'bad json');+});++test('the caller declaration of kind/from is passed through', async () => {+ const { server, seen } = makeServer();+ await request(server, {+ url: '/alpha',+ headers: auth(SECRET_A),+ body: post({ message: 'ship it', kind: 'communication', from: 'ci-bot', title: 'build' })+ });+ assert.equal(seen[0].msg.kind, 'communication');+ assert.equal(seen[0].msg.from, 'ci-bot');+ assert.equal(seen[0].msg.title, 'build');+ // A kind the enum doesn't know is dropped rather than trusted.+ await request(server, {+ url: '/alpha', headers: auth(SECRET_A), body: post({ message: 'x', kind: 'anything-goes' })+ });+ assert.equal(seen[1].msg.kind, undefined);+});++test('a held message answers 202 with its token and no task', async () => {+ const { server } = makeServer({ pending: true });+ const res = await request(server, {+ url: '/alpha', headers: auth(SECRET_A), body: post({ message: 'do the thing' })+ });+ assert.equal(res.status, 202);+ assert.equal(res.body.pending, true);+ assert.equal(res.body.status, 'awaiting-approval');+ assert.equal(res.body.token, 'tok-pending');+ assert.equal(res.body.taskId, undefined);+});++test('GET is token-scoped, and answers 404 identically for every miss', async () => {+ const { server } = makeServer();+ const ok = await request(server, {+ method: 'GET', url: '/alpha', headers: { 'x-md-webhook-token': 'good-token' }+ });+ assert.equal(ok.status, 200);+ assert.equal(ok.body.status, 'todo');++ const badToken = await request(server, {+ method: 'GET', url: '/alpha', headers: { 'x-md-webhook-token': 'nope' }+ });+ const badEndpoint = await request(server, {+ method: 'GET', url: '/ghost', headers: { 'x-md-webhook-token': 'good-token' }+ });+ assert.deepEqual(badToken.body, badEndpoint.body);+ assert.equal(badToken.status, 404);+ assert.equal(badEndpoint.status, 404);++ const noToken = await request(server, { method: 'GET', url: '/alpha' });+ assert.equal(noToken.status, 401);+});++test('the query-param token fallback still works', async () => {+ const { server } = makeServer();+ const res = await request(server, { method: 'GET', url: '/alpha?token=good-token' });+ assert.equal(res.status, 200);+});++test('one noisy endpoint cannot starve the others', async () => {+ const { server } = makeServer();+ let limited = 0;+ for (let i = 0; i < 61; i++) {+ const r = await request(server, {+ url: '/alpha', headers: auth(SECRET_A), body: post({ message: `n${i}` })+ });+ if (r.status === 429) limited++;+ }+ assert.ok(limited > 0, 'the per-endpoint budget must trip before the global one');++ const other = await request(server, {+ url: '/legacy', headers: auth(SECRET_B), body: post({ message: 'still fine' })+ });+ assert.equal(other.status, 200, 'a different endpoint keeps its own budget');+});++test('a secretless endpoint is never served', async () => {+ const { server } = makeServer();+ server.setEndpoints([{ id: 'empty', name: 'Empty', secret: '', schema: SCHEMA }]);+ assert.deepEqual(server.endpointIds(), []);+ const res = await request(server, {+ url: '/empty', headers: { 'x-md-webhook-secret': '' }, body: post({ message: 'hi' })+ });+ assert.equal(res.status, 401);+});