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: PR #71 (shareable hires / Hiring Fair) onto v0.2.7 main + close security issues

Chaitanya Giric4cf3567caa9
diff --cc electron-builder.yml
index fdc166b5,64833e56..ffa15491
--- a/electron-builder.yml
+++ b/electron-builder.yml
@@@ -1,114 -1,112 +1,121 @@@
-appId: in.munderdiffl.app
-productName: Munder Difflin
-copyright: Copyright © 2026 Chaitanya Giri
-
-# Notarize + staple after signing, but only when APPLE_* creds are in the env
-# (the hook no-ops otherwise, so contributor builds still work). Root-level hook.
-afterSign: build/notarize.cjs
-
-# Register the munderdifflin:// URL scheme (shareable-hires deep link) in the
-# packaged app: CFBundleURLTypes on macOS, registry entries via NSIS on Windows.
-protocols:
- - name: Munder Difflin
- schemes:
- - munderdifflin
-
-# electron-vite emits the app into out/; package exactly that plus what the
-# runtime needs. node-pty is native, so keep it out of the asar.
-directories:
- output: dist
- buildResources: build
-
-files:
- - out/**
- - package.json
- - "!**/*.{md,map,ts,tsx}"
- - "!**/{.eslintrc,.prettierrc,tsconfig*.json,electron.vite.config.*}"
-
-# Ship the standalone Slack reply helper as a plain file under the app's
-# resources dir (process.resourcesPath). It runs under `node`, NOT inside the
-# asar, so the office worker can invoke `node <resources>/md-slack-reply.cjs`.
-extraResources:
- - from: resources/md-slack-reply.cjs
- to: md-slack-reply.cjs
-
-asarUnpack:
- - "**/node_modules/node-pty/**"
- # better-sqlite3 is native (bindings/prebuild need the .node on the real FS).
- - "**/node_modules/better-sqlite3/**"
-
-# Rebuild native deps (node-pty) for the target during packaging.
-npmRebuild: true
-
-# ---- macOS ----
-mac:
- category: public.app-category.developer-tools
- icon: build/icon.icns
- # Declare WHY the app touches the user's folders. macOS shows these strings in
- # the privacy prompt and, for a signed app, remembers the grant — so the user
- # is asked ONCE instead of on every agent action.
- extendInfo:
- NSDocumentsFolderUsageDescription: "Munder Difflin runs your Claude Code agents, which read and write files in the project folders you point them at."
- NSDesktopFolderUsageDescription: "Munder Difflin's agents may work on projects located on your Desktop."
- NSDownloadsFolderUsageDescription: "Munder Difflin's agents may work on projects located in your Downloads."
- NSRemovableVolumesUsageDescription: "Munder Difflin's agents may work on projects located on external volumes."
- NSNetworkVolumesUsageDescription: "Munder Difflin's agents may work on projects located on network volumes."
- # Hardened runtime + entitlements so the spawned `claude` agents inherit this
- # app's TCC responsibility (one grant covers them all) and node-pty can load.
- hardenedRuntime: true
- entitlements: build/entitlements.mac.plist
- entitlementsInherit: build/entitlements.mac.plist
- gatekeeperAssess: false
- # Disable electron-builder's BUILT-IN notarization. It auto-triggers whenever the
- # APPLE_* env vars are present and runs inside signApp — a path our afterSign hook's
- # try/catch can't guard, so a bad-credential failure there hard-fails the whole
- # release (exactly what bit us). Instead, the root-level `afterSign: build/notarize.cjs`
- # hook does notarization best-effort: it tries, and on failure ships the signed (un-
- # notarized) build rather than sinking the cross-platform release. Notarization
- # resumes automatically once the APPLE_* secrets are valid — no further changes.
- notarize: false
- # Signing: TCC binds a remembered grant to a STABLE code signature, so a signed
- # build is asked for folder access ONCE. The "Developer ID Application" cert is
- # auto-discovered from the login keychain (CSC_IDENTITY_AUTO_DISCOVERY). If no
- # cert is found, electron-builder warns and produces an unsigned build, so
- # contributors without an Apple account can still build.
- # To sign: install your "Developer ID Application" cert into the keychain.
- # (Override with CSC_LINK=<path-to.p12> + CSC_KEY_PASSWORD for CI.)
- # Notarization happens in the root-level `afterSign` hook (top of this file).
- target:
- - target: dmg
- arch: [universal]
- artifactName: Munder-Difflin-${version}-mac-${arch}.dmg
-
-dmg:
- title: Munder Difflin ${version}
-
-# ---- Windows ----
-win:
- icon: build/icon.ico
- target:
- - target: nsis
- arch: [x64]
- - target: portable
- arch: [x64]
-
-nsis:
- oneClick: false
- perMachine: false
- allowToChangeInstallationDirectory: true
- artifactName: Munder-Difflin-${version}-win-x64-setup.exe
- shortcutName: Munder Difflin
-
-portable:
- artifactName: Munder-Difflin-${version}-win-x64-portable.exe
-
-# ---- Linux ----
-linux:
- category: Development
- icon: build/icon.png
- target:
- - target: AppImage
- arch: [x64]
- artifactName: Munder-Difflin-${version}-linux-x86_64.AppImage
+appId: in.munderdiffl.app
+productName: Munder Difflin
+copyright: Copyright © 2026 Chaitanya Giri
+
+# Notarize + staple after signing, but only when APPLE_* creds are in the env
+# (the hook no-ops otherwise, so contributor builds still work). Root-level hook.
+afterSign: build/notarize.cjs
+
++# Register the munderdifflin:// URL scheme (shareable-hires deep link) in the
++# packaged app: CFBundleURLTypes on macOS, registry entries via NSIS on Windows.
++protocols:
++ - name: Munder Difflin
++ schemes:
++ - munderdifflin
++
+# electron-vite emits the app into out/; package exactly that plus what the
+# runtime needs. node-pty is native, so keep it out of the asar.
+directories:
+ output: dist
+ buildResources: build
+
+files:
+ - out/**
+ - package.json
+ - "!**/*.{md,map,ts,tsx}"
+ - "!**/{.eslintrc,.prettierrc,tsconfig*.json,electron.vite.config.*}"
+
+# Ship the standalone Slack reply helper as a plain file under the app's
+# resources dir (process.resourcesPath). It runs under `node`, NOT inside the
+# asar, so the office worker can invoke `node <resources>/md-slack-reply.cjs`.
+extraResources:
+ - from: resources/md-slack-reply.cjs
+ to: md-slack-reply.cjs
+ # Knowledge Graph agent CLI + its pure-JS core. Agents invoke `node
+ # <resources>/kg.cjs` out-of-process; kg-core.cjs ships beside it so the CLI's
+ # `require('./kg-core.cjs')` resolves outside the asar.
+ - from: resources/kg.cjs
+ to: kg.cjs
+ - from: src/main/kg-core.cjs
+ to: kg-core.cjs
+
+asarUnpack:
+ - "**/node_modules/node-pty/**"
+ # better-sqlite3 is native (bindings/prebuild need the .node on the real FS).
+ - "**/node_modules/better-sqlite3/**"
+
+# Rebuild native deps (node-pty) for the target during packaging.
+npmRebuild: true
+
+# ---- macOS ----
+mac:
+ category: public.app-category.developer-tools
+ icon: build/icon.icns
+ # Declare WHY the app touches the user's folders. macOS shows these strings in
+ # the privacy prompt and, for a signed app, remembers the grant — so the user
+ # is asked ONCE instead of on every agent action.
+ extendInfo:
+ NSDocumentsFolderUsageDescription: "Munder Difflin runs your Claude Code agents, which read and write files in the project folders you point them at."
+ NSDesktopFolderUsageDescription: "Munder Difflin's agents may work on projects located on your Desktop."
+ NSDownloadsFolderUsageDescription: "Munder Difflin's agents may work on projects located in your Downloads."
+ NSRemovableVolumesUsageDescription: "Munder Difflin's agents may work on projects located on external volumes."
+ NSNetworkVolumesUsageDescription: "Munder Difflin's agents may work on projects located on network volumes."
+ # Free Flow voice dictation records the microphone (opt-in; off by default).
+ NSMicrophoneUsageDescription: "Munder Difflin records your voice only when you use Free Flow dictation, then sends it to Groq to transcribe into the message queue."
+ # Hardened runtime + entitlements so the spawned `claude` agents inherit this
+ # app's TCC responsibility (one grant covers them all) and node-pty can load.
+ hardenedRuntime: true
+ entitlements: build/entitlements.mac.plist
+ entitlementsInherit: build/entitlements.mac.plist
+ gatekeeperAssess: false
+ # Disable electron-builder's BUILT-IN notarization. It auto-triggers whenever the
+ # APPLE_* env vars are present and runs inside signApp — a path our afterSign hook's
+ # try/catch can't guard, so a bad-credential failure there hard-fails the whole
+ # release (exactly what bit us). Instead, the root-level `afterSign: build/notarize.cjs`
+ # hook does notarization best-effort: it tries, and on failure ships the signed (un-
+ # notarized) build rather than sinking the cross-platform release. Notarization
+ # resumes automatically once the APPLE_* secrets are valid — no further changes.
+ notarize: false
+ # Signing: TCC binds a remembered grant to a STABLE code signature, so a signed
+ # build is asked for folder access ONCE. The "Developer ID Application" cert is
+ # auto-discovered from the login keychain (CSC_IDENTITY_AUTO_DISCOVERY). If no
+ # cert is found, electron-builder warns and produces an unsigned build, so
+ # contributors without an Apple account can still build.
+ # To sign: install your "Developer ID Application" cert into the keychain.
+ # (Override with CSC_LINK=<path-to.p12> + CSC_KEY_PASSWORD for CI.)
+ # Notarization happens in the root-level `afterSign` hook (top of this file).
+ target:
+ - target: dmg
+ arch: [universal]
+ artifactName: Munder-Difflin-${version}-mac-${arch}.dmg
+
+dmg:
+ title: Munder Difflin ${version}
+
+# ---- Windows ----
+win:
+ icon: build/icon.ico
+ target:
+ - target: nsis
+ arch: [x64]
+ - target: portable
+ arch: [x64]
+
+nsis:
+ oneClick: false
+ perMachine: false
+ allowToChangeInstallationDirectory: true
+ artifactName: Munder-Difflin-${version}-win-x64-setup.exe
+ shortcutName: Munder Difflin
+
+portable:
+ artifactName: Munder-Difflin-${version}-win-x64-portable.exe
+
+# ---- Linux ----
+linux:
+ category: Development
+ icon: build/icon.png
+ target:
+ - target: AppImage
+ arch: [x64]
+ artifactName: Munder-Difflin-${version}-linux-x86_64.AppImage
diff --cc src/main/hire.ts
index 00000000,8ee324eb..9bb21ba0
mode 000000,100644..100644
--- a/src/main/hire.ts
+++ b/src/main/hire.ts
@@@ -1,0 -1,122 +1,193 @@@
+ /**
+ * Hire-manifest transport for the main process: fetch a manifest from an https
+ * URL (deep link) or read one from disk (file import), and validate it via the
+ * shared, dependency-free validator. See `src/shared/hire.ts` for the spec and
+ * security model. Deliberately free of any `electron` import so it can be
+ * smoke-tested as a plain Node module (mirrors webhook.ts's approach).
+ */
+ import { readFileSync, statSync } from 'node:fs';
++import { lookup } from 'node:dns/promises';
++import { isIP } from 'node:net';
+ import {
+ HIRE_MAX_BYTES,
+ isAllowedManifestUrl,
+ validateHireManifest,
+ type HireManifest,
+ type HireValidation
+ } from '../shared/hire';
+
+ export type HireResult = { ok: true; manifest: HireManifest } | { ok: false; error: string };
+
+ function finish(v: HireValidation): HireResult {
+ if (v.ok && v.manifest) return { ok: true, manifest: v.manifest };
+ return { ok: false, error: `invalid hire manifest: ${v.errors.join('; ')}` };
+ }
+
++/** True if an IP LITERAL is in a range we must never fetch from (SSRF guard):
++ * loopback, RFC1918 private, link-local incl. the 169.254.169.254 cloud-metadata
++ * endpoint, CGNAT, ULA, and unspecified/multicast/reserved. https alone does NOT
++ * make a target safe — a remote manifest can point/redirect at https://10.x or
++ * https://169.254.169.254, so the resolved ADDRESS is what we gate on. */
++function isBlockedIp(ip: string): boolean {
++ const kind = isIP(ip);
++ if (kind === 4) {
++ const o = ip.split('.').map(Number);
++ if (o.length !== 4 || o.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return true;
++ if (o[0] === 0 || o[0] === 127) return true; // 0.0.0.0/8 unspecified, 127/8 loopback
++ if (o[0] === 10) return true; // 10.0.0.0/8
++ if (o[0] === 172 && o[1] >= 16 && o[1] <= 31) return true; // 172.16.0.0/12
++ if (o[0] === 192 && o[1] === 168) return true; // 192.168.0.0/16
++ if (o[0] === 169 && o[1] === 254) return true; // 169.254.0.0/16 link-local + metadata
++ if (o[0] === 100 && o[1] >= 64 && o[1] <= 127) return true; // 100.64.0.0/10 CGNAT
++ if (o[0] >= 224) return true; // 224.0.0.0/3 multicast/reserved
++ return false;
++ }
++ if (kind === 6) {
++ const lower = ip.toLowerCase();
++ if (lower === '::1' || lower === '::') return true; // loopback / unspecified
++ // IPv4-mapped (::ffff:a.b.c.d) — judge by the embedded v4 address.
++ if (lower.startsWith('::ffff:')) {
++ const v4 = lower.slice(lower.lastIndexOf(':') + 1);
++ if (isIP(v4) === 4) return isBlockedIp(v4);
++ }
++ if (lower.startsWith('fe8') || lower.startsWith('fe9') || lower.startsWith('fea') || lower.startsWith('feb')) return true; // fe80::/10 link-local
++ if (lower.startsWith('fc') || lower.startsWith('fd')) return true; // fc00::/7 ULA
++ return false;
++ }
++ return true; // not a parseable IP → fail closed
++}
++
++/** Resolve a host (or use the literal IP) and return true if ANY resolved
++ * address is in a blocked range. Unresolvable → blocked (fail closed). Closes
++ * the simple DNS-to-internal SSRF; a determined rebind between this lookup and
++ * fetch()'s own resolution is a residual we accept for v1 (no connection pinning). */
++async function isInternalHost(hostname: string): Promise<boolean> {
++ const host = hostname.replace('[', '').replace(']', ''); // strip IPv6 brackets
++ if (isIP(host)) return isBlockedIp(host);
++ try {
++ const addrs = await lookup(host, { all: true });
++ return addrs.length === 0 || addrs.some((a) => isBlockedIp(a.address));
++ } catch { return true; }
++}
++
++/** SSRF gate for ONE url — the initial request AND every redirect hop. The only
++ * internal target permitted is the documented http-loopback dev gallery (already
++ * gated by isAllowedManifestUrl); every other target must resolve to a PUBLIC
++ * address. Returns an error string when the target is internal, else null. */
++async function assertPublicTarget(u: URL): Promise<string | null> {
++ const devLoopbackHttp = u.protocol === 'http:' &&
++ (u.hostname === 'localhost' || u.hostname === '127.0.0.1' || u.hostname === '[::1]');
++ if (devLoopbackHttp) return null;
++ if (await isInternalHost(u.hostname)) {
++ return 'manifest URL resolves to a private/loopback/link-local address (SSRF blocked)';
++ }
++ return null;
++}
++
+ /** Fetch + validate a hire manifest from an https URL. Bounded: 10s timeout,
+ * 64 KB body cap, https only (the deep-link parser already enforces https,
+ * but this is also called with user-pasted URLs). */
+ export async function fetchHireManifest(src: string): Promise<HireResult> {
+ let url: URL;
+ try { url = new URL(src); } catch { return { ok: false, error: 'not a valid URL' }; }
+ if (!isAllowedManifestUrl(url)) return { ok: false, error: 'manifest URL must be https (http allowed for localhost only)' };
+
+ const ctrl = new AbortController();
+ const timer = setTimeout(() => ctrl.abort(), 10_000);
+ try {
+ // redirect:'manual' — `follow` would only validate the INITIAL url, so a
+ // remote https manifest could 302 to http://127.0.0.1:PORT/... or a cloud
+ // metadata endpoint, turning a clicked link into a blind GET to an internal
+ // service. We follow hops ourselves and re-validate each Location.
+ // - the INITIAL url may be http-loopback (local gallery dev served over
+ // http://localhost) — isAllowedManifestUrl permits that;
+ // - a REDIRECT TARGET must be https. A real gallery never needs to bounce
+ // you into loopback/internal http, and requiring https on hops closes
+ // redirect-based SSRF to 127.0.0.1:PORT and link-local/metadata IPs
+ // outright, while https→https redirects (shorteners, CDNs) still work.
++ // - AND the resolved ADDRESS of every target (initial + each hop) must be
++ // public: https://10.x / https://169.254.169.254 would otherwise sail
++ // through the https-only check. assertPublicTarget resolves DNS and
++ // blocks private/loopback/link-local/metadata IPs.
++ const ssrf0 = await assertPublicTarget(url);
++ if (ssrf0) return { ok: false, error: ssrf0 };
+ let current = url;
+ let res: Response | null = null;
+ for (let hop = 0; hop < 5; hop++) {
+ res = await fetch(current, {
+ signal: ctrl.signal,
+ redirect: 'manual',
+ headers: { accept: 'application/json' }
+ });
+ if (res.status >= 300 && res.status < 400) {
+ const loc = res.headers.get('location');
+ if (!loc) return { ok: false, error: 'redirect without a location' };
+ let next: URL;
+ try { next = new URL(loc, current); } catch { return { ok: false, error: 'invalid redirect target' }; }
+ if (next.protocol !== 'https:') return { ok: false, error: 'redirect target must be https (a manifest may not redirect into http/loopback)' };
++ const ssrfN = await assertPublicTarget(next);
++ if (ssrfN) return { ok: false, error: ssrfN };
+ current = next;
+ continue;
+ }
+ break;
+ }
+ if (!res) return { ok: false, error: 'fetch failed' };
+ if (res.status >= 300 && res.status < 400) return { ok: false, error: 'too many redirects' };
+ if (!res.ok) return { ok: false, error: `fetch failed: HTTP ${res.status}` };
+
+ // Bound the body as we read it — content-length is attacker-controlled
+ // (absent/chunked skips the check), and `res.text()` would buffer the whole
+ // stream first, so a hostile host could stream unbounded data and OOM us
+ // inside the 10s window. Read chunks, abort once bytes exceed the cap.
+ const len = Number(res.headers.get('content-length') ?? 0);
+ if (len > HIRE_MAX_BYTES) return { ok: false, error: 'manifest too large' };
+ const text = await readBounded(res, HIRE_MAX_BYTES);
+ if (text === null) return { ok: false, error: 'manifest too large' };
+
+ let parsed: unknown;
+ try { parsed = JSON.parse(text); } catch { return { ok: false, error: 'manifest is not valid JSON' }; }
+ return finish(validateHireManifest(parsed));
+ } catch (e) {
+ const msg = e instanceof Error && e.name === 'AbortError' ? 'fetch timed out' : String(e);
+ return { ok: false, error: `fetch failed: ${msg}` };
+ } finally {
+ clearTimeout(timer);
+ }
+ }
+
+ /** Read a response body, decoding as UTF-8, aborting once the byte count exceeds
+ * `maxBytes`. Returns null if the cap is exceeded. Byte-accurate (the cap is a
+ * byte limit, not UTF-16 code units). */
+ async function readBounded(res: Response, maxBytes: number): Promise<string | null> {
+ const body = res.body;
+ if (!body) {
+ // No stream (e.g. some fetch polyfills) — fall back to text() with a post-check.
+ const t = await res.text();
+ return Buffer.byteLength(t, 'utf8') > maxBytes ? null : t;
+ }
+ const reader = body.getReader();
+ const chunks: Uint8Array[] = [];
+ let total = 0;
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ if (value) {
+ total += value.byteLength;
+ if (total > maxBytes) { try { await reader.cancel(); } catch { /* noop */ } return null; }
+ chunks.push(value);
+ }
+ }
+ return Buffer.concat(chunks).toString('utf8');
+ }
+
+ /** Read + validate a hire manifest from a local JSON file (file import). */
+ export function readHireManifestFile(path: string): HireResult {
+ try {
+ if (statSync(path).size > HIRE_MAX_BYTES) return { ok: false, error: 'manifest too large' };
+ const parsed: unknown = JSON.parse(readFileSync(path, 'utf8'));
+ return finish(validateHireManifest(parsed));
+ } catch (e) {
+ return { ok: false, error: `could not read manifest: ${String(e)}` };
+ }
+ }
diff --cc src/main/index.ts
index 1f194784,ddf9a03d..9ec83555
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@@ -26,9 -25,10 +26,11 @@@ import { readAgentUsage, readContextTok
import { listIssues, listCIRuns } from './github';
import { SlackWebhookServer, SlackReplyServer, postSlackReply, type SlackEventFile } from './slack';
import { WebhookServer, type WebhookInbound, type WebhookTaskStatus } from './webhook';
+import { transcribeWithGroq, DEFAULT_GROQ_MODEL } from './freeflow';
import { TelemetryCollector } from './telemetry';
import { ControlRegistry } from './control';
+ import { fetchHireManifest, readHireManifestFile } from './hire';
+ import { parseHireDeepLink, type HireManifest } from '../shared/hire';
import { ClosingTimeController } from './closingTime';
import {
inferAgentProvider,
@@@ -39,19 -39,6 +41,20 @@@
} from '../shared/agentProvider';
const isDev = !!process.env.ELECTRON_RENDERER_URL;
+
- // Keep the hive alive through transient faults. The floor is a long-running
++// Keep the main process alive on an unexpected throw/rejection. The harness is a
+// multi-agent supervisor — a single stray throw (e.g. node-pty's ConPTY console
+// helper choking when a fast-exiting agent CLI's console is already gone) must
+// NOT take the whole app and every running agent down with it. Log and continue
+// rather than letting the default handler exit the process.
++// (Restored during the #71 merge — the PR's rebase dropped these handlers.)
+process.on('uncaughtException', (err) => {
+ console.error('[main] uncaughtException (kept alive):', err);
+});
+process.on('unhandledRejection', (reason) => {
+ console.error('[main] unhandledRejection (kept alive):', reason);
+});
+
const ptyManager = new PtyManager();
/** Live PTY id → its hive agent id, recorded at spawn. The pty:kill handler only
* gets the PTY id, so this lets a closed tab archive the right registry agent. */
@@@ -1142,42 -1103,117 +1138,135 @@@ function debounce(fn: () => void, ms: n
return () => { if (t) clearTimeout(t); t = setTimeout(() => { t = null; fn(); }, ms); };
}
+/** Cascade a new floor off the focused window so it doesn't stack exactly on
+ * top, clamped on-screen (clampBounds drops an off-display position). */
+function floorCascade(): WindowBounds | null {
+ const base = (mainWindow && !mainWindow.isDestroyed())
+ ? mainWindow
+ : [...allWindows].find((w) => !w.isDestroyed());
+ if (!base) return null;
+ const b = base.getBounds();
+ const OFFSET = 36;
+ return clampBounds({ x: b.x + OFFSET, y: b.y + OFFSET, width: b.width, height: b.height });
+}
+
+ // ─── Shareable hires: munderdifflin:// deep link + file import ──────────────
+ // A hire manifest NEVER auto-spawns: it is validated, then handed to the
+ // renderer, which pre-fills the Add-Agent modal for human review. See
+ // src/shared/hire.ts for the spec + security model.
+
+ /** Manifests that arrived before the renderer was ready to receive them.
+ * The renderer PULLS these via hire:drainPending once its subscription is
+ * mounted — main never pushes blind, so a fast-loading packaged renderer
+ * can't lose a deep link to a startup race. */
+ const pendingHires: HireManifest[] = [];
+ let rendererReadyForHires = false;
+
+ function deliverHire(manifest: HireManifest): void {
+ if (rendererReadyForHires && mainWindow && !mainWindow.isDestroyed()) {
+ mainWindow.show();
+ mainWindow.focus();
+ mainWindow.webContents.send('hire:import', manifest);
+ } else {
+ pendingHires.push(manifest);
+ if (mainWindow && !mainWindow.isDestroyed()) {
+ mainWindow.show();
+ mainWindow.focus();
+ }
+ }
+ }
+
+ async function handleHireLink(link: string): Promise<void> {
+ const src = parseHireDeepLink(link);
+ if (!src) { console.warn('[hire] ignoring malformed deep link'); return; }
+ const res = await fetchHireManifest(src);
+ if (!res.ok) {
+ console.error('[hire] deep link rejected:', res.error);
+ if (mainWindow && !mainWindow.isDestroyed()) {
+ mainWindow.webContents.send('hire:error', { error: res.error });
+ }
+ return;
+ }
+ deliverHire(res.manifest);
+ }
+
+ // Register the protocol. In dev (electron .) Windows needs the explicit
+ // exe+args form or the registration points at electron.exe with no entry.
+ if (process.defaultApp) {
+ if (process.argv.length >= 2) {
+ app.setAsDefaultProtocolClient('munderdifflin', process.execPath, [resolve(process.argv[1])]);
+ }
+ } else {
+ app.setAsDefaultProtocolClient('munderdifflin');
+ }
+
+ // Deep links on Windows/Linux arrive as the argv of a SECOND process — take the
+ // single-instance lock and forward them to the running instance. (macOS gets
+ // the 'open-url' event instead.) The lock also rules out two harnesses fighting
+ // over the same hive, which was previously possible but never useful.
+ const gotInstanceLock = app.requestSingleInstanceLock();
+ if (!gotInstanceLock) {
+ allowQuit = true;
+ app.quit();
+ } else {
+ app.on('second-instance', (_evt, argv) => {
+ if (mainWindow) {
+ if (mainWindow.isMinimized()) mainWindow.restore();
+ mainWindow.focus();
+ }
+ const link = argv.find((a) => a.startsWith('munderdifflin://'));
+ if (link) void handleHireLink(link);
+ });
+ }
+
+ app.on('open-url', (evt, url) => {
+ evt.preventDefault();
+ void handleHireLink(url);
+ });
+
+ // IPC: the renderer signals readiness and PULLS anything queued (deep links
+ // that arrived before the window/subscription existed, incl. cold starts).
+ ipcMain.handle('hire:drainPending', () => {
+ rendererReadyForHires = true;
+ const out = pendingHires.splice(0, pendingHires.length);
+ return out;
+ });
+
+ // IPC: "import hire…" file picker in the Add-Agent modal.
+ ipcMain.handle('hire:openFile', async () => {
+ const res = await dialog.showOpenDialog({
+ title: 'Import a hire manifest',
+ filters: [{ name: 'Hire manifest', extensions: ['json'] }],
+ properties: ['openFile']
+ });
+ if (res.canceled || res.filePaths.length === 0) return { ok: false, error: 'cancelled' };
+ return readHireManifestFile(res.filePaths[0]);
+ });
+
-// IPC: paste-a-URL import (same pipeline as the deep link).
-ipcMain.handle('hire:fromUrl', async (_evt, src: string) => {
- if (typeof src !== 'string' || src.length > 2000) return { ok: false, error: 'not a valid URL' };
- return fetchHireManifest(src.trim());
-});
+/**
+ * Create a window. The PRIMARY window (no opts) restores saved geometry, uses
+ * the default session, runs the hive, and keeps the existing app-quit warning.
+ * A FLOOR window (`{ floor: true }`) gets its own persistent session partition
+ * — isolating its renderer state (agents/queues/selection) from every other
+ * window — cascades its position, and on close stops only its OWN terminals
+ * while the app keeps running.
+ */
+function createWindow(opts: { floor?: boolean } = {}): BrowserWindow {
+ const isFloor = opts.floor === true;
-function createWindow(): void {
- // Restore the last window geometry (kv), falling back to the default size.
+ // Primary restores saved geometry; floors cascade off the focused window.
let saved: WindowBounds | null = null;
- try { saved = clampBounds(persist.getKv('window.bounds')); } catch { saved = null; }
+ if (!isFloor) { try { saved = clampBounds(persist.getKv('window.bounds')); } catch { saved = null; } }
+ const cascade = isFloor ? floorCascade() : null;
+ const geom = cascade ?? saved;
const win = new BrowserWindow({
- width: saved?.width ?? DEFAULT_WIN.width,
- height: saved?.height ?? DEFAULT_WIN.height,
- ...(saved && saved.x !== undefined && saved.y !== undefined ? { x: saved.x, y: saved.y } : {}),
+ width: geom?.width ?? DEFAULT_WIN.width,
+ height: geom?.height ?? DEFAULT_WIN.height,
+ ...(geom && geom.x !== undefined && geom.y !== undefined ? { x: geom.x, y: geom.y } : {}),
minWidth: MIN_WIN.width,
minHeight: MIN_WIN.height,
- title: 'Munder Difflin',
+ title: isFloor ? 'Munder Difflin — Floor' : 'Munder Difflin',
backgroundColor: '#FFF8E7',
titleBarStyle: 'hiddenInset',
show: false,
@@@ -1279,12 -1261,19 +1368,20 @@@
if (count === 0) return;
e.preventDefault();
win.focus();
- win.webContents.send('app:closeRequested', { ptyCount: count });
+ wc.send('app:closeRequested', { ptyCount: count });
});
- ptyManager.attachWebContents(win.webContents);
+ // The primary is the default PTY sink; floors route purely by per-PTY owner.
+ if (!isFloor) ptyManager.attachWebContents(wc);
+ // A main-frame reload unmounts the renderer's hire subscription — queue again
+ // until the fresh renderer drains. Guard on isMainFrame: a stray sub-frame
+ // navigation must NOT flip readiness off (the renderer only drains on mount,
+ // so a later deep link would otherwise queue and sit until a full reload).
+ win.webContents.on('did-start-navigation', (details) => {
+ if (details.isMainFrame) rendererReadyForHires = false;
+ });
+
if (isDev && process.env.ELECTRON_RENDERER_URL) {
win.loadURL(process.env.ELECTRON_RENDERER_URL);
} else {
diff --cc src/preload/index.ts
index a91dcef6,5a1cd054..b4d06684
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@@ -1,769 -1,688 +1,794 @@@
-import { contextBridge, ipcRenderer, type IpcRendererEvent } from 'electron';
-import type { HireManifest } from '../shared/hire';
-export type { HireManifest } from '../shared/hire';
-import type { AgentProvider } from '../shared/agentProvider';
-
-// Injected at build time from package.json (see electron.vite.config.ts).
-declare const __APP_VERSION__: string;
-
-export interface HiveAgentMeta {
- id: string;
- name: string;
- /** Which CLI this agent runs on (claude/codex/antigravity/custom); defaults claude. */
- provider?: AgentProvider;
- role?: string;
- capabilities?: string[];
- cwd: string;
- isGod?: boolean;
- /** Michael's prep assistant — send-only; enriches prompts and forwards them. */
- isAssistant?: boolean;
-}
-
-export interface HiveMessage {
- id: string;
- conversation: string;
- in_reply_to: string | null;
- from: string;
- to: string;
- act: 'request' | 'inform' | 'propose' | 'query' | 'agree' | 'refuse' | 'done';
- subject: string;
- body: string;
- hops: number;
- requires_reply: boolean;
- needs_human: boolean;
- created_at: string;
-}
-
-export interface HiveRegistry {
- godId: string | null;
- /** `archived` agents have had their terminal closed — retained + flagged, not
- * deleted; only live-PTY agents are 'active'. */
- agents: Record<string, HiveAgentMeta & { status: string; lastSeen: number; archived?: boolean }>;
-}
-
-/** One question→answer exchange with the human, recorded ON the task card. */
-export interface HumanQA {
- q: string;
- a?: string;
- askedAt?: string;
- answeredAt?: string;
-}
-
-/** A card on the task kanban, persisted to hive/tasks.json. */
-export interface HiveTask {
- id: string;
- title: string;
- description?: string;
- assignee?: string;
- status: 'todo' | 'doing' | 'blocked' | 'done';
- dependsOn: string[];
- priority: number;
- createdAt: string;
- /** First-class human feedback: god appends {q}, the harness UI fills {a};
- * the full history stays on the card. */
- humanQA?: HumanQA[];
- /** Outcome summary used for the Slack done-notification. */
- result?: string;
- /** Origin thread for a Slack-sourced task (drives the done-summary reply). */
- slack?: { channel: string; thread_ts: string };
- /** SHA-256 of the capability token for a generic-webhook-sourced task (drives
- * the GET status lookup; the raw token is never persisted). */
- webhook?: { tokenHash: string };
-}
-
-/** A message the router just delivered, with its resolved recipient ids. Drives
- * the envelope-handoff animation on the office floor. `needsHuman` is set when
- * the sender aimed at "human" (now routed to the god proxy) — cosmetic tint
- * only; there is no approval queue. */
-export interface HiveRouteEvent {
- id: string;
- from: string;
- to: string;
- act: 'request' | 'inform' | 'propose' | 'query' | 'agree' | 'refuse' | 'done';
- subject: string;
- targets: string[];
- needsHuman: boolean;
-}
-
-/** A direct hive message addressed to a provider that cannot drain hive inbox.
- * The renderer turns this into a queued terminal work order for that agent. */
-export interface HiveTerminalHandoffEvent {
- id: string;
- from: string;
- to: string;
- act: 'request' | 'inform' | 'propose' | 'query' | 'agree' | 'refuse' | 'done';
- subject: string;
- body: string;
- requiresReply: boolean;
- createdAt: string;
-}
-
-export interface SpawnPtyOptions {
- id: string;
- cwd: string;
- command: string;
- /** Which CLI to spawn; usually inferred from `command` in the main process. */
- provider?: AgentProvider;
- args?: string[];
- cols?: number;
- rows?: number;
- /** When present, the agent is provisioned in the hive at spawn. */
- hive?: HiveAgentMeta;
- /** When true (and cwd is a git repo), spawn the agent in its own git worktree. */
- isolate?: boolean;
- /** When true, continue the agent's prior CLI session if one was recorded
- * (provider-aware: Claude `--resume`, Antigravity `--conversation`). */
- resume?: boolean;
-}
-
-export interface PtyExit { exitCode: number; signal?: number | undefined }
-
-/** A recurring auto-dispatched mission fired on an interval by the scheduler. */
-export interface ScheduledMission {
- id: string;
- label: string;
- intervalMs: number;
- to: string;
- body: string;
- enabled: boolean;
- autoCompact?: boolean;
- lastFiredAt?: number;
- /** Mission flavor; 'heartbeat' (Lane A #1) is a context-aware adaptive beat. */
- kind?: 'dispatch' | 'heartbeat';
- /** Heartbeat only: floor-quiet threshold in ms. */
- quietThresholdMs?: number;
-}
-
-/** Circuit-breaker thresholds (Lane A #6.6b). Mirrors src/main/config.ts. */
-export interface CircuitBreakerConfig {
- enabled?: boolean;
- hardStop?: boolean;
- repeatedToolLimit?: number;
- errorStormLimit?: number;
- tokenVelocityPerMin?: number;
-}
-
-export interface HarnessConfig {
- onboardingComplete: boolean;
- harnessHome: string | null;
- registeredRepos: string[];
- autoMode: boolean;
- defaultCommand: string;
- defaultModel?: string;
- semanticMemory: boolean;
- embeddingModel: 'minilm' | 'embeddinggemma';
- missions?: ScheduledMission[];
- opsStandupSeeded?: boolean;
- heartbeatSeeded?: boolean;
- notifications?: boolean;
- slackEnabled?: boolean;
- slackSigningSecret?: string;
- slackBotToken?: string;
- slackChannelId?: string;
- slackPort?: number;
- webhookEnabled?: boolean;
- webhookSecret?: string;
- webhookPort?: number;
- costCapUsd?: number;
- costCapTokens?: number;
- agentTokenCaps?: Record<string, number>;
- maxTurns?: number;
- circuitBreaker?: CircuitBreakerConfig;
- /** Terminal theme, mirrored into each agent's per-session Claude settings. */
- terminalTheme?: 'light' | 'dark';
-}
-
-export interface MemoryStatus {
- available: boolean;
- enabled: boolean;
- active: boolean;
- initialized: boolean;
- palacePath: string | null;
- model: 'minilm' | 'embeddinggemma';
- bin: string | null;
-}
-
-export interface DirEntry {
- name: string;
- isDir: boolean;
- size: number;
- mtime: number;
-}
-
-export interface GitCommit {
- sha: string;
- shortSha: string;
- parents: string[];
- subject: string;
- author: string;
- time: number;
- refs: string[];
-}
-export interface GitStatusEntry { path: string; index: string; worktree: string }
-export interface GitStatus { staged: GitStatusEntry[]; unstaged: GitStatusEntry[]; untracked: string[] }
-
-/** Real token usage + estimated USD cost summed from an agent's Claude Code
- * transcripts under ~/.claude/projects. Reconciler/fallback path — now priced
- * PER MODEL (not Sonnet-for-everyone). The live path uses AgentUsageSample. */
-export interface AgentUsage {
- inputTokens: number;
- outputTokens: number;
- cacheReadTokens: number;
- cacheWriteTokens: number;
- estimatedCostUsd: number;
- /** Most-recently-seen model id (normalized), if any priced record was found. */
- model?: string;
-}
-
-/** Live cumulative cost/token snapshot from the OTel collector (the locked
- * cross-lane seam). PII-free by construction. Mirrors telemetry.ts. */
-export interface AgentUsageSample {
- agentId: string;
- sessionId: string;
- ts: number;
- input: number;
- output: number;
- cacheRead: number;
- cacheCreation: number;
- model: string;
- usd: number;
-}
-
-/** One tool invocation for the per-agent span waterfall (#7B.2). Ephemeral. */
-export interface ToolSpan {
- agentId: string;
- sessionId: string;
- ts: number;
- tool: string;
- success: boolean;
- durationMs: number;
- decision?: 'accept' | 'reject';
- error?: string;
-}
-
-/** Closing-time progress event (mirrors src/main/closingTime.ts). */
-export interface ClosingTimeEvent {
- phase: 'started' | 'progress' | 'complete' | 'timeout' | 'cancelled';
- /** Workers that have ACKed so far / total workers being waited on. */
- acked: number;
- total: number;
-}
-
-/** Per-agent operator-control state (#7C.1–7C.3). */
-export interface AgentControlSnapshot {
- paused: boolean;
- halted: boolean;
- gatedTools: string[];
- pendingSteers: number;
-}
-
-/** Circuit-breaker state (Lane A #6 → this lane's avatars/meter). */
-export interface BreakerState {
- agentId: string;
- level: 'healthy' | 'steering' | 'constrained' | 'stopped';
- reason: string;
- ts: number;
-}
-
-/** Live telemetry push payload (channel `telemetry:event`). */
-export type TelemetryEvent =
- | { kind: 'usage'; sample: AgentUsageSample }
- | { kind: 'tool_result'; span: ToolSpan }
- | { kind: 'api_error'; agentId: string; sessionId: string; ts: number; error: string };
-
-/** Cold-start backfill from the collector. */
-export interface TelemetrySnapshot {
- usage: AgentUsageSample[];
- spans: Record<string, ToolSpan[]>;
-}
-
-/** One captured user prompt from the SQLite command_history table. */
-export interface CommandHistoryEntry {
- id: number;
- agentId: string;
- cwd: string | null;
- text: string;
- ts: number;
-}
-
-/** A GitHub issue, normalized for the renderer (labels/assignees flattened to names). */
-export interface GHIssue {
- number: number;
- title: string;
- body: string;
- url: string;
- labels: string[];
- assignees: string[];
-}
-
-/** A CI (GitHub Actions) workflow run, normalized for the renderer. */
-export interface CIRun {
- name: string;
- status: string;
- conclusion: string | null;
- url: string;
-}
-
-const api = {
- version: __APP_VERSION__,
-
- // ─── PTY ─────────────────────────────────────────────────────────────────
- spawnPty: (opts: SpawnPtyOptions): Promise<{ ok: boolean; error?: string }> =>
- ipcRenderer.invoke('pty:spawn', opts),
- writePty: (id: string, data: string): Promise<{ ok: boolean; error?: string }> =>
- ipcRenderer.invoke('pty:write', id, data),
- resizePty: (id: string, cols: number, rows: number): Promise<{ ok: boolean; error?: string }> =>
- ipcRenderer.invoke('pty:resize', id, cols, rows),
- killPty: (id: string): Promise<{ ok: boolean; error?: string }> =>
- ipcRenderer.invoke('pty:kill', id),
- listPtys: (): Promise<Array<{ id: string; cwd: string; command: string; pid: number }>> =>
- ipcRenderer.invoke('pty:list'),
- onPtyData: (id: string, cb: (data: string) => void): (() => void) => {
- const channel = `pty:data:${id}`;
- const listener = (_e: IpcRendererEvent, data: string) => cb(data);
- ipcRenderer.on(channel, listener);
- return () => ipcRenderer.removeListener(channel, listener);
- },
- onPtyExit: (id: string, cb: (info: PtyExit) => void): (() => void) => {
- const channel = `pty:exit:${id}`;
- const listener = (_e: IpcRendererEvent, info: PtyExit) => cb(info);
- ipcRenderer.on(channel, listener);
- return () => ipcRenderer.removeListener(channel, listener);
- },
-
- // ─── Dialog ──────────────────────────────────────────────────────────────
- chooseFolder: (): Promise<{ ok: true; path: string } | { ok: false; error: string }> =>
- ipcRenderer.invoke('dialog:chooseFolder'),
-
- // ─── Terminal.app ────────────────────────────────────────────────────────
- openTerminalAt: (cwd: string): Promise<{ ok: boolean; error?: string }> =>
- ipcRenderer.invoke('terminal:openAtFolder', cwd),
-
- // ─── Clipboard ─────────────────────────────────────────────────────────────
- copyToClipboard: (text: string): Promise<{ ok: boolean; error?: string }> =>
- ipcRenderer.invoke('app:copyToClipboard', text),
- /** Read the system clipboard as plain text ('' when empty/unreadable). */
- readClipboard: (): Promise<string> =>
- ipcRenderer.invoke('app:readClipboard'),
-
- // ─── Config ──────────────────────────────────────────────────────────────
- getConfig: (): Promise<HarnessConfig> =>
- ipcRenderer.invoke('config:get'),
- updateConfig: (patch: Partial<HarnessConfig>): Promise<HarnessConfig> =>
- ipcRenderer.invoke('config:update', patch),
- ensureHarnessHome: (path: string): Promise<{ ok: boolean; error?: string }> =>
- ipcRenderer.invoke('config:ensureHome', path),
- /** Change the harness home folder. 'move' copies the existing hive + palace
- * into the new folder (old kept as a safety net); 'fresh' just re-points and
- * bootstraps an empty home. On success the app relaunches (never resolves);
- * on failure (e.g. copy error) returns { ok: false, error }. */
- changeHome: (newHome: string, mode: 'move' | 'fresh'): Promise<{ ok: boolean; error?: string }> =>
- ipcRenderer.invoke('config:changeHome', { newHome, mode }),
-
- // ─── Filesystem (sandboxed to cwd) ───────────────────────────────────────
- listDir: (root: string, rel: string): Promise<
- { ok: true; entries: DirEntry[]; path: string } | { ok: false; error: string }
- > => ipcRenderer.invoke('fs:listDir', root, rel),
- readFile: (root: string, rel: string): Promise<
- { ok: true; content: string; path: string; size: number } | { ok: false; error: string }
- > => ipcRenderer.invoke('fs:readFile', root, rel),
- writeFile: (root: string, rel: string, content: string): Promise<
- { ok: true; path: string } | { ok: false; error: string }
- > => ipcRenderer.invoke('fs:writeFile', root, rel, content),
-
- // ─── Git ─────────────────────────────────────────────────────────────────
- gitIsRepo: (cwd: string): Promise<boolean> => ipcRenderer.invoke('git:isRepo', cwd),
- gitBranch: (cwd: string) =>
- ipcRenderer.invoke('git:branch', cwd) as Promise<{ current: string | null; detached: boolean } | { error: string }>,
- gitStatus: (cwd: string) =>
- ipcRenderer.invoke('git:status', cwd) as Promise<GitStatus | { error: string }>,
- gitLog: (cwd: string, n?: number) =>
- ipcRenderer.invoke('git:log', cwd, n ?? 50) as Promise<GitCommit[] | { error: string }>,
- gitBranches: (cwd: string) =>
- ipcRenderer.invoke('git:branches', cwd) as Promise<{ local: string[]; remote: string[]; current: string | null } | { error: string }>,
- gitAheadBehind: (cwd: string) =>
- ipcRenderer.invoke('git:aheadBehind', cwd) as Promise<{ ahead: number; behind: number; upstream: string | null } | { error: string }>,
-
- // ─── Hive (multi-agent coordination) ─────────────────────────────────────
- hiveRegistry: (): Promise<HiveRegistry> => ipcRenderer.invoke('hive:registry'),
- hiveBoard: (): Promise<string> => ipcRenderer.invoke('hive:board'),
- hiveTasks: (): Promise<unknown> => ipcRenderer.invoke('hive:tasks'),
- hiveLog: (n?: number): Promise<unknown[]> => ipcRenderer.invoke('hive:log', n ?? 200),
- hiveMemory: (id: string): Promise<string> => ipcRenderer.invoke('hive:memory', id),
- hiveInbox: (id: string): Promise<HiveMessage[]> => ipcRenderer.invoke('hive:inbox', id),
-
- // ─── Semantic memory (MemPalace CLI) ─────────────────────────────────────
- memoryStatus: (): Promise<MemoryStatus> => ipcRenderer.invoke('hive:memoryStatus'),
- searchMemory: (query: string, wing?: string): Promise<{ ok: boolean; output: string; error?: string }> =>
- ipcRenderer.invoke('hive:searchMemory', query, wing),
- memoryWakeUp: (wing?: string): Promise<{ ok: boolean; output: string; error?: string }> =>
- ipcRenderer.invoke('hive:memoryWakeUp', wing),
- mineNow: (): Promise<{ ok: boolean }> => ipcRenderer.invoke('hive:mineNow'),
- /** Condense agent memory.md files (the janitor's missing half). With an id,
- * condense that agent on demand; without, run a full threshold scan. Returns
- * the per-agent outcomes ({ id, condensed, reason, oldBytes?, newBytes? }). */
- reflectNow: (id?: string): Promise<Array<{ id: string; condensed: boolean; reason: string; oldBytes?: number; newBytes?: number }>> =>
- ipcRenderer.invoke('memory:reflectNow', id),
-
- // ─── Command history (SQLite — every prompt submitted to an agent) ─────────
- /** Record one submitted prompt. Fire-and-forget from the prompt-detection hook. */
- historyAdd: (entry: { agentId: string; cwd?: string; text: string }): Promise<{ ok: boolean; error?: string }> =>
- ipcRenderer.invoke('history:add', entry),
- /** Most-recent-first history, optionally scoped to one agent. */
- historyList: (agentId?: string, limit?: number): Promise<CommandHistoryEntry[]> =>
- ipcRenderer.invoke('history:list', agentId, limit),
- /** Substring search over prompt text, most-recent-first. */
- historySearch: (query: string, limit?: number): Promise<CommandHistoryEntry[]> =>
- ipcRenderer.invoke('history:search', query, limit),
- hiveSend: (msg: Partial<HiveMessage>, from?: string): Promise<{ ok: boolean; error?: string; message?: HiveMessage }> =>
- ipcRenderer.invoke('hive:send', msg, from),
-
- onHiveHookEvent: (
- cb: (e: { agentId?: string; event: string; tool?: string; notificationType?: string; source?: string; message?: string; blocked?: boolean }) => void
- ): (() => void) => {
- const listener = (_e: IpcRendererEvent, payload: { agentId?: string; event: string; tool?: string; notificationType?: string; source?: string; message?: string; blocked?: boolean }) => cb(payload);
- ipcRenderer.on('hive:hookEvent', listener);
- return () => ipcRenderer.removeListener('hive:hookEvent', listener);
- },
- /** Push-based context accounting from the status line: live tokens + the
- * session's EXACT context-window size. Same pattern as onHiveHookEvent. */
- onHiveContextUpdate: (
- cb: (e: { agentId: string; tokens: number; limit: number }) => void
- ): (() => void) => {
- const listener = (_e: IpcRendererEvent, payload: { agentId: string; tokens: number; limit: number }) => cb(payload);
- ipcRenderer.on('hive:contextUpdate', listener);
- return () => ipcRenderer.removeListener('hive:contextUpdate', listener);
- },
- onHiveMessage: (cb: (e: HiveRouteEvent) => void): (() => void) => {
- const listener = (_e: IpcRendererEvent, payload: HiveRouteEvent) => cb(payload);
- ipcRenderer.on('hive:message', listener);
- return () => ipcRenderer.removeListener('hive:message', listener);
- },
- /** Register a listener for hive tasks routed to non-Claude agents (e.g.
- * Codex). Main emits this instead of bouncing; the renderer enqueues the
- * raw text so the drain effect types it into the agent's REPL when idle. */
- onHiveEnqueue: (cb: (e: { targetId: string; text: string }) => void): (() => void) => {
- const listener = (_e: IpcRendererEvent, payload: { targetId: string; text: string }) => cb(payload);
- ipcRenderer.on('hive:enqueueToAgent', listener);
- return () => ipcRenderer.removeListener('hive:enqueueToAgent', listener);
- },
- /** Register a listener for terminal work-order handoffs (#53) — hive mail to a
- * hookless provider that can't drain an inbox; the renderer types it into the
- * agent's REPL as a work order. */
- onHiveTerminalHandoff: (cb: (e: HiveTerminalHandoffEvent) => void): (() => void) => {
- const listener = (_e: IpcRendererEvent, payload: HiveTerminalHandoffEvent) => cb(payload);
- ipcRenderer.on('hive:terminalHandoff', listener);
- return () => ipcRenderer.removeListener('hive:terminalHandoff', listener);
- },
-
- // ─── Quit confirmation ───────────────────────────────────────────────────
- // ─── Shareable hires (deep link / file / URL import) ──────────────────────
- /** Fired when a validated hire manifest arrives via the munderdifflin://
- * deep link. The renderer opens the Add-Agent modal pre-filled — import
- * never spawns anything by itself. */
- onHireImport: (cb: (manifest: HireManifest) => void): (() => void) => {
- const listener = (_e: IpcRendererEvent, manifest: HireManifest) => cb(manifest);
- ipcRenderer.on('hire:import', listener);
- return () => ipcRenderer.removeListener('hire:import', listener);
- },
- /** Fired when a deep-linked manifest failed validation/fetch. */
- onHireError: (cb: (info: { error: string }) => void): (() => void) => {
- const listener = (_e: IpcRendererEvent, info: { error: string }) => cb(info);
- ipcRenderer.on('hire:error', listener);
- return () => ipcRenderer.removeListener('hire:error', listener);
- },
- /** Signal readiness and pull any queued deep-linked manifests (cold-start
- * links, links that arrived during load). Resolves the queued list. */
- drainPendingHires: (): Promise<HireManifest[]> =>
- ipcRenderer.invoke('hire:drainPending'),
- /** Open a file picker and validate the chosen hire-manifest JSON. */
- importHireFile: (): Promise<{ ok: boolean; manifest?: HireManifest; error?: string }> =>
- ipcRenderer.invoke('hire:openFile'),
- /** Fetch + validate a hire manifest from a pasted https URL. */
- importHireUrl: (src: string): Promise<{ ok: boolean; manifest?: HireManifest; error?: string }> =>
- ipcRenderer.invoke('hire:fromUrl', src),
-
- onCloseRequested: (cb: (info: { ptyCount: number }) => void): (() => void) => {
- const listener = (_e: IpcRendererEvent, info: { ptyCount: number }) => cb(info);
- ipcRenderer.on('app:closeRequested', listener);
- return () => ipcRenderer.removeListener('app:closeRequested', listener);
- },
- confirmClose: (): Promise<void> => ipcRenderer.invoke('app:confirmClose'),
- cancelClose: (): Promise<void> => ipcRenderer.invoke('app:cancelClose'),
-
- // ─── Closing time (graceful shutdown via the hive) ─────────────────────────
- /** Start the closing-time protocol: the god broadcasts shutdown, every worker
- * saves its memory and ACKs, the god concludes — then the app quits itself.
- * Resolves with ok:false (+ error) when no god agent is running. */
- startClosingTime: (): Promise<{ ok: boolean; error?: string }> =>
- ipcRenderer.invoke('app:startClosingTime'),
- /** Abort an in-progress closing time and tell the floor to resume work. */
- cancelClosingTime: (): Promise<void> => ipcRenderer.invoke('app:cancelClosingTime'),
- /** Progress events for the quit dialog: started → progress (ACK counts) →
- * complete (the app tears down moments later) | timeout | cancelled. */
- onClosingTime: (cb: (ev: ClosingTimeEvent) => void): (() => void) => {
- const listener = (_e: IpcRendererEvent, ev: ClosingTimeEvent) => cb(ev);
- ipcRenderer.on('app:closingTime', listener);
- return () => ipcRenderer.removeListener('app:closingTime', listener);
- },
-
- // ─── Reset ─────────────────────────────────────────────────────────────────
- /** Wipe all hive data + the memory palace, reset config, and relaunch the app
- * into onboarding. The process exits, so this promise never resolves. */
- resetAll: (): Promise<void> => ipcRenderer.invoke('app:resetAll'),
-
- // ─── Token telemetry (real usage + est. cost from CC transcripts) ──────────
- /** Sum input/output/cache tokens + estimated USD cost for an agent from its
- * Claude Code transcripts (reconciler/fallback). Returns null for an invalid cwd. */
- agentUsage: (cwd: string): Promise<AgentUsage | null> =>
- ipcRenderer.invoke('hive:agentUsage', cwd),
- /** Current context size (tokens) of an agent's live session, read from the
- * last assistant message of its transcript. Null until the agent's hooks
- * have fired at least once (the transcript path is learned from them). */
- agentContext: (agentId: string): Promise<number | null> =>
- ipcRenderer.invoke('hive:agentContext', agentId),
-
- // ─── Live telemetry (OTel collector — the usage-provider seam + spans) ──────
- /** Live cumulative usage for an agent (OTel-preferred, transcript fallback). */
- telemetryUsage: (agentId: string): Promise<AgentUsageSample | null> =>
- ipcRenderer.invoke('telemetry:usage', agentId),
- /** Recent tool spans for an agent's waterfall (#7B.2). */
- telemetrySpans: (agentId: string): Promise<ToolSpan[]> =>
- ipcRenderer.invoke('telemetry:spans', agentId),
- /** Cold-start backfill of all agents' usage + recent spans. */
- telemetrySnapshot: (): Promise<TelemetrySnapshot> =>
- ipcRenderer.invoke('telemetry:snapshot'),
- /** Subscribe to live telemetry pushes; returns an unsubscribe fn. */
- onTelemetryEvent: (cb: (e: TelemetryEvent) => void): (() => void) => {
- const listener = (_e: IpcRendererEvent, payload: TelemetryEvent) => cb(payload);
- ipcRenderer.on('telemetry:event', listener);
- return () => ipcRenderer.removeListener('telemetry:event', listener);
- },
-
- // ─── Circuit breaker (Lane A #6 state → avatars/meter) ──────────────────────
- /** Subscribe to breaker-state changes; returns an unsubscribe fn. */
- onBreakerState: (cb: (s: BreakerState) => void): (() => void) => {
- const listener = (_e: IpcRendererEvent, payload: BreakerState) => cb(payload);
- ipcRenderer.on('control:breakerState', listener);
- return () => ipcRenderer.removeListener('control:breakerState', listener);
- },
- /** Push a breaker state to the renderer (Lane A's policy / interim glue calls this). */
- setBreakerState: (state: BreakerState): Promise<{ ok: boolean }> =>
- ipcRenderer.invoke('control:setBreakerState', state),
-
- // ─── Operator control over agents (#7C.1–7C.3) ──────────────────────────────
- /** Pause/unpause an agent — paused → its tool calls are denied at PreToolUse. */
- controlPause: (agentId: string, on: boolean): Promise<AgentControlSnapshot | null> =>
- ipcRenderer.invoke('control:pause', agentId, on),
- /** Clear pause + halt so the agent can run again. */
- controlResume: (agentId: string): Promise<AgentControlSnapshot | null> =>
- ipcRenderer.invoke('control:resume', agentId),
- /** Gate/ungate a specific tool for an agent (denied at PreToolUse). */
- controlGateTool: (agentId: string, tool: string, on: boolean): Promise<AgentControlSnapshot | null> =>
- ipcRenderer.invoke('control:gateTool', agentId, tool, on),
- /** Queue a steer note — injected as context on the agent's next hook (#7C.2). */
- controlSteer: (agentId: string, text: string): Promise<AgentControlSnapshot | null> =>
- ipcRenderer.invoke('control:steer', agentId, text),
- /** Request a graceful stop at the next hook boundary (#7C.3). */
- controlHalt: (agentId: string): Promise<AgentControlSnapshot | null> =>
- ipcRenderer.invoke('control:halt', agentId),
- /** Read an agent's current control snapshot. */
- controlSnapshot: (agentId: string): Promise<AgentControlSnapshot | null> =>
- ipcRenderer.invoke('control:snapshot', agentId),
- /** Subscribe to gate/deny events (a tool was blocked); returns unsubscribe fn. */
- onApprovalRequest: (cb: (e: { agentId: string; tool?: string; reason?: string }) => void): (() => void) => {
- const listener = (_e: IpcRendererEvent, payload: { agentId: string; tool?: string; reason?: string }) => cb(payload);
- ipcRenderer.on('control:approvalRequest', listener);
- return () => ipcRenderer.removeListener('control:approvalRequest', listener);
- },
-
- // ─── Task kanban (hive/tasks.json) ───────────────────────────────────────
- /** Overwrite the hive task ledger with the full task list and commit it. */
- hiveWriteTasks: (tasks: HiveTask[]): Promise<{ ok: boolean; error?: string }> =>
- ipcRenderer.invoke('hive:writeTasks', tasks),
-
- // ─── Scheduled missions (recurring auto-dispatch) ──────────────────────────
- listMissions: (): Promise<ScheduledMission[]> => ipcRenderer.invoke('missions:list'),
- saveMissions: (missions: ScheduledMission[]): Promise<{ ok: boolean }> =>
- ipcRenderer.invoke('missions:save', missions),
- /** Fires when the scheduler stamps a mission's lastFiredAt (a beat/dispatch),
- * so the SCHEDULES panel can refresh "last fired" without a reload. */
- onMissionsUpdated: (cb: () => void): (() => void) => {
- const listener = (): void => cb();
- ipcRenderer.on('missions:updated', listener);
- return () => ipcRenderer.removeListener('missions:updated', listener);
- },
- /** Fires when an autoCompact mission ticks — the renderer queues a /compact
- * per agent (deduped) and delivers it when each agent is idle. */
- onAutoCompact: (cb: () => void): (() => void) => {
- const listener = (): void => cb();
- ipcRenderer.on('mission:autoCompact', listener);
- return () => ipcRenderer.removeListener('mission:autoCompact', listener);
- },
-
- // ─── Full-text search across hive files (board, tasks, memory) ─────────────
- textSearch: (q: string): Promise<{ ok: boolean; results: Array<{ source: string; excerpt: string }> }> =>
- ipcRenderer.invoke('hive:textSearch', q),
-
- // ─── GitHub issue ingestion (gh CLI) ───────────────────────────────────────
- /** List up to 30 open issues in the repo at `cwd` via the `gh` CLI. Returns
- * `{ ok: false, error }` if `gh` is missing/unauthenticated or `cwd` isn't a repo. */
- githubIssues: (cwd: string): Promise<{ ok: boolean; issues?: GHIssue[]; error?: string }> =>
- ipcRenderer.invoke('github:issues', cwd),
-
- // ─── GitHub CI status watcher (gh CLI) ─────────────────────────────────────
- /** List up to 5 recent CI (GitHub Actions) runs in the repo at `cwd` via the
- * `gh` CLI. Returns `{ ok: false, error }` if `gh` is missing/unauthenticated,
- * `cwd` isn't a repo, or the repo has no Actions. */
- githubCIRuns: (cwd: string): Promise<{ ok: boolean; runs?: CIRun[]; error?: string }> =>
- ipcRenderer.invoke('github:ciRuns', cwd),
-
- // ─── Desktop notifications ───────────────────────────────────────────────────
- /** Toggle native desktop notifications for agent lifecycle events. */
- setNotifications: (v: boolean): Promise<HarnessConfig> =>
- ipcRenderer.invoke('app:setNotifications', v),
-
- // ─── Agent lifecycle (archival) ─────────────────────────────────────────────
- /** Archive/unarchive a hive agent in the registry. Closing a terminal tab
- * archives it automatically via pty:kill; this is the explicit primitive. */
- hiveSetArchived: (id: string, archived: boolean): Promise<{ ok: boolean; error?: string }> =>
- ipcRenderer.invoke('hive:setArchived', id, archived),
-
- // ─── Slack integration (Slack message → Michael's queue) ─────────────────────
- /** Register a listener for inbound Slack messages; returns an unsubscribe fn.
- * The message carries the thread coordinates needed to reply in-thread. */
- onSlackMessage: (cb: (msg: { text: string; channel: string; ts: string; thread_ts: string; autonomyPreamble?: string; files?: { path: string; name: string; mimetype: string }[] }) => void): (() => void) => {
- const listener = (_e: IpcRendererEvent, msg: { text: string; channel: string; ts: string; thread_ts: string; autonomyPreamble?: string; files?: { path: string; name: string; mimetype: string }[] }) => cb(msg);
- ipcRenderer.on('slack:incomingMessage', listener);
- return () => ipcRenderer.removeListener('slack:incomingMessage', listener);
- },
- /** Start the Slack webhook server; returns the public tunnel URL to paste into
- * the Slack app's Event Subscriptions → Request URL. */
- slackStart: (): Promise<{ ok: boolean; url?: string; error?: string }> =>
- ipcRenderer.invoke('slack:start'),
- /** Stop the Slack webhook server + tunnel. */
- slackStop: (): Promise<{ ok: boolean }> =>
- ipcRenderer.invoke('slack:stop'),
- /** Current connection state + last Request URL (so Settings can hydrate the
- * "Connected" badge and re-show the persisted tunnel URL on reopen). */
- slackStatus: (): Promise<{ running: boolean; url?: string }> =>
- ipcRenderer.invoke('slack:status'),
- /** Post a reply into a Slack thread (the bot token stays in main). Used for the
- * renderer's immediate "queued" ack. */
- slackReply: (m: { channel: string; thread_ts: string; text: string }): Promise<{ ok: boolean; error?: string }> =>
- ipcRenderer.invoke('slack:reply', m),
- /** Absolute path to the bundled reply helper, for the office worker's
- * end-of-run "post your summary back to Slack" instruction. */
- slackReplyScriptPath: (): Promise<string> =>
- ipcRenderer.invoke('slack:replyScriptPath'),
- /** Persist Slack settings (and stop the server if disabled / secret cleared). */
- slackSetConfig: (patch: {
- signingSecret?: string; botToken?: string; channelId?: string; port?: number; enabled?: boolean;
- }): Promise<{ ok: boolean }> =>
- ipcRenderer.invoke('slack:setConfig', patch),
-
- // ─── Generic webhook + status API (POST → work, GET → status) ────────────────
- /** Start the generic webhook server; returns the public endpoint URL callers
- * POST to (secret-gated) and GET a token's status from. */
- webhookStart: (): Promise<{ ok: boolean; url?: string; error?: string }> =>
- ipcRenderer.invoke('webhook:start'),
- /** Stop the generic webhook server + tunnel. */
- webhookStop: (): Promise<{ ok: boolean }> =>
- ipcRenderer.invoke('webhook:stop'),
- /** Current state + last endpoint URL (so Settings can hydrate the badge/URL). */
- webhookStatus: (): Promise<{ running: boolean; url?: string }> =>
- ipcRenderer.invoke('webhook:status'),
- /** Mint + persist a fresh secret and return it for the user to copy. */
- webhookGenerateSecret: (): Promise<{ ok: boolean; secret?: string }> =>
- ipcRenderer.invoke('webhook:generateSecret'),
- /** Persist webhook settings (and stop the server if disabled / secret cleared). */
- webhookSetConfig: (patch: {
- secret?: string; port?: number; enabled?: boolean;
- }): Promise<{ ok: boolean }> =>
- ipcRenderer.invoke('webhook:setConfig', patch)
-};
-
-contextBridge.exposeInMainWorld('cth', api);
-
-export type CthApi = typeof api;
+import { contextBridge, ipcRenderer, webUtils, type IpcRendererEvent } from 'electron';
+import type { AgentProvider } from '../shared/agentProvider';
++import type { HireManifest } from '../shared/hire';
++export type { HireManifest } from '../shared/hire';
+
+// Injected at build time from package.json (see electron.vite.config.ts).
+declare const __APP_VERSION__: string;
+
+export interface HiveAgentMeta {
+ id: string;
+ name: string;
+ /** Which CLI this agent runs on (claude/codex/antigravity/custom); defaults claude. */
+ provider?: AgentProvider;
+ role?: string;
+ capabilities?: string[];
+ cwd: string;
+ isGod?: boolean;
+ /** Michael's prep assistant — send-only; enriches prompts and forwards them. */
+ isAssistant?: boolean;
+}
+
+export interface HiveMessage {
+ id: string;
+ conversation: string;
+ in_reply_to: string | null;
+ from: string;
+ to: string;
+ act: 'request' | 'inform' | 'propose' | 'query' | 'agree' | 'refuse' | 'done';
+ subject: string;
+ body: string;
+ hops: number;
+ requires_reply: boolean;
+ needs_human: boolean;
+ created_at: string;
+}
+
+export interface HiveRegistry {
+ godId: string | null;
+ /** `archived` agents have had their terminal closed — retained + flagged, not
+ * deleted; only live-PTY agents are 'active'. */
+ agents: Record<string, HiveAgentMeta & { status: string; lastSeen: number; archived?: boolean }>;
+}
+
+/** One question→answer exchange with the human, recorded ON the task card. */
+export interface HumanQA {
+ q: string;
+ a?: string;
+ askedAt?: string;
+ answeredAt?: string;
+}
+
+/** A card on the task kanban, persisted to hive/tasks.json. */
+export interface HiveTask {
+ id: string;
+ title: string;
+ description?: string;
+ assignee?: string;
+ status: 'todo' | 'doing' | 'blocked' | 'done';
+ dependsOn: string[];
+ priority: number;
+ createdAt: string;
+ /** First-class human feedback: god appends {q}, the harness UI fills {a};
+ * the full history stays on the card. */
+ humanQA?: HumanQA[];
+ /** Outcome summary used for the Slack done-notification. */
+ result?: string;
+ /** Origin thread for a Slack-sourced task (drives the done-summary reply). */
+ slack?: { channel: string; thread_ts: string };
+ /** SHA-256 of the capability token for a generic-webhook-sourced task (drives
+ * the GET status lookup; the raw token is never persisted). */
+ webhook?: { tokenHash: string };
+}
+
+/** A message the router just delivered, with its resolved recipient ids. Drives
+ * the envelope-handoff animation on the office floor. `needsHuman` is set when
+ * the sender aimed at "human" (now routed to the god proxy) — cosmetic tint
+ * only; there is no approval queue. */
+export interface HiveRouteEvent {
+ id: string;
+ from: string;
+ to: string;
+ act: 'request' | 'inform' | 'propose' | 'query' | 'agree' | 'refuse' | 'done';
+ subject: string;
+ targets: string[];
+ needsHuman: boolean;
+}
+
+/** A direct hive message addressed to a provider that cannot drain hive inbox.
+ * The renderer turns this into a queued terminal work order for that agent. */
+export interface HiveTerminalHandoffEvent {
+ id: string;
+ from: string;
+ to: string;
+ act: 'request' | 'inform' | 'propose' | 'query' | 'agree' | 'refuse' | 'done';
+ subject: string;
+ body: string;
+ requiresReply: boolean;
+ createdAt: string;
+}
+
+export interface SpawnPtyOptions {
+ id: string;
+ cwd: string;
+ command: string;
+ /** Which CLI to spawn; usually inferred from `command` in the main process. */
+ provider?: AgentProvider;
+ args?: string[];
+ cols?: number;
+ rows?: number;
+ /** When present, the agent is provisioned in the hive at spawn. */
+ hive?: HiveAgentMeta;
+ /** When true (and cwd is a git repo), spawn the agent in its own git worktree. */
+ isolate?: boolean;
+ /** When true, continue the agent's prior CLI session if one was recorded
+ * (provider-aware: Claude `--resume`, Antigravity `--conversation`). For
+ * Claude the main process looks up the session id from the hive registry and
+ * seeds its transcript into the cwd's project dir (#1 — restore on restart). */
+ resume?: boolean;
+ /** Explicit Claude session id to resume (#2 — Add Agent "resume session"). The
+ * main process seeds that session's `.jsonl` into the target cwd's project dir
+ * (copying it from wherever it lives) and launches `claude --resume <id>`. */
+ resumeSessionId?: string;
+}
+
+export interface PtyExit { exitCode: number; signal?: number | undefined }
+
+/** A recurring auto-dispatched mission fired on an interval by the scheduler. */
+export interface ScheduledMission {
+ id: string;
+ label: string;
+ intervalMs: number;
+ to: string;
+ body: string;
+ enabled: boolean;
+ autoCompact?: boolean;
+ lastFiredAt?: number;
+ /** Mission flavor; 'heartbeat' (Lane A #1) is a context-aware adaptive beat. */
+ kind?: 'dispatch' | 'heartbeat';
+ /** Heartbeat only: floor-quiet threshold in ms. */
+ quietThresholdMs?: number;
+}
+
+/** Circuit-breaker thresholds (Lane A #6.6b). Mirrors src/main/config.ts. */
+export interface KnowledgeGraphConfig {
+ enabled?: boolean;
+ rootPath?: string;
+}
+
+export interface CircuitBreakerConfig {
+ enabled?: boolean;
+ hardStop?: boolean;
+ repeatedToolLimit?: number;
+ errorStormLimit?: number;
+ tokenVelocityPerMin?: number;
+}
+
+export interface HarnessConfig {
+ onboardingComplete: boolean;
+ harnessHome: string | null;
+ registeredRepos: string[];
+ autoMode: boolean;
+ defaultCommand: string;
+ defaultModel?: string;
+ semanticMemory: boolean;
+ embeddingModel: 'minilm' | 'embeddinggemma';
+ missions?: ScheduledMission[];
+ opsStandupSeeded?: boolean;
+ heartbeatSeeded?: boolean;
+ notifications?: boolean;
+ slackEnabled?: boolean;
+ slackSigningSecret?: string;
+ slackBotToken?: string;
+ slackChannelId?: string;
+ slackPort?: number;
+ webhookEnabled?: boolean;
+ webhookSecret?: string;
+ webhookPort?: number;
+ /** Free Flow voice dictation — master flag (default off), user Groq key, model.
+ * Entry point B (hold-Option-to-talk) is handled in the renderer, no hotkey. */
+ freeflowEnabled?: boolean;
+ groqApiKey?: string;
+ freeflowModel?: string;
+ costCapUsd?: number;
+ costCapTokens?: number;
+ agentTokenCaps?: Record<string, number>;
+ maxTurns?: number;
+ circuitBreaker?: CircuitBreakerConfig;
+ /** Enterprise Knowledge Graph (multimodal context for agents). Default OFF. */
+ knowledgeGraph?: KnowledgeGraphConfig;
+ /** Terminal theme, mirrored into each agent's per-session Claude settings. */
+ terminalTheme?: 'light' | 'dark';
+ /** TV-show office themes feature flag (Settings picker + switch flow). Default OFF. */
+ tvShowOffices?: boolean;
+ /** Active office map/cast theme (honored only when tvShowOffices is on). */
+ officeTheme?: 'office' | 'friends' | 'brooklyn99' | 'siliconvalley' | 'got' | 'hogwarts';
+}
+
+export interface MemoryStatus {
+ available: boolean;
+ enabled: boolean;
+ active: boolean;
+ initialized: boolean;
+ palacePath: string | null;
+ model: 'minilm' | 'embeddinggemma';
+ bin: string | null;
+}
+
+/** Enterprise Knowledge Graph — corpus status, one document, and a search hit. */
+export interface KnowledgeStatus {
+ enabled: boolean;
+ root: string;
+ docCount: number;
+ chunkCount: number;
+ byModality: Record<string, number>;
+}
+export interface KnowledgeDoc {
+ id: string;
+ title: string;
+ source: string;
+ modality: string;
+ mime: string | null;
+ origExt: string;
+ bytes: number;
+ tags: string[];
+ caption: string | null;
+ chunkCount: number;
+ addedAt: string;
+ extractor: string;
+ truncated: boolean;
+}
+export interface KnowledgeHit {
+ docId: string;
+ title: string;
+ source: string;
+ modality: string;
+ chunkIdx: number;
+ score: number;
+ snippet: string;
+}
+export interface KnowledgeIngestResult {
+ ok: boolean;
+ results: Array<{ ok: boolean; srcPath: string; docId?: string; chunkCount?: number; error?: string }>;
+ error?: string;
+}
+
+export interface DirEntry {
+ name: string;
+ isDir: boolean;
+ size: number;
+ mtime: number;
+}
+
+export interface GitCommit {
+ sha: string;
+ shortSha: string;
+ parents: string[];
+ subject: string;
+ author: string;
+ time: number;
+ refs: string[];
+}
+export interface GitStatusEntry { path: string; index: string; worktree: string }
+export interface GitStatus { staged: GitStatusEntry[]; unstaged: GitStatusEntry[]; untracked: string[] }
+
+/** Real token usage + estimated USD cost summed from an agent's Claude Code
+ * transcripts under ~/.claude/projects. Reconciler/fallback path — now priced
+ * PER MODEL (not Sonnet-for-everyone). The live path uses AgentUsageSample. */
+export interface AgentUsage {
+ inputTokens: number;
+ outputTokens: number;
+ cacheReadTokens: number;
+ cacheWriteTokens: number;
+ estimatedCostUsd: number;
+ /** Most-recently-seen model id (normalized), if any priced record was found. */
+ model?: string;
+}
+
+/** Live cumulative cost/token snapshot from the OTel collector (the locked
+ * cross-lane seam). PII-free by construction. Mirrors telemetry.ts. */
+export interface AgentUsageSample {
+ agentId: string;
+ sessionId: string;
+ ts: number;
+ input: number;
+ output: number;
+ cacheRead: number;
+ cacheCreation: number;
+ model: string;
+ usd: number;
+}
+
+/** One tool invocation for the per-agent span waterfall (#7B.2). Ephemeral. */
+export interface ToolSpan {
+ agentId: string;
+ sessionId: string;
+ ts: number;
+ tool: string;
+ success: boolean;
+ durationMs: number;
+ decision?: 'accept' | 'reject';
+ error?: string;
+}
+
+/** Closing-time progress event (mirrors src/main/closingTime.ts). */
+export interface ClosingTimeEvent {
+ phase: 'started' | 'progress' | 'complete' | 'timeout' | 'cancelled';
+ /** Workers that have ACKed so far / total workers being waited on. */
+ acked: number;
+ total: number;
+}
+
+/** Per-agent operator-control state (#7C.1–7C.3). */
+export interface AgentControlSnapshot {
+ paused: boolean;
+ halted: boolean;
+ gatedTools: string[];
+ pendingSteers: number;
+}
+
+/** Circuit-breaker state (Lane A #6 → this lane's avatars/meter). */
+export interface BreakerState {
+ agentId: string;
+ level: 'healthy' | 'steering' | 'constrained' | 'stopped';
+ reason: string;
+ ts: number;
+}
+
+/** Live telemetry push payload (channel `telemetry:event`). */
+export type TelemetryEvent =
+ | { kind: 'usage'; sample: AgentUsageSample }
+ | { kind: 'tool_result'; span: ToolSpan }
+ | { kind: 'api_error'; agentId: string; sessionId: string; ts: number; error: string };
+
+/** Cold-start backfill from the collector. */
+export interface TelemetrySnapshot {
+ usage: AgentUsageSample[];
+ spans: Record<string, ToolSpan[]>;
+}
+
+/** One captured user prompt from the SQLite command_history table. */
+export interface CommandHistoryEntry {
+ id: number;
+ agentId: string;
+ cwd: string | null;
+ text: string;
+ ts: number;
+}
+
+/** A GitHub issue, normalized for the renderer (labels/assignees flattened to names). */
+export interface GHIssue {
+ number: number;
+ title: string;
+ body: string;
+ url: string;
+ labels: string[];
+ assignees: string[];
+}
+
+/** A CI (GitHub Actions) workflow run, normalized for the renderer. */
+export interface CIRun {
+ name: string;
+ status: string;
+ conclusion: string | null;
+ url: string;
+}
+
+const api = {
+ version: __APP_VERSION__,
+
+ // ─── PTY ─────────────────────────────────────────────────────────────────
+ spawnPty: (opts: SpawnPtyOptions): Promise<{ ok: boolean; error?: string; worktreePath?: string; resumeNotFound?: boolean; resumed?: boolean }> =>
+ ipcRenderer.invoke('pty:spawn', opts),
+ writePty: (id: string, data: string): Promise<{ ok: boolean; error?: string }> =>
+ ipcRenderer.invoke('pty:write', id, data),
+ resizePty: (id: string, cols: number, rows: number): Promise<{ ok: boolean; error?: string }> =>
+ ipcRenderer.invoke('pty:resize', id, cols, rows),
+ killPty: (id: string): Promise<{ ok: boolean; error?: string }> =>
+ ipcRenderer.invoke('pty:kill', id),
+ listPtys: (): Promise<Array<{ id: string; cwd: string; command: string; pid: number }>> =>
+ ipcRenderer.invoke('pty:list'),
+ /** Resolve a Claude session id to the cwd it originally ran in (Add Agent
+ * resume auto-fill), or null if the id is invalid/unknown. */
+ resolveSessionCwd: (sessionId: string): Promise<string | null> =>
+ ipcRenderer.invoke('session:resolveCwd', sessionId),
+ onPtyData: (id: string, cb: (data: string) => void): (() => void) => {
+ const channel = `pty:data:${id}`;
+ const listener = (_e: IpcRendererEvent, data: string) => cb(data);
+ ipcRenderer.on(channel, listener);
+ return () => ipcRenderer.removeListener(channel, listener);
+ },
+ onPtyExit: (id: string, cb: (info: PtyExit) => void): (() => void) => {
+ const channel = `pty:exit:${id}`;
+ const listener = (_e: IpcRendererEvent, info: PtyExit) => cb(info);
+ ipcRenderer.on(channel, listener);
+ return () => ipcRenderer.removeListener(channel, listener);
+ },
+
+ // ─── Dialog ──────────────────────────────────────────────────────────────
+ chooseFolder: (): Promise<{ ok: true; path: string } | { ok: false; error: string }> =>
+ ipcRenderer.invoke('dialog:chooseFolder'),
+
+ // ─── Terminal.app ────────────────────────────────────────────────────────
+ openTerminalAt: (cwd: string): Promise<{ ok: boolean; error?: string }> =>
+ ipcRenderer.invoke('terminal:openAtFolder', cwd),
+
+ // ─── Clipboard ─────────────────────────────────────────────────────────────
+ copyToClipboard: (text: string): Promise<{ ok: boolean; error?: string }> =>
+ ipcRenderer.invoke('app:copyToClipboard', text),
+ /** Read the system clipboard as plain text ('' when empty/unreadable). */
+ readClipboard: (): Promise<string> =>
+ ipcRenderer.invoke('app:readClipboard'),
+
+ // ─── Config ──────────────────────────────────────────────────────────────
+ getConfig: (): Promise<HarnessConfig> =>
+ ipcRenderer.invoke('config:get'),
+ updateConfig: (patch: Partial<HarnessConfig>): Promise<HarnessConfig> =>
+ ipcRenderer.invoke('config:update', patch),
+ ensureHarnessHome: (path: string): Promise<{ ok: boolean; error?: string }> =>
+ ipcRenderer.invoke('config:ensureHome', path),
+ /** Change the harness home folder. 'move' copies the existing hive + palace
+ * into the new folder (old kept as a safety net); 'fresh' just re-points and
+ * bootstraps an empty home. On success the app relaunches (never resolves);
+ * on failure (e.g. copy error) returns { ok: false, error }. */
+ changeHome: (newHome: string, mode: 'move' | 'fresh'): Promise<{ ok: boolean; error?: string }> =>
+ ipcRenderer.invoke('config:changeHome', { newHome, mode }),
+
+ // ─── Filesystem (sandboxed to cwd) ───────────────────────────────────────
+ listDir: (root: string, rel: string): Promise<
+ { ok: true; entries: DirEntry[]; path: string } | { ok: false; error: string }
+ > => ipcRenderer.invoke('fs:listDir', root, rel),
+ readFile: (root: string, rel: string): Promise<
+ { ok: true; content: string; path: string; size: number } | { ok: false; error: string }
+ > => ipcRenderer.invoke('fs:readFile', root, rel),
+ writeFile: (root: string, rel: string, content: string): Promise<
+ { ok: true; path: string } | { ok: false; error: string }
+ > => ipcRenderer.invoke('fs:writeFile', root, rel, content),
+
+ // ─── Git ─────────────────────────────────────────────────────────────────
+ gitIsRepo: (cwd: string): Promise<boolean> => ipcRenderer.invoke('git:isRepo', cwd),
+ gitBranch: (cwd: string) =>
+ ipcRenderer.invoke('git:branch', cwd) as Promise<{ current: string | null; detached: boolean } | { error: string }>,
+ gitStatus: (cwd: string) =>
+ ipcRenderer.invoke('git:status', cwd) as Promise<GitStatus | { error: string }>,
+ gitLog: (cwd: string, n?: number) =>
+ ipcRenderer.invoke('git:log', cwd, n ?? 50) as Promise<GitCommit[] | { error: string }>,
+ gitBranches: (cwd: string) =>
+ ipcRenderer.invoke('git:branches', cwd) as Promise<{ local: string[]; remote: string[]; current: string | null } | { error: string }>,
+ gitAheadBehind: (cwd: string) =>
+ ipcRenderer.invoke('git:aheadBehind', cwd) as Promise<{ ahead: number; behind: number; upstream: string | null } | { error: string }>,
+
+ // ─── Hive (multi-agent coordination) ─────────────────────────────────────
+ hiveRegistry: (): Promise<HiveRegistry> => ipcRenderer.invoke('hive:registry'),
+ hiveBoard: (): Promise<string> => ipcRenderer.invoke('hive:board'),
+ hiveTasks: (): Promise<unknown> => ipcRenderer.invoke('hive:tasks'),
+ hiveLog: (n?: number): Promise<unknown[]> => ipcRenderer.invoke('hive:log', n ?? 200),
+ hiveMemory: (id: string): Promise<string> => ipcRenderer.invoke('hive:memory', id),
+ hiveInbox: (id: string): Promise<HiveMessage[]> => ipcRenderer.invoke('hive:inbox', id),
+
+ // ─── Semantic memory (MemPalace CLI) ─────────────────────────────────────
+ memoryStatus: (): Promise<MemoryStatus> => ipcRenderer.invoke('hive:memoryStatus'),
+ searchMemory: (query: string, wing?: string): Promise<{ ok: boolean; output: string; error?: string }> =>
+ ipcRenderer.invoke('hive:searchMemory', query, wing),
+ memoryWakeUp: (wing?: string): Promise<{ ok: boolean; output: string; error?: string }> =>
+ ipcRenderer.invoke('hive:memoryWakeUp', wing),
+ mineNow: (): Promise<{ ok: boolean }> => ipcRenderer.invoke('hive:mineNow'),
+ /** Condense agent memory.md files (the janitor's missing half). With an id,
+ * condense that agent on demand; without, run a full threshold scan. Returns
+ * the per-agent outcomes ({ id, condensed, reason, oldBytes?, newBytes? }). */
+ reflectNow: (id?: string): Promise<Array<{ id: string; condensed: boolean; reason: string; oldBytes?: number; newBytes?: number }>> =>
+ ipcRenderer.invoke('memory:reflectNow', id),
+
+ // ─── Enterprise Knowledge Graph (multimodal context for agents) ───────────
+ kgStatus: (): Promise<KnowledgeStatus> => ipcRenderer.invoke('kg:status'),
+ kgList: (): Promise<KnowledgeDoc[]> => ipcRenderer.invoke('kg:list'),
+ kgSearch: (query: string, limit?: number): Promise<KnowledgeHit[]> =>
+ ipcRenderer.invoke('kg:search', query, limit),
+ kgGet: (id: string): Promise<{ meta: KnowledgeDoc; text: string } | null> =>
+ ipcRenderer.invoke('kg:get', id),
+ kgRemove: (id: string): Promise<{ ok: boolean }> => ipcRenderer.invoke('kg:remove', id),
+ /** Open an OS file picker and ingest the chosen artifacts in one round-trip. */
+ kgAddFiles: (): Promise<KnowledgeIngestResult> => ipcRenderer.invoke('kg:addFiles'),
+ /** Ingest explicit file paths (e.g. drag-and-drop). */
+ kgIngestFiles: (paths: string[], tags?: string[]): Promise<KnowledgeIngestResult> =>
+ ipcRenderer.invoke('kg:ingestFiles', { paths, tags }),
+
+ // ─── Composer attachments (images + files, sent to agents by PATH) ─────────
+ /** Open an OS picker for images/files; returns chosen absolute paths + names. */
+ attachFiles: (): Promise<
+ { ok: true; files: { path: string; name: string }[] } | { ok: false; error: string }
+ > => ipcRenderer.invoke('dialog:attachFiles'),
+ /** Resolve a dropped File's absolute path (Electron 32 removed File.path). */
+ pathForFile: (file: File): string => webUtils.getPathForFile(file),
+ /** Write the current clipboard image to a temp PNG and return its path (paste-to-attach). */
+ saveClipboardImage: (): Promise<
+ { ok: true; file: { path: string; name: string } } | { ok: false; error: string }
+ > => ipcRenderer.invoke('clipboard:saveImage'),
+
+ // ─── Command history (SQLite — every prompt submitted to an agent) ─────────
+ /** Record one submitted prompt. Fire-and-forget from the prompt-detection hook. */
+ historyAdd: (entry: { agentId: string; cwd?: string; text: string }): Promise<{ ok: boolean; error?: string }> =>
+ ipcRenderer.invoke('history:add', entry),
+ /** Most-recent-first history, optionally scoped to one agent. */
+ historyList: (agentId?: string, limit?: number): Promise<CommandHistoryEntry[]> =>
+ ipcRenderer.invoke('history:list', agentId, limit),
+ /** Substring search over prompt text, most-recent-first. */
+ historySearch: (query: string, limit?: number): Promise<CommandHistoryEntry[]> =>
+ ipcRenderer.invoke('history:search', query, limit),
+ hiveSend: (msg: Partial<HiveMessage>, from?: string): Promise<{ ok: boolean; error?: string; message?: HiveMessage }> =>
+ ipcRenderer.invoke('hive:send', msg, from),
+
+ onHiveHookEvent: (
+ cb: (e: { agentId?: string; event: string; tool?: string; notificationType?: string; source?: string; message?: string; blocked?: boolean }) => void
+ ): (() => void) => {
+ const listener = (_e: IpcRendererEvent, payload: { agentId?: string; event: string; tool?: string; notificationType?: string; source?: string; message?: string; blocked?: boolean }) => cb(payload);
+ ipcRenderer.on('hive:hookEvent', listener);
+ return () => ipcRenderer.removeListener('hive:hookEvent', listener);
+ },
+ /** Push-based context accounting from the status line: live tokens + the
+ * session's EXACT context-window size. Same pattern as onHiveHookEvent. */
+ onHiveContextUpdate: (
+ cb: (e: { agentId: string; tokens: number; limit: number }) => void
+ ): (() => void) => {
+ const listener = (_e: IpcRendererEvent, payload: { agentId: string; tokens: number; limit: number }) => cb(payload);
+ ipcRenderer.on('hive:contextUpdate', listener);
+ return () => ipcRenderer.removeListener('hive:contextUpdate', listener);
+ },
+ onHiveMessage: (cb: (e: HiveRouteEvent) => void): (() => void) => {
+ const listener = (_e: IpcRendererEvent, payload: HiveRouteEvent) => cb(payload);
+ ipcRenderer.on('hive:message', listener);
+ return () => ipcRenderer.removeListener('hive:message', listener);
+ },
+ /** Register a listener for hive tasks routed to non-Claude agents (e.g.
+ * Codex). Main emits this instead of bouncing; the renderer enqueues the
+ * raw text so the drain effect types it into the agent's REPL when idle. */
+ onHiveEnqueue: (cb: (e: { targetId: string; text: string }) => void): (() => void) => {
+ const listener = (_e: IpcRendererEvent, payload: { targetId: string; text: string }) => cb(payload);
+ ipcRenderer.on('hive:enqueueToAgent', listener);
+ return () => ipcRenderer.removeListener('hive:enqueueToAgent', listener);
+ },
+ /** Register a listener for terminal work-order handoffs (#53) — hive mail to a
+ * hookless provider that can't drain an inbox; the renderer types it into the
+ * agent's REPL as a work order. */
+ onHiveTerminalHandoff: (cb: (e: HiveTerminalHandoffEvent) => void): (() => void) => {
+ const listener = (_e: IpcRendererEvent, payload: HiveTerminalHandoffEvent) => cb(payload);
+ ipcRenderer.on('hive:terminalHandoff', listener);
+ return () => ipcRenderer.removeListener('hive:terminalHandoff', listener);
+ },
+
++ // ─── Shareable hires (deep link / file import) ────────────────────────────
++ /** Fired when a validated hire manifest arrives via the munderdifflin://
++ * deep link. The renderer opens the Add-Agent modal pre-filled — import
++ * never spawns anything by itself. */
++ onHireImport: (cb: (manifest: HireManifest) => void): (() => void) => {
++ const listener = (_e: IpcRendererEvent, manifest: HireManifest) => cb(manifest);
++ ipcRenderer.on('hire:import', listener);
++ return () => ipcRenderer.removeListener('hire:import', listener);
++ },
++ /** Fired when a deep-linked manifest failed validation/fetch. */
++ onHireError: (cb: (info: { error: string }) => void): (() => void) => {
++ const listener = (_e: IpcRendererEvent, info: { error: string }) => cb(info);
++ ipcRenderer.on('hire:error', listener);
++ return () => ipcRenderer.removeListener('hire:error', listener);
++ },
++ /** Signal readiness and pull any queued deep-linked manifests (cold-start
++ * links, links that arrived during load). Resolves the queued list. */
++ drainPendingHires: (): Promise<HireManifest[]> =>
++ ipcRenderer.invoke('hire:drainPending'),
++ /** Open a file picker and validate the chosen hire-manifest JSON. */
++ importHireFile: (): Promise<{ ok: boolean; manifest?: HireManifest; error?: string }> =>
++ ipcRenderer.invoke('hire:openFile'),
++
+ // ─── Quit confirmation ───────────────────────────────────────────────────
+ onCloseRequested: (cb: (info: { ptyCount: number }) => void): (() => void) => {
+ const listener = (_e: IpcRendererEvent, info: { ptyCount: number }) => cb(info);
+ ipcRenderer.on('app:closeRequested', listener);
+ return () => ipcRenderer.removeListener('app:closeRequested', listener);
+ },
+ confirmClose: (): Promise<void> => ipcRenderer.invoke('app:confirmClose'),
+ cancelClose: (): Promise<void> => ipcRenderer.invoke('app:cancelClose'),
+
+ // ─── Multi-window floors ───────────────────────────────────────────────────
+ /** Open a new floor (independent office window). No-op when the multiWindow
+ * flag is off. Resolves { ok } indicating whether a window opened. */
+ newFloor: (): Promise<{ ok: boolean }> => ipcRenderer.invoke('window:newFloor'),
+
+ // ─── Closing time (graceful shutdown via the hive) ─────────────────────────
+ /** Start the closing-time protocol: the god broadcasts shutdown, every worker
+ * saves its memory and ACKs, the god concludes — then the app quits itself.
+ * Resolves with ok:false (+ error) when no god agent is running. */
+ startClosingTime: (): Promise<{ ok: boolean; error?: string }> =>
+ ipcRenderer.invoke('app:startClosingTime'),
+ /** Abort an in-progress closing time and tell the floor to resume work. */
+ cancelClosingTime: (): Promise<void> => ipcRenderer.invoke('app:cancelClosingTime'),
+ /** Progress events for the quit dialog: started → progress (ACK counts) →
+ * complete (the app tears down moments later) | timeout | cancelled. */
+ onClosingTime: (cb: (ev: ClosingTimeEvent) => void): (() => void) => {
+ const listener = (_e: IpcRendererEvent, ev: ClosingTimeEvent) => cb(ev);
+ ipcRenderer.on('app:closingTime', listener);
+ return () => ipcRenderer.removeListener('app:closingTime', listener);
+ },
+
+ // ─── Reset ─────────────────────────────────────────────────────────────────
+ /** Wipe all hive data + the memory palace, reset config, and relaunch the app
+ * into onboarding. The process exits, so this promise never resolves. */
+ resetAll: (): Promise<void> => ipcRenderer.invoke('app:resetAll'),
+
+ // ─── Token telemetry (real usage + est. cost from CC transcripts) ──────────
+ /** Sum input/output/cache tokens + estimated USD cost for an agent from its
+ * Claude Code transcripts (reconciler/fallback). Returns null for an invalid cwd. */
+ agentUsage: (cwd: string): Promise<AgentUsage | null> =>
+ ipcRenderer.invoke('hive:agentUsage', cwd),
+ /** Current context size (tokens) of an agent's live session, read from the
+ * last assistant message of its transcript. Null until the agent's hooks
+ * have fired at least once (the transcript path is learned from them). */
+ agentContext: (agentId: string): Promise<number | null> =>
+ ipcRenderer.invoke('hive:agentContext', agentId),
+
+ // ─── Live telemetry (OTel collector — the usage-provider seam + spans) ──────
+ /** Live cumulative usage for an agent (OTel-preferred, transcript fallback). */
+ telemetryUsage: (agentId: string): Promise<AgentUsageSample | null> =>
+ ipcRenderer.invoke('telemetry:usage', agentId),
+ /** Recent tool spans for an agent's waterfall (#7B.2). */
+ telemetrySpans: (agentId: string): Promise<ToolSpan[]> =>
+ ipcRenderer.invoke('telemetry:spans', agentId),
+ /** Cold-start backfill of all agents' usage + recent spans. */
+ telemetrySnapshot: (): Promise<TelemetrySnapshot> =>
+ ipcRenderer.invoke('telemetry:snapshot'),
+ /** Subscribe to live telemetry pushes; returns an unsubscribe fn. */
+ onTelemetryEvent: (cb: (e: TelemetryEvent) => void): (() => void) => {
+ const listener = (_e: IpcRendererEvent, payload: TelemetryEvent) => cb(payload);
+ ipcRenderer.on('telemetry:event', listener);
+ return () => ipcRenderer.removeListener('telemetry:event', listener);
+ },
+
+ // ─── Circuit breaker (Lane A #6 state → avatars/meter) ──────────────────────
+ /** Subscribe to breaker-state changes; returns an unsubscribe fn. */
+ onBreakerState: (cb: (s: BreakerState) => void): (() => void) => {
+ const listener = (_e: IpcRendererEvent, payload: BreakerState) => cb(payload);
+ ipcRenderer.on('control:breakerState', listener);
+ return () => ipcRenderer.removeListener('control:breakerState', listener);
+ },
+ /** Push a breaker state to the renderer (Lane A's policy / interim glue calls this). */
+ setBreakerState: (state: BreakerState): Promise<{ ok: boolean }> =>
+ ipcRenderer.invoke('control:setBreakerState', state),
+
+ // ─── Operator control over agents (#7C.1–7C.3) ──────────────────────────────
+ /** Pause/unpause an agent — paused → its tool calls are denied at PreToolUse. */
+ controlPause: (agentId: string, on: boolean): Promise<AgentControlSnapshot | null> =>
+ ipcRenderer.invoke('control:pause', agentId, on),
+ /** Clear pause + halt so the agent can run again. */
+ controlResume: (agentId: string): Promise<AgentControlSnapshot | null> =>
+ ipcRenderer.invoke('control:resume', agentId),
+ /** Gate/ungate a specific tool for an agent (denied at PreToolUse). */
+ controlGateTool: (agentId: string, tool: string, on: boolean): Promise<AgentControlSnapshot | null> =>
+ ipcRenderer.invoke('control:gateTool', agentId, tool, on),
+ /** Queue a steer note — injected as context on the agent's next hook (#7C.2). */
+ controlSteer: (agentId: string, text: string): Promise<AgentControlSnapshot | null> =>
+ ipcRenderer.invoke('control:steer', agentId, text),
+ /** Request a graceful stop at the next hook boundary (#7C.3). */
+ controlHalt: (agentId: string): Promise<AgentControlSnapshot | null> =>
+ ipcRenderer.invoke('control:halt', agentId),
+ /** Read an agent's current control snapshot. */
+ controlSnapshot: (agentId: string): Promise<AgentControlSnapshot | null> =>
+ ipcRenderer.invoke('control:snapshot', agentId),
+ /** Subscribe to gate/deny events (a tool was blocked); returns unsubscribe fn. */
+ onApprovalRequest: (cb: (e: { agentId: string; tool?: string; reason?: string }) => void): (() => void) => {
+ const listener = (_e: IpcRendererEvent, payload: { agentId: string; tool?: string; reason?: string }) => cb(payload);
+ ipcRenderer.on('control:approvalRequest', listener);
+ return () => ipcRenderer.removeListener('control:approvalRequest', listener);
+ },
+
+ // ─── Task kanban (hive/tasks.json) ───────────────────────────────────────
+ /** Overwrite the hive task ledger with the full task list and commit it. */
+ hiveWriteTasks: (tasks: HiveTask[]): Promise<{ ok: boolean; error?: string }> =>
+ ipcRenderer.invoke('hive:writeTasks', tasks),
+
+ // ─── Scheduled missions (recurring auto-dispatch) ──────────────────────────
+ listMissions: (): Promise<ScheduledMission[]> => ipcRenderer.invoke('missions:list'),
+ saveMissions: (missions: ScheduledMission[]): Promise<{ ok: boolean }> =>
+ ipcRenderer.invoke('missions:save', missions),
+ /** Fires when the scheduler stamps a mission's lastFiredAt (a beat/dispatch),
+ * so the SCHEDULES panel can refresh "last fired" without a reload. */
+ onMissionsUpdated: (cb: () => void): (() => void) => {
+ const listener = (): void => cb();
+ ipcRenderer.on('missions:updated', listener);
+ return () => ipcRenderer.removeListener('missions:updated', listener);
+ },
+ /** Fires when an autoCompact mission ticks — the renderer queues a /compact
+ * per agent (deduped) and delivers it when each agent is idle. */
+ onAutoCompact: (cb: () => void): (() => void) => {
+ const listener = (): void => cb();
+ ipcRenderer.on('mission:autoCompact', listener);
+ return () => ipcRenderer.removeListener('mission:autoCompact', listener);
+ },
+
+ // ─── Full-text search across hive files (board, tasks, memory) ─────────────
+ textSearch: (q: string): Promise<{ ok: boolean; results: Array<{ source: string; excerpt: string }> }> =>
+ ipcRenderer.invoke('hive:textSearch', q),
+
+ // ─── GitHub issue ingestion (gh CLI) ───────────────────────────────────────
+ /** List up to 30 open issues in the repo at `cwd` via the `gh` CLI. Returns
+ * `{ ok: false, error }` if `gh` is missing/unauthenticated or `cwd` isn't a repo. */
+ githubIssues: (cwd: string): Promise<{ ok: boolean; issues?: GHIssue[]; error?: string }> =>
+ ipcRenderer.invoke('github:issues', cwd),
+
+ // ─── GitHub CI status watcher (gh CLI) ─────────────────────────────────────
+ /** List up to 5 recent CI (GitHub Actions) runs in the repo at `cwd` via the
+ * `gh` CLI. Returns `{ ok: false, error }` if `gh` is missing/unauthenticated,
+ * `cwd` isn't a repo, or the repo has no Actions. */
+ githubCIRuns: (cwd: string): Promise<{ ok: boolean; runs?: CIRun[]; error?: string }> =>
+ ipcRenderer.invoke('github:ciRuns', cwd),
+
+ // ─── Desktop notifications ───────────────────────────────────────────────────
+ /** Toggle native desktop notifications for agent lifecycle events. */
+ setNotifications: (v: boolean): Promise<HarnessConfig> =>
+ ipcRenderer.invoke('app:setNotifications', v),
+
+ // ─── Agent lifecycle (archival) ─────────────────────────────────────────────
+ /** Archive/unarchive a hive agent in the registry. Closing a terminal tab
+ * archives it automatically via pty:kill; this is the explicit primitive. */
+ hiveSetArchived: (id: string, archived: boolean): Promise<{ ok: boolean; error?: string }> =>
+ ipcRenderer.invoke('hive:setArchived', id, archived),
+
+ // ─── Slack integration (Slack message → Michael's queue) ─────────────────────
+ /** Register a listener for inbound Slack messages; returns an unsubscribe fn.
+ * The message carries the thread coordinates needed to reply in-thread. */
+ onSlackMessage: (cb: (msg: { text: string; channel: string; ts: string; thread_ts: string; autonomyPreamble?: string; files?: { path: string; name: string; mimetype: string }[] }) => void): (() => void) => {
+ const listener = (_e: IpcRendererEvent, msg: { text: string; channel: string; ts: string; thread_ts: string; autonomyPreamble?: string; files?: { path: string; name: string; mimetype: string }[] }) => cb(msg);
+ ipcRenderer.on('slack:incomingMessage', listener);
+ return () => ipcRenderer.removeListener('slack:incomingMessage', listener);
+ },
+ /** Start the Slack webhook server; returns the public tunnel URL to paste into
+ * the Slack app's Event Subscriptions → Request URL. */
+ slackStart: (): Promise<{ ok: boolean; url?: string; error?: string }> =>
+ ipcRenderer.invoke('slack:start'),
+ /** Stop the Slack webhook server + tunnel. */
+ slackStop: (): Promise<{ ok: boolean }> =>
+ ipcRenderer.invoke('slack:stop'),
+ /** Current connection state + last Request URL (so Settings can hydrate the
+ * "Connected" badge and re-show the persisted tunnel URL on reopen). */
+ slackStatus: (): Promise<{ running: boolean; url?: string }> =>
+ ipcRenderer.invoke('slack:status'),
+ /** Post a reply into a Slack thread (the bot token stays in main). Used for the
+ * renderer's immediate "queued" ack. */
+ slackReply: (m: { channel: string; thread_ts: string; text: string }): Promise<{ ok: boolean; error?: string }> =>
+ ipcRenderer.invoke('slack:reply', m),
+ /** Absolute path to the bundled reply helper, for the office worker's
+ * end-of-run "post your summary back to Slack" instruction. */
+ slackReplyScriptPath: (): Promise<string> =>
+ ipcRenderer.invoke('slack:replyScriptPath'),
+ /** Persist Slack settings (and stop the server if disabled / secret cleared). */
+ slackSetConfig: (patch: {
+ signingSecret?: string; botToken?: string; channelId?: string; port?: number; enabled?: boolean;
+ }): Promise<{ ok: boolean }> =>
+ ipcRenderer.invoke('slack:setConfig', patch),
+
+ // ─── Generic webhook + status API (POST → work, GET → status) ────────────────
+ /** Start the generic webhook server; returns the public endpoint URL callers
+ * POST to (secret-gated) and GET a token's status from. */
+ webhookStart: (): Promise<{ ok: boolean; url?: string; error?: string }> =>
+ ipcRenderer.invoke('webhook:start'),
+ /** Stop the generic webhook server + tunnel. */
+ webhookStop: (): Promise<{ ok: boolean }> =>
+ ipcRenderer.invoke('webhook:stop'),
+ /** Current state + last endpoint URL (so Settings can hydrate the badge/URL). */
+ webhookStatus: (): Promise<{ running: boolean; url?: string }> =>
+ ipcRenderer.invoke('webhook:status'),
+ /** Mint + persist a fresh secret and return it for the user to copy. */
+ webhookGenerateSecret: (): Promise<{ ok: boolean; secret?: string }> =>
+ ipcRenderer.invoke('webhook:generateSecret'),
+ /** Persist webhook settings (and stop the server if disabled / secret cleared). */
+ webhookSetConfig: (patch: {
+ secret?: string; port?: number; enabled?: boolean;
+ }): Promise<{ ok: boolean }> =>
+ ipcRenderer.invoke('webhook:setConfig', patch),
+
+ // ─── 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. */
+ freeflowSetConfig: (patch: {
+ enabled?: boolean; apiKey?: string; model?: string;
+ }): Promise<{ ok: boolean }> =>
+ ipcRenderer.invoke('freeflow:setConfig', patch),
+ /** Transcribe one captured audio clip via Groq (the key stays in main; only the
+ * audio bytes go in and the transcript comes back). Gated on the flag + a key. */
+ freeflowTranscribe: (arg: {
+ audio: ArrayBuffer | Uint8Array; mimeType?: string; filename?: string; language?: string;
+ }): Promise<{ ok: boolean; text?: string; error?: string }> =>
+ ipcRenderer.invoke('freeflow:transcribe', arg)
+};
+
+contextBridge.exposeInMainWorld('cth', api);
+
+export type CthApi = typeof api;
diff --cc src/renderer/src/App.tsx
index f16eb894,eac59ac5..c755f1c1
--- a/src/renderer/src/App.tsx
+++ b/src/renderer/src/App.tsx
@@@ -1,311 -1,325 +1,333 @@@
-import { useEffect, useState } from 'react';
-import { useStore, selectedAgent } from '@/store/store';
-import { startMockLoop, stopMockLoop } from '@/store/mockEvents';
-import type { HarnessConfig } from '@/store/config';
-import { OfficeFloor } from '@/scene/office/OfficeFloor';
-import { useHive } from '@/hooks/useHive';
-import { MemoryPanel } from '@/components/MemoryPanel';
-import { AgentDetailPanel } from '@/components/AgentDetailPanel';
-import { AgentStrip } from '@/components/AgentStrip';
-import { AddAgentModal } from '@/components/AddAgentModal';
-import { MichaelBooting } from '@/components/MichaelBooting';
-import { OnboardingWizard } from '@/components/OnboardingWizard';
-import { QuitWarningModal, type ClosingTimeState } from '@/components/QuitWarningModal';
-import { SettingsModal } from '@/components/SettingsModal';
-import { PixelPanel } from '@/components/PixelPanel';
-import { PixelButton } from '@/components/PixelButton';
-import { Icon } from '@/components/Icon';
-import { SidebarSplitter } from '@/components/SidebarSplitter';
-import { acquireTerminal } from '@/components/terminalPool';
-import { FullscreenTerminal } from '@/components/FullscreenTerminal';
-import { TaskDetailOverlay } from '@/components/TaskDetailOverlay';
-import { FullscreenFileEditor } from '@/components/FullscreenFileEditor';
-import brandLogo from '@brand/logo.png?url';
-
-// Injected at build time from package.json (see electron.vite.config.ts).
-declare const __APP_VERSION__: string;
-
-export function App() {
- const agent = useStore(selectedAgent);
- const agents = useStore(s => s.agents);
- const agentCount = agents.length;
- const addAgentOpen = useStore(s => s.addAgentOpen);
- const setAddAgentOpen = useStore(s => s.setAddAgentOpen);
- const godStatus = useStore(s => s.godStatus);
- const fullscreenAgentId = useStore(s => s.fullscreenAgentId);
- const fullscreenFilePath = useStore(s => s.fullscreenFilePath);
- const sidebarWidth = useStore(s => s.sidebarWidth);
- const setSidebarWidth = useStore(s => s.setSidebarWidth);
-
- const [config, setConfig] = useState<HarnessConfig | null>(null);
- const [settingsOpen, setSettingsOpen] = useState(false);
- const [quitWarn, setQuitWarn] = useState<{ ptyCount: number } | null>(null);
- const [closing, setClosing] = useState<ClosingTimeState | null>(null);
- const [vpWidth, setVpWidth] = useState<number>(window.innerWidth);
-
- // Initial config load
- useEffect(() => {
- let cancelled = false;
- window.cth.getConfig().then(c => { if (!cancelled) setConfig(c); });
- return () => { cancelled = true; };
- }, []);
-
- // Quit warning subscription
- useEffect(() => window.cth.onCloseRequested((info) => setQuitWarn(info)), []);
-
- // The Add-Agent modal reads defaults (registeredRepos, default model) from
- // config — refetch on open so it sees folders remembered by earlier spawns
- // and any Settings changes, without waiting for an app restart.
- useEffect(() => {
- if (addAgentOpen) void window.cth.getConfig().then(setConfig);
- }, [addAgentOpen]);
-
- // Shareable hires: a validated manifest arriving via the munderdifflin://
- // deep link pre-fills the Add-Agent modal. Never spawns by itself.
- const setPendingHire = useStore(s => s.setPendingHire);
- useEffect(() => {
- const unsub = window.cth.onHireImport?.((m) => {
- setPendingHire(m);
- setAddAgentOpen(true);
- });
- // Pull anything that arrived before this subscription existed (cold-start
- // deep links; packaged renderers load too fast for push-on-load).
- void window.cth.drainPendingHires?.().then((queued) => {
- if (queued && queued.length > 0) {
- setPendingHire(queued[queued.length - 1]);
- setAddAgentOpen(true);
- }
- });
- return unsub;
- }, [setPendingHire, setAddAgentOpen]);
- useEffect(() => window.cth.onHireError?.((info) => {
- console.error('[hire] import failed:', info.error);
- }), []);
-
- // Closing-time progress: drives the quit dialog's "wrapping up" view. The
- // dialog stays up through the whole protocol; on 'complete' the main process
- // tears down and quits by itself moments later.
- useEffect(() => window.cth.onClosingTime?.((ev) => {
- if (ev.phase === 'cancelled') { setClosing(null); return; }
- setClosing({ phase: ev.phase, acked: ev.acked, total: ev.total });
- if (ev.phase === 'started' || ev.phase === 'progress') setQuitWarn((w) => w ?? { ptyCount: 0 });
- }), []);
-
- const startClosingTime = async () => {
- const res = await window.cth.startClosingTime();
- if (!res.ok) setClosing({ phase: 'error', acked: 0, total: 0, error: res.error });
- };
- const cancelClosingTime = () => {
- void window.cth.cancelClosingTime();
- setClosing(null);
- };
-
- // The hive: god-agent bootstrap, hook-driven avatars, idle-agent waking.
- useHive(config);
-
- // Pre-warm a persistent terminal for every live agent so its output is
- // buffered from spawn. Switching agents then re-attaches an already-rendered
- // terminal instantly (with full history) instead of building a blank one.
- useEffect(() => {
- for (const a of agents) if (a.ptyId) acquireTerminal(a.ptyId);
- }, [agents]);
-
- // Synthetic demo loop — CAGED (#5B). It must never animate alongside a live
- // hive (it would fire fake envelope handoffs and step seeded agents). Run it
- // only as an explicit showcase (VITE_CTH_DEMO=1 in dev) or on a genuinely
- // empty floor, and stop it the instant the first real PTY agent appears
- // (Michael always spawns, so in normal operation it effectively never runs).
- useEffect(() => {
- if (!config?.onboardingComplete) return;
- const DEMO = import.meta.env.DEV && import.meta.env.VITE_CTH_DEMO === '1';
- const evaluate = () => {
- const hasLive = useStore.getState().agents.some((a) => a.ptyId);
- if (DEMO || !hasLive) startMockLoop();
- else stopMockLoop();
- };
- evaluate();
- const unsub = useStore.subscribe(evaluate);
- return () => { unsub(); stopMockLoop(); };
- }, [config?.onboardingComplete]);
-
- // Reconcile restored agents against the PTYs still alive in the main process.
- // After a renderer reload (e.g. the laptop slept and Vite reloaded the page),
- // this keeps agents whose process survived and drops any that truly died.
- useEffect(() => {
- if (!config?.onboardingComplete) return;
- let cancelled = false;
- window.cth.listPtys().then((list) => {
- if (cancelled) return;
- useStore.getState().reconcileWithLivePtys(list.map((p) => p.id));
- }).catch(() => { /* ignore — keep restored agents as-is */ });
- return () => { cancelled = true; };
- }, [config?.onboardingComplete]);
-
- // Track viewport width for splitter clamping
- useEffect(() => {
- const onResize = () => setVpWidth(window.innerWidth);
- window.addEventListener('resize', onResize);
- return () => window.removeEventListener('resize', onResize);
- }, []);
-
- if (!config) {
- return <div style={{ width: '100vw', height: '100vh', background: 'var(--cth-cream-100)' }} />;
- }
-
- if (!config.onboardingComplete) {
- return <OnboardingWizard onComplete={(next) => setConfig(next)} />;
- }
-
- return (
- <div style={{
- display: 'flex', flexDirection: 'column',
- width: '100vw', height: '100vh',
- overflow: 'hidden'
- }}>
- {/* Title bar */}
- <div
- className="cth-titlebar-drag"
- style={{
- height: 36, minHeight: 36,
- background: 'linear-gradient(180deg, var(--cth-cream-100) 0%, var(--cth-cream-200) 100%)',
- borderBottom: '2px solid var(--cth-ink-900)',
- display: 'flex',
- alignItems: 'center',
- paddingLeft: 96,
- paddingRight: 12,
- gap: 12,
- userSelect: 'none'
- }}
- >
- <img
- src={brandLogo}
- alt="Munder Difflin"
- style={{ height: 20, width: 'auto', display: 'block' }}
- />
- <span style={{
- fontFamily: 'var(--cth-font-ui)',
- fontSize: 14,
- color: 'var(--cth-ink-500)'
- }}>
- v{__APP_VERSION__} · {config.autoMode ? 'auto mode on' : 'auto mode off'}
- </span>
- <button
- className="cth-titlebar-nodrag cth-settings-btn"
- onClick={() => setSettingsOpen(true)}
- title="Settings"
- aria-label="Settings"
- style={{
- marginLeft: 'auto',
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- width: 28, height: 28, padding: 0,
- background: 'var(--cth-paper-100)',
- boxShadow: 'inset 0 0 0 1.5px var(--cth-ink-900)',
- border: 'none', borderRadius: 2, cursor: 'pointer',
- color: 'var(--cth-ink-900)'
- }}
- >
- <Icon name="gear" size={1} style={{ width: 18, height: 18 }} />
- </button>
- </div>
-
- <div style={{
- flex: 1, minHeight: 0,
- display: 'flex',
- padding: 16,
- gap: 0
- }}>
- <div style={{ flex: 1, minHeight: 0, minWidth: 0, position: 'relative' }}>
- <OfficeFloor />
- <MemoryPanel />
- {agentCount === 0 && godStatus === 'booting' && <MichaelBooting />}
- {agentCount === 0 && godStatus !== 'booting' && (
- <div style={{
- position: 'absolute', inset: 0,
- display: 'flex', alignItems: 'center', justifyContent: 'center',
- pointerEvents: 'none'
- }}>
- <div style={{ pointerEvents: 'auto', width: 360 }}>
- <PixelPanel variant="dialog" title="EMPTY FLOOR" noPadding>
- <div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 10 }}>
- <p style={{ margin: 0, fontSize: 14, lineHeight: '20px' }}>
- No agents on the floor yet. Spawn one to see real claude output stream in here.
- </p>
- <PixelButton variant="primary" size="md" onClick={() => setAddAgentOpen(true)}>
- <span style={{ display: 'inline-flex', gap: 6, alignItems: 'center' }}>
- <Icon name="plus" /> add agent
- </span>
- </PixelButton>
- </div>
- </PixelPanel>
- </div>
- </div>
- )}
- </div>
-
- <SidebarSplitter
- width={sidebarWidth}
- onChange={setSidebarWidth}
- viewportWidth={vpWidth}
- />
-
- <div style={{
- width: sidebarWidth, flexShrink: 0,
- minHeight: 0, display: 'flex', flexDirection: 'column'
- }}>
- {agent ? (
- <AgentDetailPanel agent={agent} />
- ) : godStatus === 'booting' ? (
- <PixelPanel variant="default" noPadding style={{
- padding: 16, height: '100%',
- display: 'flex', flexDirection: 'column',
- justifyContent: 'center', alignItems: 'center', gap: 12
- }}>
- <div style={{
- fontFamily: 'var(--cth-font-display)', fontSize: 10, lineHeight: '14px',
- color: 'var(--cth-ink-500)'
- }}>WAKING THE FLOOR</div>
- <p style={{ margin: 0, fontSize: 14, textAlign: 'center', color: 'var(--cth-ink-700)' }}>
- Michael is clocking in.<br />
- The terminal will land here once he's seated.
- </p>
- </PixelPanel>
- ) : (
- <PixelPanel variant="default" noPadding style={{
- padding: 16, height: '100%',
- display: 'flex', flexDirection: 'column',
- justifyContent: 'center', alignItems: 'center', gap: 12
- }}>
- <div style={{
- fontFamily: 'var(--cth-font-display)', fontSize: 10, lineHeight: '14px',
- color: 'var(--cth-ink-500)'
- }}>NO AGENT SELECTED</div>
- <p style={{ margin: 0, fontSize: 14, textAlign: 'center', color: 'var(--cth-ink-700)' }}>
- Spawn an agent from the strip below.<br />
- The terminal and command bar will land here.
- </p>
- <PixelButton variant="secondary" size="md" onClick={() => setAddAgentOpen(true)}>
- <span style={{ display: 'inline-flex', gap: 6, alignItems: 'center' }}>
- <Icon name="plus" /> add agent
- </span>
- </PixelButton>
- </PixelPanel>
- )}
- </div>
- </div>
-
- <AgentStrip config={config} />
-
- {addAgentOpen && (
- <AddAgentModal onClose={() => { setAddAgentOpen(false); setPendingHire(null); }} config={config} />
- )}
-
- {settingsOpen && (
- <SettingsModal config={config} onClose={() => setSettingsOpen(false)} />
- )}
-
- {quitWarn && (
- <QuitWarningModal
- ptyCount={quitWarn.ptyCount}
- closing={closing}
- onCancel={() => {
- if (closing) cancelClosingTime();
- window.cth.cancelClose();
- setQuitWarn(null);
- }}
- onConfirm={async () => { await window.cth.confirmClose(); }}
- onClosingTime={startClosingTime}
- />
- )}
-
- {fullscreenAgentId && <FullscreenTerminal />}
- {fullscreenFilePath && <FullscreenFileEditor />}
- <TaskDetailOverlay />
- </div>
- );
-}
+import { useEffect, useState } from 'react';
+import { useStore, selectedAgent } from '@/store/store';
+import { startMockLoop, stopMockLoop } from '@/store/mockEvents';
+import type { HarnessConfig } from '@/store/config';
+import { OfficeFloor } from '@/scene/office/OfficeFloor';
+import { useHive } from '@/hooks/useHive';
+import { MemoryPanel } from '@/components/MemoryPanel';
+import { AgentDetailPanel } from '@/components/AgentDetailPanel';
+import { AgentStrip } from '@/components/AgentStrip';
+import { AddAgentModal } from '@/components/AddAgentModal';
+import { MichaelBooting } from '@/components/MichaelBooting';
+import { OnboardingWizard } from '@/components/OnboardingWizard';
+import { QuitWarningModal, type ClosingTimeState } from '@/components/QuitWarningModal';
+import { SettingsModal } from '@/components/SettingsModal';
+import { PixelPanel } from '@/components/PixelPanel';
+import { PixelButton } from '@/components/PixelButton';
+import { Icon } from '@/components/Icon';
+import { SidebarSplitter } from '@/components/SidebarSplitter';
+import { acquireTerminal } from '@/components/terminalPool';
+import { FullscreenTerminal } from '@/components/FullscreenTerminal';
+import { TaskDetailOverlay } from '@/components/TaskDetailOverlay';
+import { FullscreenFileEditor } from '@/components/FullscreenFileEditor';
+import { useHoldOptionToTalk } from '@/freeflow/holdOption';
+import brandLogo from '@brand/logo.png?url';
+
+// Injected at build time from package.json (see electron.vite.config.ts).
+declare const __APP_VERSION__: string;
+
+export function App() {
+ const agent = useStore(selectedAgent);
+ const agents = useStore(s => s.agents);
+ const agentCount = agents.length;
+ const addAgentOpen = useStore(s => s.addAgentOpen);
+ const setAddAgentOpen = useStore(s => s.setAddAgentOpen);
+ const godStatus = useStore(s => s.godStatus);
+ const fullscreenAgentId = useStore(s => s.fullscreenAgentId);
+ const fullscreenFilePath = useStore(s => s.fullscreenFilePath);
+ const sidebarWidth = useStore(s => s.sidebarWidth);
+ const setSidebarWidth = useStore(s => s.setSidebarWidth);
+
+ const [config, setConfig] = useState<HarnessConfig | null>(null);
+ const [settingsOpen, setSettingsOpen] = useState(false);
+ const [quitWarn, setQuitWarn] = useState<{ ptyCount: number } | null>(null);
+ const [closing, setClosing] = useState<ClosingTimeState | null>(null);
+ const [vpWidth, setVpWidth] = useState<number>(window.innerWidth);
+
+ // Initial config load
+ useEffect(() => {
+ let cancelled = false;
+ window.cth.getConfig().then(c => {
+ if (cancelled) return;
+ setConfig(c);
+ // Mirror the Free Flow flag into the store so the composer mic button shows
+ // only when enabled (Settings keeps this in sync on save).
+ useStore.getState().setFreeflowEnabled(!!c.freeflowEnabled);
+ // 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');
+ });
+ return () => { cancelled = true; };
+ }, []);
+
+ // Free Flow entry point B — hold-Option (⌥) to talk. In-renderer push-to-talk
+ // for whichever agent the user is viewing; gated on the flag, terminal-safe
+ // (solo-hold threshold, aborts on any other key). See freeflow/holdOption.ts.
+ useHoldOptionToTalk();
+
+ // Quit warning subscription
+ useEffect(() => window.cth.onCloseRequested((info) => setQuitWarn(info)), []);
+
++ // Shareable hires: a validated manifest arriving via the munderdifflin://
++ // deep link (or file import) pre-fills the Add-Agent modal. Never spawns by itself.
++ const setPendingHire = useStore(s => s.setPendingHire);
++ useEffect(() => {
++ const unsub = window.cth.onHireImport?.((m) => {
++ setPendingHire(m);
++ setAddAgentOpen(true);
++ });
++ // Pull anything that arrived before this subscription existed (cold-start
++ // deep links; packaged renderers load too fast for push-on-load).
++ void window.cth.drainPendingHires?.().then((queued) => {
++ if (queued && queued.length > 0) {
++ setPendingHire(queued[queued.length - 1]);
++ setAddAgentOpen(true);
++ }
++ });
++ return unsub;
++ }, [setPendingHire, setAddAgentOpen]);
++ useEffect(() => window.cth.onHireError?.((info) => {
++ console.error('[hire] import failed:', info.error);
++ }), []);
++
+ // Closing-time progress: drives the quit dialog's "wrapping up" view. The
+ // dialog stays up through the whole protocol; on 'complete' the main process
+ // tears down and quits by itself moments later.
+ useEffect(() => window.cth.onClosingTime?.((ev) => {
+ if (ev.phase === 'cancelled') { setClosing(null); return; }
+ setClosing({ phase: ev.phase, acked: ev.acked, total: ev.total });
+ if (ev.phase === 'started' || ev.phase === 'progress') setQuitWarn((w) => w ?? { ptyCount: 0 });
+ }), []);
+
+ const startClosingTime = async () => {
+ const res = await window.cth.startClosingTime();
+ if (!res.ok) setClosing({ phase: 'error', acked: 0, total: 0, error: res.error });
+ };
+ const cancelClosingTime = () => {
+ void window.cth.cancelClosingTime();
+ setClosing(null);
+ };
+
+ // The hive: god-agent bootstrap, hook-driven avatars, idle-agent waking.
+ useHive(config);
+
+ // Pre-warm a persistent terminal for every live agent so its output is
+ // buffered from spawn. Switching agents then re-attaches an already-rendered
+ // terminal instantly (with full history) instead of building a blank one.
+ useEffect(() => {
+ for (const a of agents) if (a.ptyId) acquireTerminal(a.ptyId);
+ }, [agents]);
+
+ // Synthetic demo loop — CAGED (#5B). It must never animate alongside a live
+ // hive (it would fire fake envelope handoffs and step seeded agents). Run it
+ // only as an explicit showcase (VITE_CTH_DEMO=1 in dev) or on a genuinely
+ // empty floor, and stop it the instant the first real PTY agent appears
+ // (Michael always spawns, so in normal operation it effectively never runs).
+ useEffect(() => {
+ if (!config?.onboardingComplete) return;
+ const DEMO = import.meta.env.DEV && import.meta.env.VITE_CTH_DEMO === '1';
+ const evaluate = () => {
+ const hasLive = useStore.getState().agents.some((a) => a.ptyId);
+ if (DEMO || !hasLive) startMockLoop();
+ else stopMockLoop();
+ };
+ evaluate();
+ const unsub = useStore.subscribe(evaluate);
+ return () => { unsub(); stopMockLoop(); };
+ }, [config?.onboardingComplete]);
+
+ // Reconcile restored agents against the PTYs still alive in the main process.
+ // After a renderer reload (e.g. the laptop slept and Vite reloaded the page),
+ // this keeps agents whose process survived and drops any that truly died.
+ useEffect(() => {
+ if (!config?.onboardingComplete) return;
+ let cancelled = false;
+ window.cth.listPtys().then((list) => {
+ if (cancelled) return;
+ useStore.getState().reconcileWithLivePtys(list.map((p) => p.id));
+ }).catch(() => { /* ignore — keep restored agents as-is */ });
+ return () => { cancelled = true; };
+ }, [config?.onboardingComplete]);
+
+ // Track viewport width for splitter clamping
+ useEffect(() => {
+ const onResize = () => setVpWidth(window.innerWidth);
+ window.addEventListener('resize', onResize);
+ return () => window.removeEventListener('resize', onResize);
+ }, []);
+
+ if (!config) {
+ return <div style={{ width: '100vw', height: '100vh', background: 'var(--cth-cream-100)' }} />;
+ }
+
+ if (!config.onboardingComplete) {
+ return <OnboardingWizard onComplete={(next) => setConfig(next)} />;
+ }
+
+ return (
+ <div style={{
+ display: 'flex', flexDirection: 'column',
+ width: '100vw', height: '100vh',
+ overflow: 'hidden'
+ }}>
+ {/* Title bar */}
+ <div
+ className="cth-titlebar-drag"
+ style={{
+ height: 36, minHeight: 36,
+ background: 'linear-gradient(180deg, var(--cth-cream-100) 0%, var(--cth-cream-200) 100%)',
+ borderBottom: '2px solid var(--cth-ink-900)',
+ display: 'flex',
+ alignItems: 'center',
+ paddingLeft: 96,
+ paddingRight: 12,
+ gap: 12,
+ userSelect: 'none'
+ }}
+ >
+ <img
+ src={brandLogo}
+ alt="Munder Difflin"
+ style={{ height: 20, width: 'auto', display: 'block' }}
+ />
+ <span style={{
+ fontFamily: 'var(--cth-font-ui)',
+ fontSize: 14,
+ color: 'var(--cth-ink-500)'
+ }}>
+ v{__APP_VERSION__} · {config.autoMode ? 'auto mode on' : 'auto mode off'}
+ </span>
+ <button
+ className="cth-titlebar-nodrag cth-settings-btn"
+ onClick={() => setSettingsOpen(true)}
+ title="Settings"
+ aria-label="Settings"
+ style={{
+ marginLeft: 'auto',
+ display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
+ width: 28, height: 28, padding: 0,
+ background: 'var(--cth-paper-100)',
+ boxShadow: 'inset 0 0 0 1.5px var(--cth-ink-900)',
+ border: 'none', borderRadius: 2, cursor: 'pointer',
+ color: 'var(--cth-ink-900)'
+ }}
+ >
+ <Icon name="gear" size={1} style={{ width: 18, height: 18 }} />
+ </button>
+ </div>
+
+ <div style={{
+ flex: 1, minHeight: 0,
+ display: 'flex',
+ padding: 16,
+ gap: 0
+ }}>
+ <div style={{ flex: 1, minHeight: 0, minWidth: 0, position: 'relative' }}>
+ <OfficeFloor />
+ <MemoryPanel />
+ {agentCount === 0 && godStatus === 'booting' && <MichaelBooting />}
+ {agentCount === 0 && godStatus !== 'booting' && (
+ <div style={{
+ position: 'absolute', inset: 0,
+ display: 'flex', alignItems: 'center', justifyContent: 'center',
+ pointerEvents: 'none'
+ }}>
+ <div style={{ pointerEvents: 'auto', width: 360 }}>
+ <PixelPanel variant="dialog" title="EMPTY FLOOR" noPadding>
+ <div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 10 }}>
+ <p style={{ margin: 0, fontSize: 14, lineHeight: '20px' }}>
+ No agents on the floor yet. Spawn one to see real claude output stream in here.
+ </p>
+ <PixelButton variant="primary" size="md" onClick={() => setAddAgentOpen(true)}>
+ <span style={{ display: 'inline-flex', gap: 6, alignItems: 'center' }}>
+ <Icon name="plus" /> add agent
+ </span>
+ </PixelButton>
+ </div>
+ </PixelPanel>
+ </div>
+ </div>
+ )}
+ </div>
+
+ <SidebarSplitter
+ width={sidebarWidth}
+ onChange={setSidebarWidth}
+ viewportWidth={vpWidth}
+ />
+
+ <div style={{
+ width: sidebarWidth, flexShrink: 0,
+ minHeight: 0, display: 'flex', flexDirection: 'column'
+ }}>
+ {agent ? (
+ <AgentDetailPanel agent={agent} />
+ ) : godStatus === 'booting' ? (
+ <PixelPanel variant="default" noPadding style={{
+ padding: 16, height: '100%',
+ display: 'flex', flexDirection: 'column',
+ justifyContent: 'center', alignItems: 'center', gap: 12
+ }}>
+ <div style={{
+ fontFamily: 'var(--cth-font-display)', fontSize: 10, lineHeight: '14px',
+ color: 'var(--cth-ink-500)'
+ }}>WAKING THE FLOOR</div>
+ <p style={{ margin: 0, fontSize: 14, textAlign: 'center', color: 'var(--cth-ink-700)' }}>
+ Michael is clocking in.<br />
+ The terminal will land here once he's seated.
+ </p>
+ </PixelPanel>
+ ) : (
+ <PixelPanel variant="default" noPadding style={{
+ padding: 16, height: '100%',
+ display: 'flex', flexDirection: 'column',
+ justifyContent: 'center', alignItems: 'center', gap: 12
+ }}>
+ <div style={{
+ fontFamily: 'var(--cth-font-display)', fontSize: 10, lineHeight: '14px',
+ color: 'var(--cth-ink-500)'
+ }}>NO AGENT SELECTED</div>
+ <p style={{ margin: 0, fontSize: 14, textAlign: 'center', color: 'var(--cth-ink-700)' }}>
+ Spawn an agent from the strip below.<br />
+ The terminal and command bar will land here.
+ </p>
+ <PixelButton variant="secondary" size="md" onClick={() => setAddAgentOpen(true)}>
+ <span style={{ display: 'inline-flex', gap: 6, alignItems: 'center' }}>
+ <Icon name="plus" /> add agent
+ </span>
+ </PixelButton>
+ </PixelPanel>
+ )}
+ </div>
+ </div>
+
+ <AgentStrip config={config} />
+
+ {addAgentOpen && (
+ <AddAgentModal onClose={() => setAddAgentOpen(false)} config={config} />
+ )}
+
+ {settingsOpen && (
+ <SettingsModal config={config} onClose={() => setSettingsOpen(false)} />
+ )}
+
+ {quitWarn && (
+ <QuitWarningModal
+ ptyCount={quitWarn.ptyCount}
+ closing={closing}
+ onCancel={() => {
+ if (closing) cancelClosingTime();
+ window.cth.cancelClose();
+ setQuitWarn(null);
+ }}
+ onConfirm={async () => { await window.cth.confirmClose(); }}
+ onClosingTime={startClosingTime}
+ />
+ )}
+
+ {fullscreenAgentId && <FullscreenTerminal />}
+ {fullscreenFilePath && <FullscreenFileEditor />}
+ <TaskDetailOverlay />
+ </div>
+ );
+}
diff --cc src/renderer/src/components/AddAgentModal.tsx
index 401f650c,af36e39d..ba421ce2
--- a/src/renderer/src/components/AddAgentModal.tsx
+++ b/src/renderer/src/components/AddAgentModal.tsx
@@@ -1,472 -1,508 +1,562 @@@
-import { useState } from 'react';
-import { PixelPanel } from './PixelPanel';
-import { PixelButton } from './PixelButton';
-import { SpritePortrait } from './SpritePortrait';
-import { Icon } from './Icon';
-import { useStore, type Agent } from '@/store/store';
-import { OFFICE_CAST, DEFAULT_CHARACTER, type OfficeCharacterName } from '@/scene/office/cast';
-import type { HireManifest } from '@shared/hire';
-import { type AccentColorName } from '@/design/tokens';
-import {
- type AgentProvider,
- type HarnessConfig,
- AGENT_PROVIDER_PRESETS,
- buildSpawnCommand,
- tokenizeCommand,
- modelsForProvider,
- inferAgentProvider,
- providerPreset,
- isClaudeProvider
-} from '@/store/config';
-
-const ACCENTS: AccentColorName[] = ['coral', 'mint', 'sky', 'lemon', 'lilac', 'peach'];
-
-function basename(path: string): string {
- return path.split('/').filter(Boolean).pop() ?? path;
-}
-
-function uniqueId(name: string): string {
- return `${name.toLowerCase().replace(/[^a-z0-9]+/g, '-')}-${Date.now().toString(36)}`;
-}
-
-export interface AddAgentModalProps {
- onClose: () => void;
- config: HarnessConfig;
-}
-
-export function AddAgentModal({ onClose, config }: AddAgentModalProps) {
- const addAgent = useStore(s => s.addAgent);
- // A validated hire manifest (deep link) seeds the form. Manifests NEVER
- // auto-spawn — the human reviews every field (esp. the command) first.
- const pendingHire = useStore(s => s.pendingHire);
-
- const knownCharacter = (c?: string): OfficeCharacterName =>
- (OFFICE_CAST.some(m => m.name === c) ? (c as OfficeCharacterName) : DEFAULT_CHARACTER);
- const knownAccent = (a?: string): AccentColorName =>
- (ACCENTS.includes(a as AccentColorName) ? (a as AccentColorName) : 'sky');
- /** The locally-built spawn command for a manifest: provider preset + model
- * from the LOCAL config builder, with the manifest's validated flags
- * appended. A manifest can never name the binary itself. */
- const hireCommand = (m: HireManifest): string => {
- const prov: AgentProvider = m.provider ?? inferAgentProvider(config.defaultCommand);
- const base = buildSpawnCommand(config, m.model, prov);
- return m.commandFlags?.length ? `${base} ${m.commandFlags.join(' ')}` : base;
- };
-
- // Default provider follows whatever the global default command is (claude
- // unless the user reconfigured it); the model only carries over for Claude.
- const initialProvider = inferAgentProvider(config.defaultCommand);
- const initialModel = isClaudeProvider(initialProvider) ? config.defaultModel : undefined;
-
- const [name, setName] = useState(pendingHire?.name ?? 'Jim');
- const [character, setCharacter] = useState<OfficeCharacterName>(knownCharacter(pendingHire?.character));
- const [accent, setAccent] = useState<AccentColorName>(knownAccent(pendingHire?.accent));
- const [cwd, setCwd] = useState<string>(config.registeredRepos[0] ?? '');
- const [provider, setProvider] = useState<AgentProvider>(pendingHire?.provider ?? initialProvider);
- const [model, setModel] = useState<string | undefined>(
- pendingHire ? pendingHire.model : initialModel
- );
- const [command, setCommand] = useState(
- pendingHire ? hireCommand(pendingHire) : buildSpawnCommand(config, initialModel, initialProvider)
- );
- const [description, setDescription] = useState(pendingHire?.description ?? 'a fresh harness');
- const [hireMeta, setHireMeta] = useState<HireManifest | null>(pendingHire);
-
- // Picking a model rebuilds the command; the command field stays editable for
- // power users (it's the source of truth for the actual spawn).
- const pickModel = (id?: string) => {
- setModel(id);
- setCommand(buildSpawnCommand(config, id, provider));
- };
- // Switching provider resets the model to that CLI's default and rebuilds the
- // command from the provider's preset binary (so Antigravity spawns `agy` and
- // Codex spawns `codex`, not the configured `claude`). For 'custom' we keep the
- // user's typed command rather than blanking it.
- const pickProvider = (id: AgentProvider) => {
- setProvider(id);
- const nextModel = isClaudeProvider(id) ? config.defaultModel : undefined;
- setModel(nextModel);
- if (id === 'custom') {
- setCommand(command.trim() || config.defaultCommand || '');
- return;
- }
- setCommand(buildSpawnCommand(config, nextModel, id));
- };
- const preset = providerPreset(provider);
- const [goal, setGoal] = useState(pendingHire?.goal ?? '');
- const [isolate, setIsolate] = useState(pendingHire?.isolate ?? false);
- const [error, setError] = useState<string | undefined>();
- const [busy, setBusy] = useState(false);
-
- const pickFolder = async () => {
- setError(undefined);
- const res = await window.cth.chooseFolder();
- if (res.ok) setCwd(res.path);
- else if (res.error !== 'cancelled') setError(res.error);
- };
-
- /** Apply an imported manifest to every form field (file/URL import path). */
- const applyManifest = (m: HireManifest) => {
- setHireMeta(m);
- setName(m.name);
- setCharacter(knownCharacter(m.character));
- setAccent(knownAccent(m.accent));
- if (m.provider) setProvider(m.provider);
- setModel(m.model);
- setCommand(hireCommand(m));
- if (m.description) setDescription(m.description);
- setGoal(m.goal ?? '');
- setIsolate(m.isolate ?? false);
- };
-
- const importHire = async () => {
- setError(undefined);
- const res = await window.cth.importHireFile();
- if (res.ok && res.manifest) applyManifest(res.manifest);
- else if (res.error && res.error !== 'cancelled') setError(res.error);
- };
-
- const submit = async () => {
- setError(undefined);
- if (!name.trim()) { setError('Name is required'); return; }
- if (!cwd) { setError('Pick a folder first'); return; }
- if (!command.trim()) { setError('Command is required'); return; }
-
- setBusy(true);
- const id = uniqueId(name);
- const ptyId = `pty-${id}`;
- // Split the editable command field into argv-style pieces for node-pty.
- // Quote-aware so an agy model label like "Gemini 3.1 Pro (High)" — or any
- // auto-mode flags appended to the command — stays one argument.
- const [exe, ...args] = tokenizeCommand(command.trim());
- const spawnRes = await window.cth.spawnPty({
- id: ptyId,
- cwd,
- command: exe,
- provider,
- args,
- cols: 100,
- rows: 30,
- // When set, the main process spawns this agent in its own git worktree.
- isolate,
- // Provision this agent in the hive (memory + mailbox + identity/protocol).
- hive: {
- id,
- name: name.trim(),
- provider,
- cwd,
- role: description.trim() || undefined,
- capabilities: hireMeta?.capabilities
- }
- });
- if (!spawnRes.ok) {
- setBusy(false);
- setError(spawnRes.error ?? 'spawn failed');
- return;
- }
-
- const agent: Agent = {
- id,
- name: name.trim(),
- character,
- accent,
- description: description.trim() || 'a fresh harness',
- project: basename(cwd),
- tmuxTarget: '',
- cwd,
- goal: goal.trim() || undefined,
- status: 'idle',
- action: 'starting up',
- progress: 0,
- currentStation: 'desk',
- ptyId,
- command: command.trim(),
- provider,
- model,
- recentTextTs: Date.now()
- };
- addAgent(agent);
- // Remember the folder for the next hire: promote it to the front of the
- // registeredRepos quick-picks (the modal's default cwd) so back-to-back
- // hires land in the same project without re-picking.
- if (cwd && config.registeredRepos[0] !== cwd) {
- const repos = [cwd, ...config.registeredRepos.filter((r) => r !== cwd)];
- void window.cth.updateConfig({ registeredRepos: repos }).catch(() => { /* best-effort */ });
- }
- // A hire manifest may carry a per-agent token budget — apply it to the
- // same agentTokenCaps map the Command Center card writes.
- if (hireMeta?.tokenCap) {
- void window.cth
- .updateConfig({ agentTokenCaps: { ...(config.agentTokenCaps ?? {}), [id]: hireMeta.tokenCap } })
- .catch(() => { /* best-effort */ });
- }
- setBusy(false);
- onClose();
- };
-
- return (
- <div
- onClick={onClose}
- style={{
- position: 'fixed', inset: 0,
- background: 'rgba(26, 19, 32, 0.6)',
- display: 'flex', alignItems: 'center', justifyContent: 'center',
- zIndex: 100
- }}
- >
- <div onClick={(e) => e.stopPropagation()} style={{ width: 600, maxWidth: '92vw' }}>
- <PixelPanel
- variant="dialog"
- title="ADD AGENT"
- style={{ padding: 16 }}
- noPadding
- >
- <div style={{ display: 'flex', flexDirection: 'column', gap: 12, padding: 16 }}>
- {hireMeta && (
- <div style={{
- padding: '6px 10px',
- background: 'var(--cth-lemon-light, #fdf3cf)',
- boxShadow: 'inset 0 0 0 1px var(--cth-ink-700)',
- fontSize: 13,
- color: 'var(--cth-ink-900)',
- display: 'flex', flexDirection: 'column', gap: 2
- }}>
- <span>
- 📋 hire imported: <strong>{hireMeta.name}</strong>
- {hireMeta.author ? <> · by {hireMeta.author}</> : null}
- </span>
- <span>review every field — especially the command — before spawning.</span>
- </div>
- )}
- <Row label="Name">
- <input
- value={name}
- onChange={(e) => setName(e.target.value)}
- placeholder="Ada"
- style={inputStyle}
- />
- </Row>
-
- <Row label="Folder">
- {config.registeredRepos.length > 0 && (
- <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 6 }}>
- {config.registeredRepos.map((r) => (
- <button
- key={r}
- onClick={() => setCwd(r)}
- title={r}
- style={{
- padding: '3px 8px 1px',
- background: cwd === r ? `var(--cth-${accent}-light)` : 'var(--cth-cream-100)',
- boxShadow: cwd === r
- ? 'inset 0 0 0 2px var(--cth-ink-900)'
- : 'inset 0 0 0 1px var(--cth-ink-700)',
- fontFamily: 'var(--cth-font-ui)',
- fontSize: 13,
- cursor: 'pointer',
- border: 'none'
- }}
- >
- {basename(r)}
- </button>
- ))}
- </div>
- )}
- <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
- <input
- value={cwd}
- onChange={(e) => setCwd(e.target.value)}
- placeholder="/path/to/your/project"
- style={{ ...inputStyle, flex: 1, fontFamily: 'var(--cth-font-mono)', fontSize: 14 }}
- />
- <PixelButton variant="secondary" size="md" onClick={pickFolder}>
- <span style={{ display: 'inline-flex', gap: 4, alignItems: 'center' }}>
- <Icon name="folder" /> pick
- </span>
- </PixelButton>
- </div>
- </Row>
-
- <Row label="Provider">
- <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
- {AGENT_PROVIDER_PRESETS.map((p) => {
- const active = provider === p.id;
- return (
- <button
- key={p.id}
- onClick={() => pickProvider(p.id)}
- title={
- p.id === 'antigravity'
- ? 'Spawn the Antigravity CLI (agy) with a Gemini model'
- : p.id === 'codex'
- ? 'Spawn the Codex CLI (codex) without Claude-only flags'
- : p.id === 'custom'
- ? 'Run any command — no Claude-only flags'
- : p.label
- }
- style={{
- padding: '3px 8px 1px',
- background: active ? `var(--cth-${accent}-light)` : 'var(--cth-cream-100)',
- boxShadow: active
- ? 'inset 0 0 0 2px var(--cth-ink-900)'
- : 'inset 0 0 0 1px var(--cth-ink-700)',
- fontFamily: 'var(--cth-font-ui)', fontSize: 13,
- color: 'var(--cth-ink-900)', cursor: 'pointer', border: 'none'
- }}
- >
- {p.label}
- </button>
- );
- })}
- </div>
- </Row>
-
- {preset.supportsModel && <Row label="Model">
- <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
- {(() => {
- // An imported hire may name a model newer than this picker's
- // hardcoded list (e.g. claude-fable-5). Surface it as a real,
- // selected card instead of leaving the picker looking unset —
- // the command field already carries it either way.
- const known = modelsForProvider(provider);
- return model && !known.some((m) => m.id === model)
- ? [...known, { id: model, label: `${model} (from hire)` }]
- : known;
- })().map((m) => {
- const active = (model ?? '') === (m.id ?? '');
- return (
- <button
- key={m.label}
- onClick={() => pickModel(m.id)}
- title={m.id ?? 'CLI default model'}
- style={{
- padding: '3px 8px 1px',
- background: active ? `var(--cth-${accent}-light)` : 'var(--cth-cream-100)',
- boxShadow: active
- ? 'inset 0 0 0 2px var(--cth-ink-900)'
- : 'inset 0 0 0 1px var(--cth-ink-700)',
- fontFamily: 'var(--cth-font-ui)', fontSize: 13,
- color: 'var(--cth-ink-900)', cursor: 'pointer', border: 'none'
- }}
- >
- {m.label}
- </button>
- );
- })}
- </div>
- </Row>}
-
- <Row label={config.autoMode && preset.autoFlag ? 'Command (auto mode on)' : 'Command'}>
- <input
- value={command}
- onChange={(e) => setCommand(e.target.value)}
- placeholder={
- provider === 'antigravity'
- ? 'agy'
- : provider === 'codex'
- ? 'codex'
- : provider === 'custom'
- ? 'your-agent-cli'
- : 'claude'
- }
- style={{ ...inputStyle, fontFamily: 'var(--cth-font-mono)' }}
- />
- </Row>
-
- <Row label="Description">
- <input
- value={description}
- onChange={(e) => setDescription(e.target.value)}
- placeholder="what is this agent for"
- style={inputStyle}
- />
- </Row>
-
- <Row label="Goal (optional)">
- <textarea
- value={goal}
- onChange={(e) => setGoal(e.target.value)}
- placeholder="long-running directive injected on every prompt"
- rows={2}
- style={{ ...inputStyle, fontFamily: 'var(--cth-font-ui)', resize: 'none' }}
- />
- </Row>
-
- <label style={{ display: 'flex', gap: 8, alignItems: 'center', cursor: 'pointer' }}>
- <input
- type="checkbox"
- checked={isolate}
- onChange={(e) => setIsolate(e.target.checked)}
- style={{ width: 16, height: 16, cursor: 'pointer' }}
- />
- <span style={{ fontFamily: 'var(--cth-font-ui)', fontSize: 14, color: 'var(--cth-ink-900)' }}>
- Git isolation (own worktree)
- </span>
- </label>
-
- <Row label="Character">
- <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
- {OFFICE_CAST.map(c => (
- <button
- key={c.name}
- onClick={() => { setCharacter(c.name); setName(c.displayName); }}
- title={c.blurb}
- style={{
- padding: 4,
- background: character === c.name ? `var(--cth-${accent}-light)` : 'var(--cth-cream-100)',
- boxShadow: character === c.name
- ? 'inset 0 0 0 2px var(--cth-ink-900)'
- : 'inset 0 0 0 1px var(--cth-ink-700)',
- cursor: 'pointer',
- display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2,
- border: 'none', width: 56
- }}
- >
- <div style={{ width: 44, height: 56, display: 'flex', alignItems: 'flex-end', justifyContent: 'center', overflow: 'hidden' }}>
- <SpritePortrait character={c.name} scale={2} />
- </div>
- <span style={{ fontSize: 11, color: 'var(--cth-ink-700)' }}>{c.displayName}</span>
- </button>
- ))}
- </div>
- </Row>
-
- <Row label="Color">
- <div style={{ display: 'flex', gap: 6 }}>
- {ACCENTS.map(a => (
- <button
- key={a}
- onClick={() => setAccent(a)}
- style={{
- width: 32, height: 32,
- background: `var(--cth-${a})`,
- boxShadow: accent === a
- ? 'inset 0 0 0 2px var(--cth-ink-900), 0 0 0 2px var(--cth-ink-900)'
- : 'inset 0 0 0 1px var(--cth-ink-900)',
- cursor: 'pointer',
- border: 'none'
- }}
- aria-label={a}
- />
- ))}
- </div>
- </Row>
-
- {error && (
- <div style={{
- padding: '6px 10px',
- background: 'var(--cth-coral-light)',
- boxShadow: 'inset 0 0 0 1px var(--cth-coral)',
- fontSize: 14,
- color: 'var(--cth-ink-900)'
- }}>
- {error}
- </div>
- )}
-
- <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 4 }}>
- <PixelButton variant="secondary" size="md" onClick={importHire} disabled={busy} title="Import a hire manifest (.json)">
- import hire…
- </PixelButton>
- <div style={{ flex: 1 }} />
- <PixelButton variant="ghost" size="md" onClick={onClose} disabled={busy}>cancel</PixelButton>
- <PixelButton variant="primary" size="md" onClick={submit} disabled={busy}>
- {busy ? 'spawning...' : 'spawn'}
- </PixelButton>
- </div>
- </div>
- </PixelPanel>
- </div>
- </div>
- );
-}
-
-const inputStyle: React.CSSProperties = {
- width: '100%',
- padding: '6px 8px 4px',
- background: 'var(--cth-paper-100)',
- border: 'none',
- boxShadow: 'inset 0 0 0 1px var(--cth-ink-700)',
- fontFamily: 'var(--cth-font-ui)',
- fontSize: 16,
- color: 'var(--cth-ink-900)',
- outline: 'none'
-};
-
-function Row({ label, children }: { label: string; children: React.ReactNode }) {
- return (
- <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
- <span style={{
- fontFamily: 'var(--cth-font-display)',
- fontSize: 8, lineHeight: '12px',
- color: 'var(--cth-ink-700)',
- textTransform: 'uppercase'
- }}>{label}</span>
- {children}
- </label>
- );
-}
+import { useState } from 'react';
+import { PixelPanel } from './PixelPanel';
+import { PixelButton } from './PixelButton';
+import { SpritePortrait } from './SpritePortrait';
+import { Icon } from './Icon';
+import { useStore, type Agent } from '@/store/store';
+import { OFFICE_CAST, DEFAULT_CHARACTER, type OfficeCharacterName } from '@/scene/office/cast';
+import { type AccentColorName } from '@/design/tokens';
++import type { HireManifest } from '@shared/hire';
+import {
+ type AgentProvider,
+ type HarnessConfig,
+ AGENT_PROVIDER_PRESETS,
+ buildSpawnCommand,
+ tokenizeCommand,
+ modelsForProvider,
+ inferAgentProvider,
+ providerPreset,
+ isClaudeProvider
+} from '@/store/config';
+
+const ACCENTS: AccentColorName[] = ['coral', 'mint', 'sky', 'lemon', 'lilac', 'peach'];
+
+function basename(path: string): string {
+ return path.split('/').filter(Boolean).pop() ?? path;
+}
+
+function uniqueId(name: string): string {
+ return `${name.toLowerCase().replace(/[^a-z0-9]+/g, '-')}-${Date.now().toString(36)}`;
+}
+
+export interface AddAgentModalProps {
+ onClose: () => void;
+ config: HarnessConfig;
+}
+
+export function AddAgentModal({ onClose, config }: AddAgentModalProps) {
+ const addAgent = useStore(s => s.addAgent);
++ // A validated hire manifest (deep link / file import) seeds the form. Manifests
++ // NEVER auto-spawn — the human reviews every field (esp. the command) first.
++ const pendingHire = useStore(s => s.pendingHire);
++
++ const knownCharacter = (c?: string): OfficeCharacterName =>
++ (OFFICE_CAST.some(m => m.name === c) ? (c as OfficeCharacterName) : DEFAULT_CHARACTER);
++ const knownAccent = (a?: string): AccentColorName =>
++ (ACCENTS.includes(a as AccentColorName) ? (a as AccentColorName) : 'sky');
++ /** The locally-built spawn command for a manifest: provider preset + model
++ * from the LOCAL config builder, with the manifest's validated flags
++ * appended. A manifest can never name the binary itself. */
++ const hireCommand = (m: HireManifest): string => {
++ const prov: AgentProvider = m.provider ?? inferAgentProvider(config.defaultCommand);
++ const base = buildSpawnCommand(config, m.model, prov);
++ return m.commandFlags?.length ? `${base} ${m.commandFlags.join(' ')}` : base;
++ };
+
+ // Default provider follows whatever the global default command is (claude
+ // unless the user reconfigured it); the model only carries over for Claude.
+ const initialProvider = inferAgentProvider(config.defaultCommand);
+ const initialModel = isClaudeProvider(initialProvider) ? config.defaultModel : undefined;
+
- const [name, setName] = useState('Jim');
- const [character, setCharacter] = useState<OfficeCharacterName>(DEFAULT_CHARACTER);
- const [accent, setAccent] = useState<AccentColorName>('sky');
++ const [name, setName] = useState(pendingHire?.name ?? 'Jim');
++ const [character, setCharacter] = useState<OfficeCharacterName>(knownCharacter(pendingHire?.character));
++ const [accent, setAccent] = useState<AccentColorName>(knownAccent(pendingHire?.accent));
+ const [cwd, setCwd] = useState<string>(config.registeredRepos[0] ?? '');
- const [provider, setProvider] = useState<AgentProvider>(initialProvider);
- const [model, setModel] = useState<string | undefined>(initialModel);
- const [command, setCommand] = useState(buildSpawnCommand(config, initialModel, initialProvider));
- const [description, setDescription] = useState('a fresh harness');
++ const [provider, setProvider] = useState<AgentProvider>(pendingHire?.provider ?? initialProvider);
++ const [model, setModel] = useState<string | undefined>(
++ pendingHire ? pendingHire.model : initialModel
++ );
++ const [command, setCommand] = useState(
++ pendingHire ? hireCommand(pendingHire) : buildSpawnCommand(config, initialModel, initialProvider)
++ );
++ const [description, setDescription] = useState(pendingHire?.description ?? 'a fresh harness');
++ const [hireMeta, setHireMeta] = useState<HireManifest | null>(pendingHire);
+
+ // Picking a model rebuilds the command; the command field stays editable for
+ // power users (it's the source of truth for the actual spawn).
+ const pickModel = (id?: string) => {
+ setModel(id);
+ setCommand(buildSpawnCommand(config, id, provider));
+ };
+ // Switching provider resets the model to that CLI's default and rebuilds the
+ // command from the provider's preset binary (so Antigravity spawns `agy` and
+ // Codex spawns `codex`, not the configured `claude`). For 'custom' we keep the
+ // user's typed command rather than blanking it.
+ const pickProvider = (id: AgentProvider) => {
+ setProvider(id);
+ const nextModel = isClaudeProvider(id) ? config.defaultModel : undefined;
+ setModel(nextModel);
+ if (id === 'custom') {
+ setCommand(command.trim() || config.defaultCommand || '');
+ return;
+ }
+ setCommand(buildSpawnCommand(config, nextModel, id));
+ };
+ const preset = providerPreset(provider);
- const [goal, setGoal] = useState('');
- const [isolate, setIsolate] = useState(false);
++ const [goal, setGoal] = useState(pendingHire?.goal ?? '');
++ const [isolate, setIsolate] = useState(pendingHire?.isolate ?? false);
+ // #2 — optional Claude session id to continue. When set, the spawn seeds that
+ // session's transcript into the cwd's project dir and launches `--resume`.
+ const [resumeSessionId, setResumeSessionId] = useState('');
+ const resuming = resumeSessionId.trim().length > 0;
+ // Note shown when the folder was auto-filled from the pasted session id.
+ const [folderNote, setFolderNote] = useState<string | undefined>();
+ const [error, setError] = useState<string | undefined>();
+ const [busy, setBusy] = useState(false);
+
+ // Zero-step resume: when a session id is entered, look up the cwd it originally
+ // ran in (from the transcript) and pre-fill the Folder so the user doesn't have
+ // to find the worktree. They can still override the folder afterwards. Runs on
+ // blur so we don't hit the resolver on every keystroke.
+ const resolveFolderFromSession = async () => {
+ const sid = resumeSessionId.trim();
+ if (!sid) { setFolderNote(undefined); return; }
+ const resolved = await window.cth.resolveSessionCwd(sid);
+ if (resolved) { setCwd(resolved); setFolderNote(`folder set from session: ${resolved}`); }
+ else setFolderNote(undefined);
+ };
+
+ const pickFolder = async () => {
+ setError(undefined);
+ const res = await window.cth.chooseFolder();
+ if (res.ok) setCwd(res.path);
+ else if (res.error !== 'cancelled') setError(res.error);
+ };
+
++ /** Apply an imported manifest to every form field (file import path). The
++ * command is rebuilt locally from the provider preset + validated flags — a
++ * manifest can never inject the spawn binary. Import never spawns. */
++ const applyManifest = (m: HireManifest) => {
++ setHireMeta(m);
++ setName(m.name);
++ setCharacter(knownCharacter(m.character));
++ setAccent(knownAccent(m.accent));
++ if (m.provider) setProvider(m.provider);
++ setModel(m.model);
++ setCommand(hireCommand(m));
++ if (m.description) setDescription(m.description);
++ setGoal(m.goal ?? '');
++ setIsolate(m.isolate ?? false);
++ };
++
++ const importHire = async () => {
++ setError(undefined);
++ const res = await window.cth.importHireFile();
++ if (res.ok && res.manifest) applyManifest(res.manifest);
++ else if (res.error && res.error !== 'cancelled') setError(res.error);
++ };
++
+ const submit = async () => {
+ setError(undefined);
+ if (!name.trim()) { setError('Name is required'); return; }
+ if (!cwd) { setError('Pick a folder first'); return; }
+ if (!command.trim()) { setError('Command is required'); return; }
+
+ setBusy(true);
+ const id = uniqueId(name);
+ const ptyId = `pty-${id}`;
+ // Split the editable command field into argv-style pieces for node-pty.
+ // Quote-aware so an agy model label like "Gemini 3.1 Pro (High)" — or any
+ // auto-mode flags appended to the command — stays one argument.
+ const [exe, ...args] = tokenizeCommand(command.trim());
+ const spawnRes = await window.cth.spawnPty({
+ id: ptyId,
+ cwd,
+ command: exe,
+ provider,
+ args,
+ cols: 100,
+ rows: 30,
+ // When set, the main process spawns this agent in its own git worktree.
+ // Forced OFF when resuming a session — `--resume` needs the real cwd's
+ // transcript, not a fresh worktree with a different (empty) project dir.
+ isolate: resuming ? false : isolate,
+ // #2 — continue an existing Claude session in this agent's cwd.
+ resumeSessionId: resuming ? resumeSessionId.trim() : undefined,
+ // Provision this agent in the hive (memory + mailbox + identity/protocol).
+ hive: {
+ id,
+ name: name.trim(),
+ provider,
+ cwd,
- role: description.trim() || undefined
++ role: description.trim() || undefined,
++ // A hire manifest may carry validated capability tags (routing hints).
++ capabilities: hireMeta?.capabilities
+ }
+ });
+ if (!spawnRes.ok) {
+ setBusy(false);
+ setError(spawnRes.error ?? 'spawn failed');
+ return;
+ }
+ // #2 — the requested resume session id wasn't found anywhere; main fell back
+ // to a fresh session. Don't block the spawn, but make it visible.
+ if (resuming && spawnRes.resumeNotFound) {
+ console.warn(`[add-agent] resume session "${resumeSessionId.trim()}" not found — started a fresh session`);
+ }
+
+ const agent: Agent = {
+ id,
+ name: name.trim(),
+ character,
+ accent,
+ description: description.trim() || 'a fresh harness',
+ project: basename(cwd),
+ tmuxTarget: '',
+ cwd,
+ goal: goal.trim() || undefined,
+ status: 'idle',
+ action: resuming && spawnRes.resumeNotFound ? 'session not found — fresh start' : 'starting up',
+ progress: 0,
+ currentStation: 'desk',
+ ptyId,
+ command: command.trim(),
+ provider,
+ model,
+ // Persist the resolved worktree path (set only when isolation provisioned
+ // one) so a restart can re-enter this exact worktree — see restoreTeam.
+ worktreePath: spawnRes.worktreePath,
+ recentTextTs: Date.now()
+ };
+ addAgent(agent);
++ // Remember the folder for the next hire: promote it to the front of the
++ // registeredRepos quick-picks (the modal's default cwd) so back-to-back
++ // hires land in the same project without re-picking.
++ if (cwd && config.registeredRepos[0] !== cwd) {
++ const repos = [cwd, ...config.registeredRepos.filter((r) => r !== cwd)];
++ void window.cth.updateConfig({ registeredRepos: repos }).catch(() => { /* best-effort */ });
++ }
++ // A hire manifest may carry a per-agent token budget — apply it to the
++ // same agentTokenCaps map the Command Center card writes.
++ if (hireMeta?.tokenCap) {
++ void window.cth
++ .updateConfig({ agentTokenCaps: { ...(config.agentTokenCaps ?? {}), [id]: hireMeta.tokenCap } })
++ .catch(() => { /* best-effort */ });
++ }
+ setBusy(false);
+ onClose();
+ };
+
+ return (
+ <div
+ onClick={onClose}
+ style={{
+ position: 'fixed', inset: 0,
+ background: 'rgba(26, 19, 32, 0.6)',
+ display: 'flex', alignItems: 'center', justifyContent: 'center',
+ zIndex: 100
+ }}
+ >
+ <div onClick={(e) => e.stopPropagation()} style={{ width: 600, maxWidth: '92vw' }}>
+ <PixelPanel
+ variant="dialog"
+ title="ADD AGENT"
+ style={{ padding: 16 }}
+ noPadding
+ >
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 12, padding: 16 }}>
++ {hireMeta && (
++ <div style={{
++ padding: '6px 10px',
++ background: 'var(--cth-lemon-light, #fdf3cf)',
++ boxShadow: 'inset 0 0 0 1px var(--cth-ink-700)',
++ fontSize: 13,
++ color: 'var(--cth-ink-900)',
++ display: 'flex', flexDirection: 'column', gap: 2
++ }}>
++ <span>
++ 📋 hire imported: <strong>{hireMeta.name}</strong>
++ {hireMeta.author ? <> · by {hireMeta.author}</> : null}
++ </span>
++ <span>review every field — especially the command — before spawning.</span>
++ </div>
++ )}
+ <Row label="Name">
+ <input
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder="Ada"
+ style={inputStyle}
+ />
+ </Row>
+
+ <Row label="Folder">
+ {config.registeredRepos.length > 0 && (
+ <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 6 }}>
+ {config.registeredRepos.map((r) => (
+ <button
+ key={r}
+ onClick={() => setCwd(r)}
+ title={r}
+ style={{
+ padding: '3px 8px 1px',
+ background: cwd === r ? `var(--cth-${accent}-light)` : 'var(--cth-cream-100)',
+ boxShadow: cwd === r
+ ? 'inset 0 0 0 2px var(--cth-ink-900)'
+ : 'inset 0 0 0 1px var(--cth-ink-700)',
+ fontFamily: 'var(--cth-font-ui)',
+ fontSize: 13,
+ cursor: 'pointer',
+ border: 'none'
+ }}
+ >
+ {basename(r)}
+ </button>
+ ))}
+ </div>
+ )}
+ <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
+ <input
+ value={cwd}
+ onChange={(e) => setCwd(e.target.value)}
+ placeholder="/path/to/your/project"
+ style={{ ...inputStyle, flex: 1, fontFamily: 'var(--cth-font-mono)', fontSize: 14 }}
+ />
+ <PixelButton variant="secondary" size="md" onClick={pickFolder}>
+ <span style={{ display: 'inline-flex', gap: 4, alignItems: 'center' }}>
+ <Icon name="folder" /> pick
+ </span>
+ </PixelButton>
+ </div>
+ </Row>
+
+ <Row label="Provider">
+ <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
+ {AGENT_PROVIDER_PRESETS.map((p) => {
+ const active = provider === p.id;
+ return (
+ <button
+ key={p.id}
+ onClick={() => pickProvider(p.id)}
+ title={
+ p.id === 'antigravity'
+ ? 'Spawn the Antigravity CLI (agy) with a Gemini model'
+ : p.id === 'codex'
+ ? 'Spawn the Codex CLI (codex) without Claude-only flags'
+ : p.id === 'custom'
+ ? 'Run any command — no Claude-only flags'
+ : p.label
+ }
+ style={{
+ padding: '3px 8px 1px',
+ background: active ? `var(--cth-${accent}-light)` : 'var(--cth-cream-100)',
+ boxShadow: active
+ ? 'inset 0 0 0 2px var(--cth-ink-900)'
+ : 'inset 0 0 0 1px var(--cth-ink-700)',
+ fontFamily: 'var(--cth-font-ui)', fontSize: 13,
+ color: 'var(--cth-ink-900)', cursor: 'pointer', border: 'none'
+ }}
+ >
+ {p.label}
+ </button>
+ );
+ })}
+ </div>
+ </Row>
+
+ {preset.supportsModel && <Row label="Model">
+ <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
- {modelsForProvider(provider).map((m) => {
++ {(() => {
++ // An imported hire may name a model newer than this picker's
++ // hardcoded list (e.g. claude-fable-5). Surface it as a real,
++ // selected card instead of leaving the picker looking unset —
++ // the command field already carries it either way.
++ const known = modelsForProvider(provider);
++ return model && !known.some((m) => m.id === model)
++ ? [...known, { id: model, label: `${model} (from hire)` }]
++ : known;
++ })().map((m) => {
+ const active = (model ?? '') === (m.id ?? '');
+ return (
+ <button
+ key={m.label}
+ onClick={() => pickModel(m.id)}
+ title={m.id ?? 'CLI default model'}
+ style={{
+ padding: '3px 8px 1px',
+ background: active ? `var(--cth-${accent}-light)` : 'var(--cth-cream-100)',
+ boxShadow: active
+ ? 'inset 0 0 0 2px var(--cth-ink-900)'
+ : 'inset 0 0 0 1px var(--cth-ink-700)',
+ fontFamily: 'var(--cth-font-ui)', fontSize: 13,
+ color: 'var(--cth-ink-900)', cursor: 'pointer', border: 'none'
+ }}
+ >
+ {m.label}
+ </button>
+ );
+ })}
+ </div>
+ </Row>}
+
+ <Row label={config.autoMode && preset.autoFlag ? 'Command (auto mode on)' : 'Command'}>
+ <input
+ value={command}
+ onChange={(e) => setCommand(e.target.value)}
+ placeholder={
+ provider === 'antigravity'
+ ? 'agy'
+ : provider === 'codex'
+ ? 'codex'
+ : provider === 'custom'
+ ? 'your-agent-cli'
+ : 'claude'
+ }
+ style={{ ...inputStyle, fontFamily: 'var(--cth-font-mono)' }}
+ />
+ </Row>
+
+ <Row label="Description">
+ <input
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ placeholder="what is this agent for"
+ style={inputStyle}
+ />
+ </Row>
+
+ <Row label="Goal (optional)">
+ <textarea
+ value={goal}
+ onChange={(e) => setGoal(e.target.value)}
+ placeholder="long-running directive injected on every prompt"
+ rows={2}
+ style={{ ...inputStyle, fontFamily: 'var(--cth-font-ui)', resize: 'none' }}
+ />
+ </Row>
+
+ <Row label="Resume session ID (optional)">
+ <input
+ value={resumeSessionId}
+ onChange={(e) => { setResumeSessionId(e.target.value); setFolderNote(undefined); }}
+ onBlur={resolveFolderFromSession}
+ placeholder="paste a Claude session id to continue its conversation"
+ style={{ ...inputStyle, fontFamily: 'var(--cth-font-mono)', fontSize: 14 }}
+ />
+ {folderNote && (
+ <span style={{ fontFamily: 'var(--cth-font-ui)', fontSize: 12, color: 'var(--cth-mint, var(--cth-ink-700))' }}>
+ {folderNote}
+ </span>
+ )}
+ {resuming && (
+ <span style={{ fontFamily: 'var(--cth-font-ui)', fontSize: 12, color: 'var(--cth-ink-700)' }}>
+ Will resume this session in the chosen folder (git isolation disabled).
+ </span>
+ )}
+ </Row>
+
+ <label style={{ display: 'flex', gap: 8, alignItems: 'center', cursor: resuming ? 'not-allowed' : 'pointer', opacity: resuming ? 0.5 : 1 }}>
+ <input
+ type="checkbox"
+ checked={resuming ? false : isolate}
+ disabled={resuming}
+ onChange={(e) => setIsolate(e.target.checked)}
+ style={{ width: 16, height: 16, cursor: resuming ? 'not-allowed' : 'pointer' }}
+ />
+ <span style={{ fontFamily: 'var(--cth-font-ui)', fontSize: 14, color: 'var(--cth-ink-900)' }}>
+ Git isolation (own worktree)
+ </span>
+ </label>
+
+ <Row label="Character">
+ <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
+ {OFFICE_CAST.map(c => (
+ <button
+ key={c.name}
+ onClick={() => { setCharacter(c.name); setName(c.displayName); }}
+ title={c.blurb}
+ style={{
+ padding: 4,
+ background: character === c.name ? `var(--cth-${accent}-light)` : 'var(--cth-cream-100)',
+ boxShadow: character === c.name
+ ? 'inset 0 0 0 2px var(--cth-ink-900)'
+ : 'inset 0 0 0 1px var(--cth-ink-700)',
+ cursor: 'pointer',
+ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2,
+ border: 'none', width: 56
+ }}
+ >
+ <div style={{ width: 44, height: 56, display: 'flex', alignItems: 'flex-end', justifyContent: 'center', overflow: 'hidden' }}>
+ <SpritePortrait character={c.name} scale={2} />
+ </div>
+ <span style={{ fontSize: 11, color: 'var(--cth-ink-700)' }}>{c.displayName}</span>
+ </button>
+ ))}
+ </div>
+ </Row>
+
+ <Row label="Color">
+ <div style={{ display: 'flex', gap: 6 }}>
+ {ACCENTS.map(a => (
+ <button
+ key={a}
+ onClick={() => setAccent(a)}
+ style={{
+ width: 32, height: 32,
+ background: `var(--cth-${a})`,
+ boxShadow: accent === a
+ ? 'inset 0 0 0 2px var(--cth-ink-900), 0 0 0 2px var(--cth-ink-900)'
+ : 'inset 0 0 0 1px var(--cth-ink-900)',
+ cursor: 'pointer',
+ border: 'none'
+ }}
+ aria-label={a}
+ />
+ ))}
+ </div>
+ </Row>
+
+ {error && (
+ <div style={{
+ padding: '6px 10px',
+ background: 'var(--cth-coral-light)',
+ boxShadow: 'inset 0 0 0 1px var(--cth-coral)',
+ fontSize: 14,
+ color: 'var(--cth-ink-900)'
+ }}>
+ {error}
+ </div>
+ )}
+
+ <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 4 }}>
++ <PixelButton variant="secondary" size="md" onClick={importHire} disabled={busy} title="Import a hire manifest (.json)">
++ import hire…
++ </PixelButton>
++ <div style={{ flex: 1 }} />
+ <PixelButton variant="ghost" size="md" onClick={onClose} disabled={busy}>cancel</PixelButton>
+ <PixelButton variant="primary" size="md" onClick={submit} disabled={busy}>
+ {busy ? 'spawning...' : 'spawn'}
+ </PixelButton>
+ </div>
+ </div>
+ </PixelPanel>
+ </div>
+ </div>
+ );
+}
+
+const inputStyle: React.CSSProperties = {
+ width: '100%',
+ padding: '6px 8px 4px',
+ background: 'var(--cth-paper-100)',
+ border: 'none',
+ boxShadow: 'inset 0 0 0 1px var(--cth-ink-700)',
+ fontFamily: 'var(--cth-font-ui)',
+ fontSize: 16,
+ color: 'var(--cth-ink-900)',
+ outline: 'none'
+};
+
+function Row({ label, children }: { label: string; children: React.ReactNode }) {
+ return (
+ <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
+ <span style={{
+ fontFamily: 'var(--cth-font-display)',
+ fontSize: 8, lineHeight: '12px',
+ color: 'var(--cth-ink-700)',
+ textTransform: 'uppercase'
+ }}>{label}</span>
+ {children}
+ </label>
+ );
+}
diff --cc src/renderer/src/store/store.ts
index 4c0f26c9,5fd5803e..fc039f48
--- a/src/renderer/src/store/store.ts
+++ b/src/renderer/src/store/store.ts
@@@ -1,551 -1,544 +1,557 @@@
-import { create } from 'zustand';
-import type { AccentColorName } from '@/design/tokens';
-import type { OfficeCharacterName } from '@/scene/office/cast';
-import type { StatusKind } from '@/components/PixelBadge';
-import type { AgentProvider } from '@shared/agentProvider';
-import type { HireManifest } from '@shared/hire';
-
-export type ToolKind =
- | 'Read' | 'Edit' | 'Write' | 'Bash' | 'WebFetch' | 'WebSearch'
- | 'Grep' | 'Glob' | 'TodoWrite' | 'MCP';
-
-export type StationKind =
- | 'shelf' | 'terminal' | 'web' | 'board' | 'mailbox' | 'mcp' | 'desk';
-
-export interface BlockReason {
- summary: string; // short headline shown on banner
- detail: string; // longer explanation
- command?: string; // verbatim command awaiting confirmation, if any
- actions: Array<{
- label: string;
- kind: 'approve' | 'deny' | 'neutral';
- /** what we'd send to the tmux pane on click */
- send?: string;
- }>;
-}
-
-export interface Agent {
- id: string;
- name: string;
- /** which Office character represents this agent on the floor */
- character: OfficeCharacterName;
- accent: AccentColorName;
- /** persistent short context — what is this agent for (shown on the floor) */
- description: string;
- project: string;
- /** legacy field — populated only for the seeded mock agents */
- tmuxTarget: string;
- cwd: string;
- goal?: string;
- status: StatusKind;
- action: string;
- progress: number;
- currentStation?: StationKind;
- carrying?: ToolKind;
- /** latest assistant message, streamed character-by-character in the sidebar */
- recentAssistantText?: string;
- /** epoch ms — used to drive the typewriter so identical strings still re-stream */
- recentTextTs?: number;
- /** populated when status === 'blocked' */
- blockReason?: BlockReason;
- /** present iff this agent has a real PTY in the main process */
- ptyId?: string;
- /** the command being run in the PTY (e.g. 'claude' or 'agy') */
- command?: string;
- /** which agent CLI preset owns this PTY recipe; drives the model picker +
- * spawn flags. Defaults to 'claude' when unset (legacy agents / inferred
- * from command). */
- provider?: AgentProvider;
- /** the model this agent runs on (e.g. 'claude-sonnet-4-6[1m]' or 'gemini-3-pro');
- * drives the model selector + the --model arg used when (re)spawning the agent */
- model?: string;
- /** the last prompt the user submitted to this agent in Claude Code —
- * shown on the floor as a card above the seated avatar */
- lastPrompt?: string;
- /** the orchestrator ("god") agent — seated in Michael's room, runs the floor */
- isGod?: boolean;
- /** Michael's prep assistant — send-only; enriches prompts and forwards them to
- * the god. Excluded from broadcast fan-out and from the restorable-dead sweep. */
- isAssistant?: boolean;
- /** When git isolation is enabled, the dedicated worktree path the agent runs
- * in (its own `agent/<id>` branch); undefined for shared-cwd agents. */
- worktreePath?: string;
- /** Live context size of the agent's Claude session (tokens), polled from its
- * transcript. Drives the context gauge on the agent card. */
- contextTokens?: number;
- /** The context-window limit assumed for this agent's model (tokens). */
- contextLimit?: number;
- /** True once this agent's terminal was closed. Archived agents are retained
- * (in the store's `archivedAgents` list + the hive registry) but flagged and
- * kept off the floor; only live-PTY agents are 'active'. */
- archived?: boolean;
-}
-
-export interface FeedEntry {
- agentId: string;
- text: string;
- ts: number;
-}
-
-/** A message the user has parked for an agent while its terminal was busy.
- * Queued messages are drained one at a time when the agent next goes idle (see
- * useHive's flush loop). */
-export interface QueuedMessage {
- id: string;
- text: string;
- /** epoch ms the message was queued — drives ordering and the "queued 2m ago" hint */
- ts: number;
- /** Slack-originated: thread coordinates so the office can reply in-thread. */
- slack?: { channel: string; thread_ts: string };
- /** Optional override for the text actually typed into the agent's PTY. When set,
- * the drain submits THIS instead of `text`, while UI/card surfaces keep using
- * `text`. Used by Slack-origin work to carry the autonomy preamble to god's
- * prompt without polluting the human-readable kanban card title (= raw `text`). */
- instruction?: string;
-}
-
-export type SidebarTab = 'terminal' | 'files' | 'messages' | 'traces';
-
-/** Lifecycle of the god agent ("Michael") bootstrap on launch.
- * 'booting' until his PTY is confirmed live, then 'ready' (or 'failed' if the
- * spawn errored). The empty-floor UI shows a loader while 'booting' so users
- * don't see the "add agent" prompt before Michael has clocked in. */
-export type GodStatus = 'booting' | 'ready' | 'failed';
-
-interface State {
- agents: Agent[];
- /** Agents whose terminal was closed — retained + flagged, kept off the active
- * roster/floor. The hive registry retains them durably; this mirrors them for
- * the renderer's "Archived" view. */
- archivedAgents: Agent[];
- /** Workers from the previous session whose terminal died with the app (quit /
- * crash). Kept with their full spawn recipe (id, cwd, model, command) so the
- * user can one-click respawn them with the SAME agent id — memory, inbox and
- * registry entry reattach by themselves. God/assistant are excluded (they
- * auto-respawn). */
- restorableAgents: Agent[];
- selectedId: string | null;
- feeds: Record<string, string[]>;
- addAgentOpen: boolean;
- /** A validated hire manifest waiting to pre-fill the Add-Agent modal. */
- pendingHire: HireManifest | null;
- fullscreenAgentId: string | null;
- fullscreenFilePath: string | null;
- sidebarWidth: number;
- sidebarTab: SidebarTab;
- godStatus: GodStatus;
- /** Per-agent outgoing message queue (agent id → messages awaiting delivery).
- * Lets the user keep "talking" to a busy agent: messages park here and are
- * drained to the terminal one-by-one once the agent is free. */
- messageQueues: Record<string, QueuedMessage[]>;
- /** Per-agent tool-call count this session — a lightweight activity/usage proxy
- * shown in the command center (interactive sessions don't expose billed $). */
- toolCounts: Record<string, number>;
- bumpToolCount: (id: string) => void;
- setGodStatus: (status: GodStatus) => void;
- select: (id: string) => void;
- updateAgent: (id: string, patch: Partial<Agent>) => void;
- pushFeed: (id: string, line: string) => void;
- addAgent: (agent: Agent) => void;
- removeAgent: (id: string) => void;
- /** Archive an agent (its terminal was closed): move it from the active roster
- * into `archivedAgents` with its PTY cleared. Retained + flagged, NOT deleted. */
- archiveAgent: (id: string) => void;
- /** Permanently forget an archived agent (drops the renderer entry only; the
- * hive registry keeps its record). */
- removeArchivedAgent: (id: string) => void;
- /** Drop one agent from the restorable list (it was respawned or dismissed). */
- removeRestorableAgent: (id: string) => void;
- /** One-shot request to open a Command-Center tab (e.g. clicking the office
- * task board → 'tasks'). `seq` makes repeated identical requests distinct. */
- ccTabRequest: { tab: string; seq: number } | null;
- requestCommandCenterTab: (tab: string) => void;
- /** The task whose detail overlay is open (rendered app-wide over the office
- * floor — the card content grows: contracts, deps, the human Q&A trail). */
- taskDetailId: string | null;
- openTaskDetail: (id: string) => void;
- closeTaskDetail: () => void;
- /** One-shot prefill for the Command Center's dispatch box (a task detail's
- * "assign" from anywhere in the app). seq-keyed like ccTabRequest. */
- dispatchSeedRequest: { text: string; seq: number } | null;
- requestDispatchSeed: (text: string) => void;
- /** Unsent ASK ME answer drafts, keyed by task id — so switching tabs (which
- * unmounts the ask-me view) doesn't eat a half-typed answer. */
- answerDrafts: Record<string, string>;
- setAnswerDraft: (taskId: string, text: string) => void;
- /** Unsent composer drafts, per agent — so switching agents (which remounts the
- * composer) doesn't eat what the user was typing. */
- drafts: Record<string, string>;
- setDraft: (agentId: string, text: string) => 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`). */
- enqueueMessage: (agentId: string, text: string, meta?: { slack?: { channel: string; thread_ts: string }; instruction?: string }) => void;
- /** Drop a single queued message (user removed it, or it was just delivered). */
- removeQueuedMessage: (agentId: string, messageId: string) => void;
- /** Clear an agent's entire pending queue. */
- clearQueue: (agentId: string) => void;
- setAddAgentOpen: (open: boolean) => void;
- setPendingHire: (m: HireManifest | null) => void;
- setFullscreen: (id: string | null) => void;
- setFullscreenFile: (path: string | null) => void;
- setSidebarWidth: (px: number) => void;
- setSidebarTab: (tab: SidebarTab) => void;
- /** Drop persisted agents whose PTY is no longer alive in the main process.
- * Called once at startup so a renderer reload (e.g. after the laptop sleeps)
- * restores still-running agents and only removes truly-dead ones. */
- reconcileWithLivePtys: (livePtyIds: string[]) => void;
-}
-
-const LS_SIDEBAR_WIDTH = 'cth.sidebarWidth';
-const LS_SIDEBAR_TAB = 'cth.sidebarTab';
-const LS_AGENTS = 'cth.agents';
-const LS_ARCHIVED = 'cth.archivedAgents';
-const LS_RESTORABLE = 'cth.restorableAgents';
-const LS_SELECTED = 'cth.selectedId';
-const LS_QUEUES = 'cth.messageQueues';
-
-// Fields that are large or transient — not worth persisting across reloads.
-// contextTokens/contextLimit describe a LIVE session; persisting them showed a
-// dead session's context gauge after a restart until the poll caught up.
-type PersistedAgent = Omit<Agent, 'recentAssistantText' | 'recentTextTs' | 'blockReason' | 'contextTokens' | 'contextLimit'>;
-
-function persistAgents(agents: Agent[], selectedId: string | null): void {
- try {
- const slim: PersistedAgent[] = agents.map(({ recentAssistantText, recentTextTs, blockReason, contextTokens, contextLimit, ...rest }) => {
- void recentAssistantText; void recentTextTs; void blockReason; void contextTokens; void contextLimit;
- return rest;
- });
- window.localStorage.setItem(LS_AGENTS, JSON.stringify(slim));
- window.localStorage.setItem(LS_SELECTED, selectedId ?? '');
- } catch { /* noop */ }
-}
-
-function loadPersistedAgents(): Agent[] {
- try {
- const raw = window.localStorage.getItem(LS_AGENTS);
- if (!raw) return [];
- const parsed = JSON.parse(raw) as PersistedAgent[];
- if (!Array.isArray(parsed)) return [];
- // Reset volatile run-state; the PTY stream / mock loop will repopulate it.
- return parsed.map((a) => ({
- ...a,
- progress: 0,
- status: 'idle',
- action: 'reconnecting…',
- currentStation: 'desk',
- carrying: undefined,
- recentTextTs: Date.now(),
- }));
- } catch {
- return [];
- }
-}
-
-function persistArchived(archived: Agent[]): void {
- try {
- const slim: PersistedAgent[] = archived.map(({ recentAssistantText, recentTextTs, blockReason, contextTokens, contextLimit, ...rest }) => {
- void recentAssistantText; void recentTextTs; void blockReason; void contextTokens; void contextLimit;
- return rest;
- });
- window.localStorage.setItem(LS_ARCHIVED, JSON.stringify(slim));
- } catch { /* noop */ }
-}
-
-function loadPersistedArchived(): Agent[] {
- try {
- const raw = window.localStorage.getItem(LS_ARCHIVED);
- if (!raw) return [];
- const parsed = JSON.parse(raw) as PersistedAgent[];
- if (!Array.isArray(parsed)) return [];
- // Archived agents have no live process — force the flag + clear run-state.
- return parsed.map((a) => ({
- ...a,
- archived: true,
- status: 'idle',
- ptyId: undefined,
- carrying: undefined,
- currentStation: undefined
- }));
- } catch {
- return [];
- }
-}
-
-function persistRestorable(restorable: Agent[]): void {
- try {
- const slim: PersistedAgent[] = restorable.map(({ recentAssistantText, recentTextTs, blockReason, ...rest }) => {
- void recentAssistantText; void recentTextTs; void blockReason;
- return rest;
- });
- window.localStorage.setItem(LS_RESTORABLE, JSON.stringify(slim));
- } catch { /* noop */ }
-}
-
-function loadPersistedRestorable(): Agent[] {
- try {
- const raw = window.localStorage.getItem(LS_RESTORABLE);
- if (!raw) return [];
- const parsed = JSON.parse(raw) as PersistedAgent[];
- if (!Array.isArray(parsed)) return [];
- // No live process — clear run-state; the spawn recipe fields are what matter.
- return parsed.map((a) => ({
- ...a,
- status: 'idle',
- carrying: undefined,
- currentStation: undefined
- }));
- } catch {
- return [];
- }
-}
-
-function persistQueues(queues: Record<string, QueuedMessage[]>): void {
- try {
- // Only keep non-empty queues so the key stays small.
- const slim: Record<string, QueuedMessage[]> = {};
- for (const [id, q] of Object.entries(queues)) if (q.length) slim[id] = q;
- window.localStorage.setItem(LS_QUEUES, JSON.stringify(slim));
- } catch { /* noop */ }
-}
-
-function loadPersistedQueues(): Record<string, QueuedMessage[]> {
- try {
- const raw = window.localStorage.getItem(LS_QUEUES);
- if (!raw) return {};
- const parsed = JSON.parse(raw) as Record<string, QueuedMessage[]>;
- if (!parsed || typeof parsed !== 'object') return {};
- // Defensively keep only well-formed entries.
- const out: Record<string, QueuedMessage[]> = {};
- for (const [id, q] of Object.entries(parsed)) {
- if (Array.isArray(q)) {
- out[id] = q.filter((m) => m && typeof m.text === 'string' && typeof m.id === 'string');
- }
- }
- return out;
- } catch {
- return {};
- }
-}
-
-function loadPersistedSelectedId(agents: Agent[]): string | null {
- try {
- const id = window.localStorage.getItem(LS_SELECTED);
- return id && agents.some((a) => a.id === id) ? id : (agents[0]?.id ?? null);
- } catch {
- return agents[0]?.id ?? null;
- }
-}
-const initialSidebarWidth = (() => {
- try {
- const v = window.localStorage.getItem(LS_SIDEBAR_WIDTH);
- const n = v ? parseInt(v, 10) : NaN;
- if (!Number.isNaN(n) && n >= 320 && n <= 1200) return n;
- } catch { /* noop */ }
- return 420;
-})();
-const initialSidebarTab: SidebarTab = (() => {
- try {
- const v = window.localStorage.getItem(LS_SIDEBAR_TAB);
- if (v === 'files' || v === 'terminal' || v === 'messages' || v === 'traces') return v;
- } catch { /* noop */ }
- return 'terminal';
-})();
-
-const initialAgents = loadPersistedAgents();
-const initialArchivedAgents = loadPersistedArchived();
-const initialRestorableAgents = loadPersistedRestorable();
-const initialSelectedId = loadPersistedSelectedId(initialAgents);
-const initialQueues = loadPersistedQueues();
-
-let queuedSeq = 0;
-/** Process-unique id for a queued message (timestamp + counter avoids collisions
- * when several are queued within the same millisecond). */
-function newQueuedId(): string {
- queuedSeq += 1;
- return `q-${Date.now()}-${queuedSeq}`;
-}
-
-export const useStore = create<State>((set) => ({
- agents: initialAgents,
- archivedAgents: initialArchivedAgents,
- restorableAgents: initialRestorableAgents,
- selectedId: initialSelectedId,
- feeds: {},
- addAgentOpen: false,
- pendingHire: null,
- ccTabRequest: null,
- requestCommandCenterTab: (tab) =>
- set((s) => ({ ccTabRequest: { tab, seq: (s.ccTabRequest?.seq ?? 0) + 1 } })),
- fullscreenAgentId: null,
- fullscreenFilePath: null,
- sidebarWidth: initialSidebarWidth,
- sidebarTab: initialSidebarTab,
- godStatus: 'booting',
- messageQueues: initialQueues,
- toolCounts: {},
- bumpToolCount: (id) =>
- set((s) => ({ toolCounts: { ...s.toolCounts, [id]: (s.toolCounts[id] ?? 0) + 1 } })),
- setGodStatus: (status) => set({ godStatus: status }),
- select: (id) => set((s) => { persistAgents(s.agents, id); return { selectedId: id, ccTabRequest: null }; }),
- updateAgent: (id, patch) =>
- set((s) => ({ agents: s.agents.map(a => a.id === id ? { ...a, ...patch } : a) })),
- pushFeed: (id, line) =>
- set((s) => ({ feeds: { ...s.feeds, [id]: [...(s.feeds[id] ?? []), line] } })),
- addAgent: (agent) =>
- set((s) => {
- const agents = [...s.agents, agent];
- // Re-spawning an archived agent un-archives it: an id is active xor archived.
- const archivedAgents = s.archivedAgents.filter((a) => a.id !== agent.id);
- // A live (re)spawn also consumes any restorable entry for the same id.
- const restorableAgents = s.restorableAgents.filter((a) => a.id !== agent.id);
- persistAgents(agents, agent.id);
- persistArchived(archivedAgents);
- if (restorableAgents.length !== s.restorableAgents.length) persistRestorable(restorableAgents);
- return {
- agents,
- archivedAgents,
- restorableAgents,
- selectedId: agent.id,
- feeds: { ...s.feeds, [agent.id]: s.feeds[agent.id] ?? [] }
- };
- }),
- removeAgent: (id) =>
- set((s) => {
- const agents = s.agents.filter(a => a.id !== id);
- const { [id]: _gone, ...feeds } = s.feeds;
- const { [id]: _queueGone, ...messageQueues } = s.messageQueues;
- const selectedId = s.selectedId === id ? (agents[0]?.id ?? null) : s.selectedId;
- persistAgents(agents, selectedId);
- if (_queueGone) persistQueues(messageQueues);
- return { agents, feeds, selectedId, messageQueues };
- }),
- archiveAgent: (id) =>
- set((s) => {
- const target = s.agents.find((a) => a.id === id);
- if (!target) return s;
- const agents = s.agents.filter((a) => a.id !== id);
- // Retain a flagged copy; the PTY is gone, so clear all live run-state.
- const archivedEntry: Agent = {
- ...target,
- archived: true,
- ptyId: undefined,
- status: 'idle',
- action: 'archived',
- carrying: undefined,
- currentStation: undefined
- };
- const archivedAgents = [...s.archivedAgents.filter((a) => a.id !== id), archivedEntry];
- const { [id]: _feedGone, ...feeds } = s.feeds;
- const { [id]: _queueGone, ...messageQueues } = s.messageQueues;
- const selectedId = s.selectedId === id ? (agents[0]?.id ?? null) : s.selectedId;
- persistAgents(agents, selectedId);
- persistArchived(archivedAgents);
- if (_queueGone) persistQueues(messageQueues);
- return { agents, archivedAgents, feeds, selectedId, messageQueues };
- }),
- removeArchivedAgent: (id) =>
- set((s) => {
- if (!s.archivedAgents.some((a) => a.id === id)) return s;
- const archivedAgents = s.archivedAgents.filter((a) => a.id !== id);
- persistArchived(archivedAgents);
- return { archivedAgents };
- }),
- removeRestorableAgent: (id) =>
- set((s) => {
- if (!s.restorableAgents.some((a) => a.id === id)) return s;
- const restorableAgents = s.restorableAgents.filter((a) => a.id !== id);
- persistRestorable(restorableAgents);
- return { restorableAgents };
- }),
- taskDetailId: null,
- openTaskDetail: (id) => set({ taskDetailId: id }),
- closeTaskDetail: () => set({ taskDetailId: null }),
- dispatchSeedRequest: null,
- requestDispatchSeed: (text) =>
- set((s) => ({ dispatchSeedRequest: { text, seq: (s.dispatchSeedRequest?.seq ?? 0) + 1 } })),
- answerDrafts: {},
- setAnswerDraft: (taskId, text) =>
- set((s) => ({ answerDrafts: { ...s.answerDrafts, [taskId]: text } })),
- drafts: {},
- setDraft: (agentId, text) =>
- set((s) => ({ drafts: { ...s.drafts, [agentId]: text } })),
- enqueueMessage: (agentId, text, meta) =>
- set((s) => {
- const trimmed = text.trim();
- if (!trimmed) return s;
- const msg: QueuedMessage = {
- id: newQueuedId(), text: trimmed, ts: Date.now(),
- ...(meta?.slack ? { slack: meta.slack } : {}),
- ...(meta?.instruction ? { instruction: meta.instruction } : {})
- };
- const messageQueues = { ...s.messageQueues, [agentId]: [...(s.messageQueues[agentId] ?? []), msg] };
- persistQueues(messageQueues);
- return { messageQueues };
- }),
- removeQueuedMessage: (agentId, messageId) =>
- set((s) => {
- const current = s.messageQueues[agentId];
- if (!current) return s;
- const next = current.filter((m) => m.id !== messageId);
- const messageQueues = { ...s.messageQueues, [agentId]: next };
- persistQueues(messageQueues);
- return { messageQueues };
- }),
- clearQueue: (agentId) =>
- set((s) => {
- if (!s.messageQueues[agentId]?.length) return s;
- const messageQueues = { ...s.messageQueues, [agentId]: [] };
- persistQueues(messageQueues);
- return { messageQueues };
- }),
- reconcileWithLivePtys: (livePtyIds) =>
- set((s) => {
- const live = new Set(livePtyIds);
- // Keep agents with no PTY (synthetic) or whose PTY is still alive.
- const agents = s.agents.filter((a) => !a.ptyId || live.has(a.ptyId));
- if (agents.length === s.agents.length) return s;
- // Workers whose terminal died with the previous session become restorable
- // (full spawn recipe retained) instead of silently vanishing. God and the
- // prep assistant are excluded — they auto-respawn at boot.
- const dead = s.agents.filter(
- (a) => a.ptyId && !live.has(a.ptyId) && !a.isGod && !a.isAssistant
- );
- const restorableAgents = [
- ...s.restorableAgents.filter((r) => !dead.some((d) => d.id === r.id)),
- ...dead
- ];
- const feeds: Record<string, string[]> = {};
- for (const a of agents) feeds[a.id] = s.feeds[a.id] ?? [];
- const selectedId = agents.some((a) => a.id === s.selectedId)
- ? s.selectedId
- : (agents[0]?.id ?? null);
- persistAgents(agents, selectedId);
- persistRestorable(restorableAgents);
- return { agents, feeds, selectedId, restorableAgents };
- }),
- setAddAgentOpen: (open) => set({ addAgentOpen: open }),
- setPendingHire: (m) => set({ pendingHire: m }),
- setFullscreen: (id) => set({ fullscreenAgentId: id }),
- setFullscreenFile: (path) => set({ fullscreenFilePath: path }),
- setSidebarWidth: (px) => {
- const clamped = Math.min(1200, Math.max(320, Math.round(px)));
- try { window.localStorage.setItem(LS_SIDEBAR_WIDTH, String(clamped)); } catch { /* noop */ }
- set({ sidebarWidth: clamped });
- },
- setSidebarTab: (tab) => {
- try { window.localStorage.setItem(LS_SIDEBAR_TAB, tab); } catch { /* noop */ }
- set({ sidebarTab: tab });
- }
-}));
-
-export function selectedAgent(s: State): Agent | undefined {
- return s.agents.find(a => a.id === s.selectedId);
-}
+import { create } from 'zustand';
+import type { AccentColorName } from '@/design/tokens';
+import type { OfficeCharacterName } from '@/scene/office/cast';
+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';
+
+export type ToolKind =
+ | 'Read' | 'Edit' | 'Write' | 'Bash' | 'WebFetch' | 'WebSearch'
+ | 'Grep' | 'Glob' | 'TodoWrite' | 'MCP';
+
+export type StationKind =
+ | 'shelf' | 'terminal' | 'web' | 'board' | 'mailbox' | 'mcp' | 'desk';
+
+export interface BlockReason {
+ summary: string; // short headline shown on banner
+ detail: string; // longer explanation
+ command?: string; // verbatim command awaiting confirmation, if any
+ actions: Array<{
+ label: string;
+ kind: 'approve' | 'deny' | 'neutral';
+ /** what we'd send to the tmux pane on click */
+ send?: string;
+ }>;
+}
+
+export interface Agent {
+ id: string;
+ name: string;
+ /** which Office character represents this agent on the floor */
+ character: OfficeCharacterName;
+ accent: AccentColorName;
+ /** persistent short context — what is this agent for (shown on the floor) */
+ description: string;
+ project: string;
+ /** legacy field — populated only for the seeded mock agents */
+ tmuxTarget: string;
+ cwd: string;
+ goal?: string;
+ status: StatusKind;
+ action: string;
+ progress: number;
+ currentStation?: StationKind;
+ carrying?: ToolKind;
+ /** latest assistant message, streamed character-by-character in the sidebar */
+ recentAssistantText?: string;
+ /** epoch ms — used to drive the typewriter so identical strings still re-stream */
+ recentTextTs?: number;
+ /** populated when status === 'blocked' */
+ blockReason?: BlockReason;
+ /** present iff this agent has a real PTY in the main process */
+ ptyId?: string;
+ /** the command being run in the PTY (e.g. 'claude' or 'agy') */
+ command?: string;
+ /** which agent CLI preset owns this PTY recipe; drives the model picker +
+ * spawn flags. Defaults to 'claude' when unset (legacy agents / inferred
+ * from command). */
+ provider?: AgentProvider;
+ /** the model this agent runs on (e.g. 'claude-sonnet-4-6[1m]' or 'gemini-3-pro');
+ * drives the model selector + the --model arg used when (re)spawning the agent */
+ model?: string;
+ /** the last prompt the user submitted to this agent in Claude Code —
+ * shown on the floor as a card above the seated avatar */
+ lastPrompt?: string;
+ /** the orchestrator ("god") agent — seated in Michael's room, runs the floor */
+ isGod?: boolean;
+ /** Michael's prep assistant — send-only; enriches prompts and forwards them to
+ * the god. Excluded from broadcast fan-out and from the restorable-dead sweep. */
+ isAssistant?: boolean;
+ /** When git isolation is enabled, the dedicated worktree path the agent runs
+ * in (its own `agent/<id>` branch); undefined for shared-cwd agents. */
+ worktreePath?: string;
+ /** Live context size of the agent's Claude session (tokens), polled from its
+ * transcript. Drives the context gauge on the agent card. */
+ contextTokens?: number;
+ /** The context-window limit assumed for this agent's model (tokens). */
+ contextLimit?: number;
+ /** True once this agent's terminal was closed. Archived agents are retained
+ * (in the store's `archivedAgents` list + the hive registry) but flagged and
+ * kept off the floor; only live-PTY agents are 'active'. */
+ archived?: boolean;
+}
+
+export interface FeedEntry {
+ agentId: string;
+ text: string;
+ ts: number;
+}
+
+/** A message the user has parked for an agent while its terminal was busy.
+ * Queued messages are drained one at a time when the agent next goes idle (see
+ * useHive's flush loop). */
+export interface QueuedMessage {
+ id: string;
+ text: string;
+ /** epoch ms the message was queued — drives ordering and the "queued 2m ago" hint */
+ ts: number;
+ /** Slack-originated: thread coordinates so the office can reply in-thread. */
+ slack?: { channel: string; thread_ts: string };
+ /** Optional override for the text actually typed into the agent's PTY. When set,
+ * the drain submits THIS instead of `text`, while UI/card surfaces keep using
+ * `text`. Used by Slack-origin work to carry the autonomy preamble to god's
+ * prompt without polluting the human-readable kanban card title (= raw `text`). */
+ instruction?: string;
+}
+
+export type SidebarTab = 'terminal' | 'files' | 'messages' | 'traces';
+
+/** Lifecycle of the god agent ("Michael") bootstrap on launch.
+ * 'booting' until his PTY is confirmed live, then 'ready' (or 'failed' if the
+ * spawn errored). The empty-floor UI shows a loader while 'booting' so users
+ * don't see the "add agent" prompt before Michael has clocked in. */
+export type GodStatus = 'booting' | 'ready' | 'failed';
+
+interface State {
+ agents: Agent[];
+ /** Agents whose terminal was closed — retained + flagged, kept off the active
+ * roster/floor. The hive registry retains them durably; this mirrors them for
+ * the renderer's "Archived" view. */
+ archivedAgents: Agent[];
+ /** Workers from the previous session whose terminal died with the app (quit /
+ * crash). Kept with their full spawn recipe (id, cwd, model, command) so the
+ * user can one-click respawn them with the SAME agent id — memory, inbox and
+ * registry entry reattach by themselves. God/assistant are excluded (they
+ * auto-respawn). */
+ restorableAgents: Agent[];
+ selectedId: string | null;
+ feeds: Record<string, string[]>;
+ addAgentOpen: boolean;
+ fullscreenAgentId: string | null;
+ fullscreenFilePath: string | null;
+ sidebarWidth: number;
+ sidebarTab: SidebarTab;
+ godStatus: GodStatus;
+ /** Per-agent outgoing message queue (agent id → messages awaiting delivery).
+ * Lets the user keep "talking" to a busy agent: messages park here and are
+ * drained to the terminal one-by-one once the agent is free. */
+ messageQueues: Record<string, QueuedMessage[]>;
+ /** Per-agent tool-call count this session — a lightweight activity/usage proxy
+ * shown in the command center (interactive sessions don't expose billed $). */
+ toolCounts: Record<string, number>;
+ bumpToolCount: (id: string) => void;
+ setGodStatus: (status: GodStatus) => void;
+ select: (id: string) => void;
+ updateAgent: (id: string, patch: Partial<Agent>) => void;
+ pushFeed: (id: string, line: string) => void;
+ addAgent: (agent: Agent) => void;
+ removeAgent: (id: string) => void;
+ /** Archive an agent (its terminal was closed): move it from the active roster
+ * into `archivedAgents` with its PTY cleared. Retained + flagged, NOT deleted. */
+ archiveAgent: (id: string) => void;
+ /** Permanently forget an archived agent (drops the renderer entry only; the
+ * hive registry keeps its record). */
+ removeArchivedAgent: (id: string) => void;
+ /** Drop one agent from the restorable list (it was respawned or dismissed). */
+ removeRestorableAgent: (id: string) => void;
+ /** One-shot request to open a Command-Center tab (e.g. clicking the office
+ * task board → 'tasks'). `seq` makes repeated identical requests distinct. */
+ ccTabRequest: { tab: string; seq: number } | null;
+ requestCommandCenterTab: (tab: string) => void;
+ /** The task whose detail overlay is open (rendered app-wide over the office
+ * floor — the card content grows: contracts, deps, the human Q&A trail). */
+ taskDetailId: string | null;
+ openTaskDetail: (id: string) => void;
+ closeTaskDetail: () => void;
+ /** One-shot prefill for the Command Center's dispatch box (a task detail's
+ * "assign" from anywhere in the app). seq-keyed like ccTabRequest. */
+ dispatchSeedRequest: { text: string; seq: number } | null;
+ requestDispatchSeed: (text: string) => void;
+ /** Unsent ASK ME answer drafts, keyed by task id — so switching tabs (which
+ * unmounts the ask-me view) doesn't eat a half-typed answer. */
+ answerDrafts: Record<string, string>;
+ setAnswerDraft: (taskId: string, text: string) => void;
+ /** Unsent composer drafts, per agent — so switching agents (which remounts the
+ * composer) doesn't eat what the user was typing. */
+ drafts: Record<string, string>;
+ setDraft: (agentId: string, text: string) => void;
+ /** Mirror of config.freeflowEnabled so the composer can show/hide the Free Flow
+ * mic button reactively (set by App on config load and by Settings on save). */
+ freeflowEnabled: boolean;
+ setFreeflowEnabled: (on: boolean) => void;
+ /** Mirror of the active office theme (set by App on config load + by Settings
+ * on switch). OfficeFloor depends on this and rebuilds the scene on change. */
+ officeTheme: ThemeId;
+ setOfficeTheme: (theme: ThemeId) => 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`). */
+ enqueueMessage: (agentId: string, text: string, meta?: { slack?: { channel: string; thread_ts: string }; instruction?: string }) => void;
+ /** Drop a single queued message (user removed it, or it was just delivered). */
+ removeQueuedMessage: (agentId: string, messageId: string) => void;
+ /** Clear an agent's entire pending queue. */
+ clearQueue: (agentId: string) => void;
+ setAddAgentOpen: (open: boolean) => void;
++ /** A validated hire manifest waiting to pre-fill the Add-Agent modal. */
++ pendingHire: HireManifest | null;
++ setPendingHire: (m: HireManifest | null) => void;
+ setFullscreen: (id: string | null) => void;
+ setFullscreenFile: (path: string | null) => void;
+ setSidebarWidth: (px: number) => void;
+ setSidebarTab: (tab: SidebarTab) => void;
+ /** Drop persisted agents whose PTY is no longer alive in the main process.
+ * Called once at startup so a renderer reload (e.g. after the laptop sleeps)
+ * restores still-running agents and only removes truly-dead ones. */
+ reconcileWithLivePtys: (livePtyIds: string[]) => void;
+}
+
+const LS_SIDEBAR_WIDTH = 'cth.sidebarWidth';
+const LS_SIDEBAR_TAB = 'cth.sidebarTab';
+const LS_AGENTS = 'cth.agents';
+const LS_ARCHIVED = 'cth.archivedAgents';
+const LS_RESTORABLE = 'cth.restorableAgents';
+const LS_SELECTED = 'cth.selectedId';
+const LS_QUEUES = 'cth.messageQueues';
+
+// Fields that are large or transient — not worth persisting across reloads.
+// contextTokens/contextLimit describe a LIVE session; persisting them showed a
+// dead session's context gauge after a restart until the poll caught up.
+type PersistedAgent = Omit<Agent, 'recentAssistantText' | 'recentTextTs' | 'blockReason' | 'contextTokens' | 'contextLimit'>;
+
+function persistAgents(agents: Agent[], selectedId: string | null): void {
+ try {
+ const slim: PersistedAgent[] = agents.map(({ recentAssistantText, recentTextTs, blockReason, contextTokens, contextLimit, ...rest }) => {
+ void recentAssistantText; void recentTextTs; void blockReason; void contextTokens; void contextLimit;
+ return rest;
+ });
+ window.localStorage.setItem(LS_AGENTS, JSON.stringify(slim));
+ window.localStorage.setItem(LS_SELECTED, selectedId ?? '');
+ } catch { /* noop */ }
+}
+
+function loadPersistedAgents(): Agent[] {
+ try {
+ const raw = window.localStorage.getItem(LS_AGENTS);
+ if (!raw) return [];
+ const parsed = JSON.parse(raw) as PersistedAgent[];
+ if (!Array.isArray(parsed)) return [];
+ // Reset volatile run-state; the PTY stream / mock loop will repopulate it.
+ return parsed.map((a) => ({
+ ...a,
+ progress: 0,
+ status: 'idle',
+ action: 'reconnecting…',
+ currentStation: 'desk',
+ carrying: undefined,
+ recentTextTs: Date.now(),
+ }));
+ } catch {
+ return [];
+ }
+}
+
+function persistArchived(archived: Agent[]): void {
+ try {
+ const slim: PersistedAgent[] = archived.map(({ recentAssistantText, recentTextTs, blockReason, contextTokens, contextLimit, ...rest }) => {
+ void recentAssistantText; void recentTextTs; void blockReason; void contextTokens; void contextLimit;
+ return rest;
+ });
+ window.localStorage.setItem(LS_ARCHIVED, JSON.stringify(slim));
+ } catch { /* noop */ }
+}
+
+function loadPersistedArchived(): Agent[] {
+ try {
+ const raw = window.localStorage.getItem(LS_ARCHIVED);
+ if (!raw) return [];
+ const parsed = JSON.parse(raw) as PersistedAgent[];
+ if (!Array.isArray(parsed)) return [];
+ // Archived agents have no live process — force the flag + clear run-state.
+ return parsed.map((a) => ({
+ ...a,
+ archived: true,
+ status: 'idle',
+ ptyId: undefined,
+ carrying: undefined,
+ currentStation: undefined
+ }));
+ } catch {
+ return [];
+ }
+}
+
+function persistRestorable(restorable: Agent[]): void {
+ try {
+ const slim: PersistedAgent[] = restorable.map(({ recentAssistantText, recentTextTs, blockReason, ...rest }) => {
+ void recentAssistantText; void recentTextTs; void blockReason;
+ return rest;
+ });
+ window.localStorage.setItem(LS_RESTORABLE, JSON.stringify(slim));
+ } catch { /* noop */ }
+}
+
+function loadPersistedRestorable(): Agent[] {
+ try {
+ const raw = window.localStorage.getItem(LS_RESTORABLE);
+ if (!raw) return [];
+ const parsed = JSON.parse(raw) as PersistedAgent[];
+ if (!Array.isArray(parsed)) return [];
+ // No live process — clear run-state; the spawn recipe fields are what matter.
+ return parsed.map((a) => ({
+ ...a,
+ status: 'idle',
+ carrying: undefined,
+ currentStation: undefined
+ }));
+ } catch {
+ return [];
+ }
+}
+
+function persistQueues(queues: Record<string, QueuedMessage[]>): void {
+ try {
+ // Only keep non-empty queues so the key stays small.
+ const slim: Record<string, QueuedMessage[]> = {};
+ for (const [id, q] of Object.entries(queues)) if (q.length) slim[id] = q;
+ window.localStorage.setItem(LS_QUEUES, JSON.stringify(slim));
+ } catch { /* noop */ }
+}
+
+function loadPersistedQueues(): Record<string, QueuedMessage[]> {
+ try {
+ const raw = window.localStorage.getItem(LS_QUEUES);
+ if (!raw) return {};
+ const parsed = JSON.parse(raw) as Record<string, QueuedMessage[]>;
+ if (!parsed || typeof parsed !== 'object') return {};
+ // Defensively keep only well-formed entries.
+ const out: Record<string, QueuedMessage[]> = {};
+ for (const [id, q] of Object.entries(parsed)) {
+ if (Array.isArray(q)) {
+ out[id] = q.filter((m) => m && typeof m.text === 'string' && typeof m.id === 'string');
+ }
+ }
+ return out;
+ } catch {
+ return {};
+ }
+}
+
+function loadPersistedSelectedId(agents: Agent[]): string | null {
+ try {
+ const id = window.localStorage.getItem(LS_SELECTED);
+ return id && agents.some((a) => a.id === id) ? id : (agents[0]?.id ?? null);
+ } catch {
+ return agents[0]?.id ?? null;
+ }
+}
+const initialSidebarWidth = (() => {
+ try {
+ const v = window.localStorage.getItem(LS_SIDEBAR_WIDTH);
+ const n = v ? parseInt(v, 10) : NaN;
+ if (!Number.isNaN(n) && n >= 320 && n <= 1200) return n;
+ } catch { /* noop */ }
+ return 420;
+})();
+const initialSidebarTab: SidebarTab = (() => {
+ try {
+ const v = window.localStorage.getItem(LS_SIDEBAR_TAB);
+ if (v === 'files' || v === 'terminal' || v === 'messages' || v === 'traces') return v;
+ } catch { /* noop */ }
+ return 'terminal';
+})();
+
+const initialAgents = loadPersistedAgents();
+const initialArchivedAgents = loadPersistedArchived();
+const initialRestorableAgents = loadPersistedRestorable();
+const initialSelectedId = loadPersistedSelectedId(initialAgents);
+const initialQueues = loadPersistedQueues();
+
+let queuedSeq = 0;
+/** Process-unique id for a queued message (timestamp + counter avoids collisions
+ * when several are queued within the same millisecond). */
+function newQueuedId(): string {
+ queuedSeq += 1;
+ return `q-${Date.now()}-${queuedSeq}`;
+}
+
+export const useStore = create<State>((set) => ({
+ agents: initialAgents,
+ archivedAgents: initialArchivedAgents,
+ restorableAgents: initialRestorableAgents,
+ selectedId: initialSelectedId,
+ feeds: {},
+ addAgentOpen: false,
+ ccTabRequest: null,
+ requestCommandCenterTab: (tab) =>
+ set((s) => ({ ccTabRequest: { tab, seq: (s.ccTabRequest?.seq ?? 0) + 1 } })),
+ fullscreenAgentId: null,
+ fullscreenFilePath: null,
+ sidebarWidth: initialSidebarWidth,
+ sidebarTab: initialSidebarTab,
+ godStatus: 'booting',
+ messageQueues: initialQueues,
+ toolCounts: {},
+ bumpToolCount: (id) =>
+ set((s) => ({ toolCounts: { ...s.toolCounts, [id]: (s.toolCounts[id] ?? 0) + 1 } })),
+ setGodStatus: (status) => set({ godStatus: status }),
+ select: (id) => set((s) => { persistAgents(s.agents, id); return { selectedId: id, ccTabRequest: null }; }),
+ updateAgent: (id, patch) =>
+ set((s) => ({ agents: s.agents.map(a => a.id === id ? { ...a, ...patch } : a) })),
+ pushFeed: (id, line) =>
+ set((s) => ({ feeds: { ...s.feeds, [id]: [...(s.feeds[id] ?? []), line] } })),
+ addAgent: (agent) =>
+ set((s) => {
+ const agents = [...s.agents, agent];
+ // Re-spawning an archived agent un-archives it: an id is active xor archived.
+ const archivedAgents = s.archivedAgents.filter((a) => a.id !== agent.id);
+ // A live (re)spawn also consumes any restorable entry for the same id.
+ const restorableAgents = s.restorableAgents.filter((a) => a.id !== agent.id);
+ persistAgents(agents, agent.id);
+ persistArchived(archivedAgents);
+ if (restorableAgents.length !== s.restorableAgents.length) persistRestorable(restorableAgents);
+ return {
+ agents,
+ archivedAgents,
+ restorableAgents,
+ selectedId: agent.id,
+ feeds: { ...s.feeds, [agent.id]: s.feeds[agent.id] ?? [] }
+ };
+ }),
+ removeAgent: (id) =>
+ set((s) => {
+ const agents = s.agents.filter(a => a.id !== id);
+ const { [id]: _gone, ...feeds } = s.feeds;
+ const { [id]: _queueGone, ...messageQueues } = s.messageQueues;
+ const selectedId = s.selectedId === id ? (agents[0]?.id ?? null) : s.selectedId;
+ persistAgents(agents, selectedId);
+ if (_queueGone) persistQueues(messageQueues);
+ return { agents, feeds, selectedId, messageQueues };
+ }),
+ archiveAgent: (id) =>
+ set((s) => {
+ const target = s.agents.find((a) => a.id === id);
+ if (!target) return s;
+ const agents = s.agents.filter((a) => a.id !== id);
+ // Retain a flagged copy; the PTY is gone, so clear all live run-state.
+ const archivedEntry: Agent = {
+ ...target,
+ archived: true,
+ ptyId: undefined,
+ status: 'idle',
+ action: 'archived',
+ carrying: undefined,
+ currentStation: undefined
+ };
+ const archivedAgents = [...s.archivedAgents.filter((a) => a.id !== id), archivedEntry];
+ const { [id]: _feedGone, ...feeds } = s.feeds;
+ const { [id]: _queueGone, ...messageQueues } = s.messageQueues;
+ const selectedId = s.selectedId === id ? (agents[0]?.id ?? null) : s.selectedId;
+ persistAgents(agents, selectedId);
+ persistArchived(archivedAgents);
+ if (_queueGone) persistQueues(messageQueues);
+ return { agents, archivedAgents, feeds, selectedId, messageQueues };
+ }),
+ removeArchivedAgent: (id) =>
+ set((s) => {
+ if (!s.archivedAgents.some((a) => a.id === id)) return s;
+ const archivedAgents = s.archivedAgents.filter((a) => a.id !== id);
+ persistArchived(archivedAgents);
+ return { archivedAgents };
+ }),
+ removeRestorableAgent: (id) =>
+ set((s) => {
+ if (!s.restorableAgents.some((a) => a.id === id)) return s;
+ const restorableAgents = s.restorableAgents.filter((a) => a.id !== id);
+ persistRestorable(restorableAgents);
+ return { restorableAgents };
+ }),
+ taskDetailId: null,
+ openTaskDetail: (id) => set({ taskDetailId: id }),
+ closeTaskDetail: () => set({ taskDetailId: null }),
+ dispatchSeedRequest: null,
+ requestDispatchSeed: (text) =>
+ set((s) => ({ dispatchSeedRequest: { text, seq: (s.dispatchSeedRequest?.seq ?? 0) + 1 } })),
+ answerDrafts: {},
+ setAnswerDraft: (taskId, text) =>
+ set((s) => ({ answerDrafts: { ...s.answerDrafts, [taskId]: text } })),
+ drafts: {},
+ setDraft: (agentId, text) =>
+ set((s) => ({ drafts: { ...s.drafts, [agentId]: text } })),
+ freeflowEnabled: false,
+ setFreeflowEnabled: (on) => set({ freeflowEnabled: on }),
+ officeTheme: 'office',
+ setOfficeTheme: (theme) => set({ officeTheme: theme }),
+ enqueueMessage: (agentId, text, meta) =>
+ set((s) => {
+ const trimmed = text.trim();
+ if (!trimmed) return s;
+ const msg: QueuedMessage = {
+ id: newQueuedId(), text: trimmed, ts: Date.now(),
+ ...(meta?.slack ? { slack: meta.slack } : {}),
+ ...(meta?.instruction ? { instruction: meta.instruction } : {})
+ };
+ const messageQueues = { ...s.messageQueues, [agentId]: [...(s.messageQueues[agentId] ?? []), msg] };
+ persistQueues(messageQueues);
+ return { messageQueues };
+ }),
+ removeQueuedMessage: (agentId, messageId) =>
+ set((s) => {
+ const current = s.messageQueues[agentId];
+ if (!current) return s;
+ const next = current.filter((m) => m.id !== messageId);
+ const messageQueues = { ...s.messageQueues, [agentId]: next };
+ persistQueues(messageQueues);
+ return { messageQueues };
+ }),
+ clearQueue: (agentId) =>
+ set((s) => {
+ if (!s.messageQueues[agentId]?.length) return s;
+ const messageQueues = { ...s.messageQueues, [agentId]: [] };
+ persistQueues(messageQueues);
+ return { messageQueues };
+ }),
+ reconcileWithLivePtys: (livePtyIds) =>
+ set((s) => {
+ const live = new Set(livePtyIds);
+ // Keep agents with no PTY (synthetic) or whose PTY is still alive.
+ const agents = s.agents.filter((a) => !a.ptyId || live.has(a.ptyId));
+ if (agents.length === s.agents.length) return s;
+ // Workers whose terminal died with the previous session become restorable
+ // (full spawn recipe retained) instead of silently vanishing. God and the
+ // prep assistant are excluded — they auto-respawn at boot.
+ const dead = s.agents.filter(
+ (a) => a.ptyId && !live.has(a.ptyId) && !a.isGod && !a.isAssistant
+ );
+ const restorableAgents = [
+ ...s.restorableAgents.filter((r) => !dead.some((d) => d.id === r.id)),
+ ...dead
+ ];
+ const feeds: Record<string, string[]> = {};
+ for (const a of agents) feeds[a.id] = s.feeds[a.id] ?? [];
+ const selectedId = agents.some((a) => a.id === s.selectedId)
+ ? s.selectedId
+ : (agents[0]?.id ?? null);
+ persistAgents(agents, selectedId);
+ persistRestorable(restorableAgents);
+ return { agents, feeds, selectedId, restorableAgents };
+ }),
+ setAddAgentOpen: (open) => set({ addAgentOpen: open }),
++ pendingHire: null,
++ setPendingHire: (m) => set({ pendingHire: m }),
+ setFullscreen: (id) => set({ fullscreenAgentId: id }),
+ setFullscreenFile: (path) => set({ fullscreenFilePath: path }),
+ setSidebarWidth: (px) => {
+ const clamped = Math.min(1200, Math.max(320, Math.round(px)));
+ try { window.localStorage.setItem(LS_SIDEBAR_WIDTH, String(clamped)); } catch { /* noop */ }
+ set({ sidebarWidth: clamped });
+ },
+ setSidebarTab: (tab) => {
+ try { window.localStorage.setItem(LS_SIDEBAR_TAB, tab); } catch { /* noop */ }
+ set({ sidebarTab: tab });
+ }
+}));
+
+export function selectedAgent(s: State): Agent | undefined {
+ return s.agents.find(a => a.id === s.selectedId);
+}
diff --cc src/shared/hire.ts
index 00000000,35d61d6b..9d505136
mode 000000,100644..100644
--- a/src/shared/hire.ts
+++ b/src/shared/hire.ts
@@@ -1,0 -1,205 +1,206 @@@
+ /**
+ * Shareable "hires" — portable agent role templates (manifest spec v1).
+ *
+ * A hire manifest is a small JSON document that describes a role-configured
+ * agent (name, provider, model, flags, goal, budget) so it can be shared as a
+ * file or hosted in a community gallery and imported with one click via the
+ * `munderdifflin://hire?src=<https-url>` deep link or an in-app file picker.
+ *
+ * SECURITY MODEL — a manifest is untrusted input:
+ * - It can NEVER auto-spawn an agent. Importing only pre-fills the Add-Agent
+ * modal; the human reviews the final command and clicks spawn.
+ * - It cannot carry a raw executable/command. The spawn binary always comes
+ * from the locally configured provider preset; a manifest may only append
+ * flag-shaped arguments (validated below), which the modal shows in full.
+ * - All fields are length/shape-capped here, in one dependency-free module
+ * shared by main (deep link / file import) and renderer (prefill).
+ */
+
+ export const HIRE_SPEC_V1 = 'munder-difflin/hire@1';
+
+ /** Providers a manifest may request ('agy' is accepted as an alias for
+ * 'antigravity'). 'custom' is deliberately NOT allowed — it would let a
+ * manifest choose an arbitrary local binary. */
+ export type HireProvider = 'claude' | 'antigravity' | 'codex';
+
+ export interface HireManifest {
+ /** Spec tag; exactly `munder-difflin/hire@1` for this version. */
+ spec: typeof HIRE_SPEC_V1;
+ /** Agent display name (also seeds the hive id). Required. */
+ name: string;
+ /** One-line role, e.g. "Documentation writer" — lands in identity.md + card. */
+ description?: string;
+ /** The standing goal/mission text pre-filled into the goal field. */
+ goal?: string;
+ /** Office cast sprite id (e.g. 'pam'); unknown values fall back to default. */
+ character?: string;
+ /** Accent color name (e.g. 'mint'); unknown values fall back to default. */
+ accent?: string;
+ /** Which CLI the role is designed for. Default: the user's default provider. */
+ provider?: HireProvider;
+ /** Model id/label for that provider (e.g. 'claude-sonnet-4-6'). */
+ model?: string;
+ /** Extra flag-shaped args appended to the locally-built spawn command.
+ * Each must look like a flag or a flag value (no shell metacharacters). */
+ commandFlags?: string[];
+ /** Capability tags for the hive registry (routing hints). */
+ capabilities?: string[];
+ /** Spawn in an isolated git worktree. */
+ isolate?: boolean;
+ /** Per-agent total-token ceiling, applied to agentTokenCaps after spawn. */
+ tokenCap?: number;
+ /** Attribution shown in the import preview. */
+ author?: string;
+ /** Manifest home (gallery page). https only. */
+ homepage?: string;
+ }
+
+ export interface HireValidation {
+ ok: boolean;
+ manifest?: HireManifest;
+ errors: string[];
+ }
+
+ const PROVIDERS: readonly string[] = ['claude', 'antigravity', 'codex'];
+ const MAX_BYTES = 64 * 1024;
+
+ /** A flag ("-x", "--flag", "--flag=value") or a bare value token that may follow
+ * a flag. Letters/digits plus a conservative punctuation set; no quotes,
- * backticks, semicolons, pipes, ampersands, redirects, or whitespace. Args are
- * passed to node-pty as argv (no shell), so this is defense in depth. */
-const FLAG_RE = /^[A-Za-z0-9._\/=:,@%+-]{1,100}$/;
++ * backticks, semicolons, pipes, ampersands, redirects, percent (cmd.exe
++ * %VAR% env-expansion), or whitespace. Args are passed to node-pty as argv
++ * (no shell), so this is defense in depth. */
++const FLAG_RE = /^[A-Za-z0-9._\/=:,@+-]{1,100}$/;
+
+ /** Allowed characters in a model id/label. Model values flow into the spawn
+ * command line (`--model <value>`), so this MUST reject shell metacharacters —
+ * on Windows a `.cmd`/`.bat` provider shim routes the command through cmd.exe,
+ * where an unquoted `&`/`|`/`^`/`<`/`>`/`(`/`)` would chain a second command.
+ * Real model ids/labels only need letters, digits, spaces, and a little
+ * punctuation: `claude-sonnet-4-6[1m]`, `Gemini 3.1 Pro (High)`. No quotes,
+ * backticks, `$`, `;`, `&`, `|`, `^`, `<`, `>`, `%`, `!`. (The command field
+ * stays editable, so a legitimate exotic value can still be typed by hand.) */
+ const MODEL_RE = /^[A-Za-z0-9 ._()[\]\/:@+-]{1,80}$/;
+
+ function str(v: unknown): v is string { return typeof v === 'string'; }
+
+ function capped(v: unknown, max: number, field: string, errors: string[], required = false): string | undefined {
+ if (v === undefined || v === null) {
+ if (required) errors.push(`"${field}" is required`);
+ return undefined;
+ }
+ if (!str(v)) { errors.push(`"${field}" must be a string`); return undefined; }
+ const t = v.trim();
+ if (required && !t) { errors.push(`"${field}" must not be empty`); return undefined; }
+ if (t.length > max) { errors.push(`"${field}" exceeds ${max} chars`); return undefined; }
+ return t || undefined;
+ }
+
+ /** Validate an untrusted parsed JSON value into a HireManifest. Pure; no I/O. */
+ export function validateHireManifest(raw: unknown): HireValidation {
+ const errors: string[] = [];
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
+ return { ok: false, errors: ['manifest must be a JSON object'] };
+ }
+ const o = raw as Record<string, unknown>;
+
+ if (o.spec !== HIRE_SPEC_V1) {
+ return { ok: false, errors: [`unsupported spec "${String(o.spec)}" (expected "${HIRE_SPEC_V1}")`] };
+ }
+
+ const name = capped(o.name, 40, 'name', errors, true);
+ const description = capped(o.description, 200, 'description', errors);
+ const goal = capped(o.goal, 4000, 'goal', errors);
+ const character = capped(o.character, 24, 'character', errors)?.toLowerCase();
+ const accent = capped(o.accent, 24, 'accent', errors)?.toLowerCase();
+ const model = capped(o.model, 80, 'model', errors);
+ if (model !== undefined && !MODEL_RE.test(model)) {
+ errors.push('"model" contains disallowed characters (it goes onto the spawn command line; letters, digits, spaces and . _ - ( ) [ ] / : @ + only)');
+ }
+ const author = capped(o.author, 80, 'author', errors);
+ const homepage = capped(o.homepage, 300, 'homepage', errors);
+
+ let provider: HireProvider | undefined;
+ if (o.provider !== undefined) {
+ const p = str(o.provider) ? (o.provider === 'agy' ? 'antigravity' : o.provider) : o.provider;
+ if (str(p) && PROVIDERS.includes(p)) provider = p as HireProvider;
+ else errors.push(`"provider" must be one of ${PROVIDERS.join(', ')} (or "agy")`);
+ }
+
+ let commandFlags: string[] | undefined;
+ if (o.commandFlags !== undefined) {
+ if (!Array.isArray(o.commandFlags) || o.commandFlags.length > 16) {
+ errors.push('"commandFlags" must be an array of at most 16 items');
+ } else {
+ commandFlags = [];
+ for (const f of o.commandFlags) {
+ if (!str(f) || !FLAG_RE.test(f)) { errors.push(`commandFlags entry ${JSON.stringify(f)} is not a safe flag token`); continue; }
+ commandFlags.push(f);
+ }
+ // The FIRST entry must actually be flag-shaped; later bare tokens are
+ // allowed as values for a preceding flag.
+ if (commandFlags.length > 0 && !commandFlags[0].startsWith('-')) {
+ errors.push('"commandFlags" must start with a flag (e.g. "--max-turns")');
+ }
+ if (commandFlags.length === 0) commandFlags = undefined;
+ }
+ }
+
+ let capabilities: string[] | undefined;
+ if (o.capabilities !== undefined) {
+ if (!Array.isArray(o.capabilities) || o.capabilities.length > 12) {
+ errors.push('"capabilities" must be an array of at most 12 items');
+ } else {
+ capabilities = o.capabilities.filter(str).map(c => c.trim().slice(0, 40)).filter(Boolean);
+ if (capabilities.length === 0) capabilities = undefined;
+ }
+ }
+
+ let isolate: boolean | undefined;
+ if (o.isolate !== undefined) {
+ if (typeof o.isolate === 'boolean') isolate = o.isolate;
+ else errors.push('"isolate" must be a boolean');
+ }
+
+ let tokenCap: number | undefined;
+ if (o.tokenCap !== undefined) {
+ if (typeof o.tokenCap === 'number' && Number.isInteger(o.tokenCap) && o.tokenCap > 0 && o.tokenCap <= 1e10) tokenCap = o.tokenCap;
+ else errors.push('"tokenCap" must be a positive integer (max 1e10)');
+ }
+
+ if (homepage && !homepage.startsWith('https://')) errors.push('"homepage" must be https');
+
+ if (errors.length > 0 || !name) return { ok: false, errors };
+ return {
+ ok: true,
+ errors: [],
+ manifest: { spec: HIRE_SPEC_V1, name, description, goal, character, accent, provider, model, commandFlags, capabilities, isolate, tokenCap, author, homepage }
+ };
+ }
+
+ /** Parse a `munderdifflin://hire?src=<https-url>` deep link. Returns the https
+ * manifest URL, or null if the link is not a well-formed hire link. */
+ export function parseHireDeepLink(link: string): string | null {
+ let u: URL;
+ try { u = new URL(link); } catch { return null; }
+ if (u.protocol !== 'munderdifflin:') return null;
+ // Both munderdifflin://hire?src= (host) and munderdifflin:hire?src= (path).
+ const action = (u.host || u.pathname.replace(/^\/+/, '')).toLowerCase();
+ if (action !== 'hire') return null;
+ const src = u.searchParams.get('src');
+ if (!src) return null;
+ let s: URL;
+ try { s = new URL(src); } catch { return null; }
+ if (!isAllowedManifestUrl(s)) return null;
+ return s.toString();
+ }
+
+ /** https everywhere; plain http is allowed ONLY for loopback (local gallery
+ * development) — a remote page can never point the app at an http manifest. */
+ export function isAllowedManifestUrl(u: URL): boolean {
+ if (u.protocol === 'https:') return true;
+ if (u.protocol !== 'http:') return false;
+ return u.hostname === 'localhost' || u.hostname === '127.0.0.1' || u.hostname === '[::1]';
+ }
+
+ /** Byte cap shared by the deep-link fetcher and the file importer. */
+ export const HIRE_MAX_BYTES = MAX_BYTES;