Skip to content

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

Merge remote-tracking branch 'origin/feat/limit-aware-queue' into integrate/v0.3.8

Chaitanya Giria4d99d5f5a7b
diff --cc src/main/config.ts
index 78e07041,7804d62f..c4fec87a
--- a/src/main/config.ts
+++ b/src/main/config.ts
@@@ -12,15 -12,7 +12,16 @@@ 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';
+ import type { LimitHold } from '../shared/rateLimit';
/** A recurring auto-dispatched mission fired on an interval by the scheduler. */
export interface ScheduledMission {
diff --cc src/main/index.ts
index a67f67da,5332ce89..473c132c
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@@ -620,14 -615,13 +627,18 @@@ 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.
- // Skip compaction entirely while anything is rate limited. /compact is a
- // model call: sending it into a capped-out CLI spends a rejected attempt
- // and, worse, leaves a queued /compact ahead of the operator's real
- // backlog when the window reopens. The next tick picks it up.
- const compactionHeld = limitGuardSettings().enabled && limitGate.list().length > 0;
- if ((m.autoCompact || m.kind === 'compact') && !compactionHeld) {
- try { liveWebContents()?.send('mission:autoCompact'); } catch { /* window gone */ }
+ //
+ // 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.
++ //
++ // Rate-limit holds are enforced inside emitContextTrigger, which is the
++ // single choke point both this path and the context trigger's own timer
++ // pass through.
+ if (m.autoCompact || m.kind === 'compact') {
+ emitContextTrigger('compact', contextRule('compact'));
}
const current = readConfig().missions ?? [];
const next = current.map((x) =>
@@@ -653,114 -647,6 +664,126 @@@
}
}
+// ─── 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. */
++/** Ask the renderer to run one half of the context trigger.
++ *
++ * COMPACTION IS HELD WHILE ANYTHING IS RATE LIMITED. `/compact` is a model call:
++ * sending it into a capped-out CLI spends a rejected attempt and, worse, leaves a
++ * queued `/compact` sitting ahead of the operator's real backlog when the window
++ * reopens. The next tick picks it up once the hold lifts.
++ *
++ * The gate lives HERE rather than at the call sites because there are two of
++ * them — the legacy per-mission `autoCompact` flag and the context trigger's own
++ * timer — and a gate on only one of them is no gate at all. `clear` is
++ * deliberately NOT held: it is handled locally by the CLI, costs no model call,
++ * and a capped agent is exactly when trimming context is still useful. */
+function emitContextTrigger(action: 'compact' | 'clear', rule: ContextRule): void {
++ if (action === 'compact' && limitGuardSettings().enabled && limitGate.list().length > 0) return;
+ 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`
diff --cc src/preload/index.ts
index d1b60db7,b2c56d20..4e419d4f
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@@ -5,13 -5,8 +5,14 @@@ export type { HireManifest } from '../s
import type { IntegrationRecord, IntegrationTemplate } from '../shared/integrations';
export type { IntegrationRecord, IntegrationTemplate } from '../shared/integrations';
import type { UpdateStatus } from '../shared/updateState';
+ import type { LimitHold, LimitSignal } from '../shared/rateLimit';
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
diff --cc src/renderer/src/components/CommandCenterPanel.tsx
index 9353d608,dab6dc13..0f749852
--- a/src/renderer/src/components/CommandCenterPanel.tsx
+++ b/src/renderer/src/components/CommandCenterPanel.tsx
@@@ -16,8 -15,9 +16,9 @@@ 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 { LimitBanner, LimitSummary } from './LimitBanner';
import {
buildSpawnCommand,
decodeProviderModel,
diff --cc src/renderer/src/components/SettingsModal.tsx
index c1641557,d3ccd6e6..48f7ef89
--- a/src/renderer/src/components/SettingsModal.tsx
+++ b/src/renderer/src/components/SettingsModal.tsx
@@@ -400,8 -402,9 +447,9 @@@ export function SettingsModal({ config
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);
+ setLimitGuard({ ...LIMIT_GUARD_FALLBACK, ...((c as HarnessConfig).limitGuard ?? {}) });
setAgentBudget(cc.costCapTokens != null ? String(cc.costCapTokens) : '');
setVelocityCeiling(cc.circuitBreaker?.tokenVelocityPerMin != null ? String(cc.circuitBreaker.tokenVelocityPerMin) : '');
setSlackEnabled(cc.slackEnabled ?? false);
diff --cc src/renderer/src/store/config.ts
index fbc5f138,4440171a..2de8e218
--- a/src/renderer/src/store/config.ts
+++ b/src/renderer/src/store/config.ts
@@@ -121,26 -116,14 +121,34 @@@ 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;
+ /** How the floor reacts when a CLI reports it has hit its usage limit.
+ * Mirrors `LimitGuardConfig` in main/config.ts. */
+ limitGuard?: {
+ enabled: boolean;
+ autoResume: boolean;
+ holdOnThrottle: boolean;
+ notify: boolean;
+ };
}
/** The Sonnet model with the 1M-token context window — used for Michael's prep
diff --cc src/renderer/src/store/store.ts
index 9933819e,6010e458..a68577b5
--- a/src/renderer/src/store/store.ts
+++ b/src/renderer/src/store/store.ts
@@@ -5,7 -5,7 +5,8 @@@ import type { ThemeId } from '@/scene/o
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';
+ import type { LimitHold } from '@shared/rateLimit';
export type ToolKind =
| 'Read' | 'Edit' | 'Write' | 'Bash' | 'WebFetch' | 'WebSearch'