an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions
HTML agent-harnessagent-orchestrationagentsai-agentsautonomous-agentsclaude-codecodexcoding-agentsdesktop-appdeveloper-toolselectrongemini-cliharnessharness-engineeringlocal-firstmemorymulti-agentopencodeorchestrationtypescript
feat: closing time - graceful, data-loss-free shutdown via the hive
Gulum6af375d4cdd2
diff --git a/src/main/closingTime.ts b/src/main/closingTime.tsnew file mode 100644index 00000000..5e14ca50--- /dev/null+++ b/src/main/closingTime.ts@@ -0,0 +1,182 @@+/**+ * Closing Time — the graceful, data-loss-free shutdown protocol.+ *+ * Killing the PTYs mid-thought loses whatever the agents were holding in+ * working memory: uncommitted WIP, unrecorded decisions, half-updated+ * memory.md files. "Closing time" closes the floor the way a real office+ * does: the human announces it, every worker packs up and confirms, the+ * manager locks the door.+ *+ * 1. The human clicks "closing time" in the quit dialog.+ * 2. We mail the god agent a shutdown brief: broadcast closing time to the+ * team; every worker commits/parks WIP, appends state + next steps to+ * its memory.md, then replies with subject CLOSING-TIME-ACK.+ * 3. The god waits for every ACK (the harness shows live progress by+ * watching the same inbox traffic), saves its own memory, and sends a+ * message with subject CLOSING-TIME-COMPLETE.+ * 4. The router observer spots that message → the app tears down and quits.+ *+ * Everything rides the existing hive rails: inbox delivery, the idle+ * inbox-wake nudge, and Stop-hook draining already guarantee the messages+ * get acted on. This module only injects the kickoff mail and watches the+ * routed traffic — it never types into terminals.+ *+ * Runs in the Electron main process.+ */+import type { WebContents } from 'electron';+import type { HiveManager, HiveMessage } from './hive';++export type ClosingTimePhase =+ | 'started' | 'progress' | 'complete' | 'timeout' | 'cancelled';++export interface ClosingTimeEvent {+ phase: ClosingTimePhase;+ /** Workers that have ACKed so far / total workers being waited on. */+ acked: number;+ total: number;+}++/** Subject markers. Deliberately forgiving (case, -/_/space) — agents write+ * these by hand, so "Closing Time Ack" must count as well as the canonical+ * CLOSING-TIME-ACK the brief asks for. */+const ACK_RE = /CLOSING[-_\s]*TIME[-_\s]*ACK/i;+const COMPLETE_RE = /CLOSING[-_\s]*TIME[-_\s]*COMPLETE/i;++/** How long to wait before surfacing "this is taking long — force quit?".+ * Compaction or a long tool call can easily hold an ACK for a few minutes. */+const TIMEOUT_MS = 6 * 60_000;+/** Grace after COMPLETE before tearing down, so the god's final commit/log+ * writes land on disk and the floor visibly concludes. */+const TEARDOWN_GRACE_MS = 2_500;++export class ClosingTimeController {+ private active = false;+ private godId = 'god';+ private workers = new Set<string>();+ private acked = new Set<string>();+ private timeoutTimer: NodeJS.Timeout | null = null;+ private teardownTimer: NodeJS.Timeout | null = null;++ constructor(+ private hive: HiveManager,+ private getWebContents: () => WebContents | null,+ /** Called once the god concluded — runs the real teardown + app.quit(). */+ private onConcluded: () => void+ ) {}++ isActive(): boolean {+ return this.active;+ }++ /** Kick off the protocol. Returns an error string when the floor cannot run+ * it (no live god agent) so the UI can fall back to the hard quit. */+ start(): { ok: boolean; error?: string } {+ if (this.active) {+ // Re-pressed while running (e.g. from the timeout view): keep waiting.+ this.armTimeout();+ this.emitState('progress');+ return { ok: true };+ }+ const reg = this.hive.registry();+ this.godId = reg.godId ?? 'god';+ const god = reg.agents[this.godId];+ if (!god || god.archived) {+ return { ok: false, error: 'No orchestrator is running — closing time needs the god agent to collect the reports.' };+ }++ this.workers = new Set(+ Object.keys(reg.agents).filter((id) => {+ const a = reg.agents[id];+ return !a.archived && !a.isGod && !a.isAssistant && id !== this.godId;+ })+ );+ this.acked = new Set();+ this.active = true;++ const names = [...this.workers]+ .map((id) => `${reg.agents[id]?.name ?? id} (${id})`)+ .join(', ') || '(none — the floor is just you)';++ this.hive.send({+ to: 'god',+ act: 'request',+ subject: 'CLOSING TIME — run the shutdown protocol now',+ body: [+ 'The human pressed "closing time": the harness will close as soon as you confirm the floor is safe. Run this protocol now, before anything else:',+ '',+ `1. BROADCAST closing time to the team (message with "to":"broadcast"). Current workers: ${names}.`,+ ' Tell each worker to immediately: park or commit any work-in-progress safely, append its current state + concrete next steps to its memory.md, and then reply to you with a message whose subject is exactly "CLOSING-TIME-ACK".',+ '2. WAIT and keep draining your inbox until EVERY worker above has sent its CLOSING-TIME-ACK. Nudge stragglers once if needed.',+ '3. Save your own state: update board.md and append your shift summary to your memory.md.',+ `4. CONCLUDE by sending a message with "to":"human" and the subject exactly "CLOSING-TIME-COMPLETE" — the harness watches for it and closes the app. Do not send it before every worker has acked.`,+ '',+ this.workers.size === 0+ ? 'There are no workers on the floor right now — do steps 3 and 4 immediately.'+ : 'The prep assistant saves its own memory separately — do NOT wait for it and do not message it.',+ 'This is a shutdown: do not start new work and do not accept new tasks.'+ ].join('\n')+ }, 'human');++ this.armTimeout();+ this.emitState('started');+ return { ok: true };+ }++ /** Human changed their mind — stand the floor back up. */+ cancel(): void {+ if (!this.active) return;+ this.cleanup();+ this.emitState('cancelled');+ try {+ this.hive.send({+ to: 'god',+ act: 'inform',+ subject: 'CLOSING TIME CANCELLED',+ body: 'The human cancelled the shutdown — disregard the closing-time protocol and resume normal operation. Any memory saves already done are a bonus, not a problem.'+ }, 'human');+ } catch { /* best-effort */ }+ }++ /** Router observer — called by the hive for every routed message. */+ onRouted(msg: HiveMessage, targets: string[]): void {+ if (!this.active) return;+ // A worker reporting in. Counted only for known workers, and only when the+ // ACK actually reached the god (not e.g. a stray broadcast echo).+ if (ACK_RE.test(msg.subject) && this.workers.has(msg.from) && targets.includes(this.godId)) {+ if (!this.acked.has(msg.from)) {+ this.acked.add(msg.from);+ this.emitState('progress');+ }+ return;+ }+ // The god concluding. COMPLETE is only honored from the god itself — a+ // worker can't (accidentally or otherwise) shut down the whole floor.+ if (COMPLETE_RE.test(msg.subject) && msg.from === this.godId) {+ this.cleanup();+ this.active = true; // stays "active" through the grace so the UI holds+ this.emitState('complete');+ this.teardownTimer = setTimeout(() => {+ this.active = false;+ this.onConcluded();+ }, TEARDOWN_GRACE_MS);+ }+ }++ private armTimeout(): void {+ if (this.timeoutTimer) clearTimeout(this.timeoutTimer);+ this.timeoutTimer = setTimeout(() => {+ if (this.active) this.emitState('timeout');+ }, TIMEOUT_MS);+ }++ private cleanup(): void {+ if (this.timeoutTimer) { clearTimeout(this.timeoutTimer); this.timeoutTimer = null; }+ if (this.teardownTimer) { clearTimeout(this.teardownTimer); this.teardownTimer = null; }+ this.active = false;+ }++ private emitState(phase: ClosingTimePhase): void {+ const ev: ClosingTimeEvent = { phase, acked: this.acked.size, total: this.workers.size };+ try { this.getWebContents()?.send('app:closingTime', ev); } catch { /* window tore down */ }+ }+}diff --git a/src/main/hive.ts b/src/main/hive.tsindex 0cc287e8..d90f219c 100644--- a/src/main/hive.ts+++ b/src/main/hive.ts@@ -530,6 +530,16 @@ export class HiveManager {for (const t of targets) this.deliver(msg, t);this.appendLog({ kind: 'message', from: msg.from, to: msg.to, act: msg.act, subject: msg.subject, id: msg.id });this.emitMessage(msg, targets);+ // Main-process observer (e.g. the closing-time controller watching for the+ // team's ACKs and the god's COMPLETE). Best-effort, never breaks routing.+ try { this.routedObserver?.(msg, targets); } catch { /* observer error */ }+ }++ /** Observer invoked for EVERY routed message with its resolved targets.+ * Used by main-process features that react to hive traffic (closing time). */+ private routedObserver: ((msg: HiveMessage, targets: string[]) => void) | null = null;+ setRoutedObserver(cb: ((msg: HiveMessage, targets: string[]) => void) | null): void {+ this.routedObserver = cb;}/** Tell the renderer a message was routed, with its resolved recipients, sodiff --git a/src/main/index.ts b/src/main/index.tsindex 7829477b..4a30990c 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -25,6 +25,7 @@ import { listIssues, listCIRuns } from './github';import { SlackWebhookServer } from './slack';import { TelemetryCollector } from './telemetry';import { ControlRegistry } from './control';+import { ClosingTimeController } from './closingTime';const isDev = !!process.env.ELECTRON_RENDERER_URL;const ptyManager = new PtyManager();@@ -971,7 +972,9 @@ ipcMain.handle('history:search', (_evt, query: unknown, limit: unknown) =>persist.searchHistory(typeof query === 'string' ? query : '', typeof limit === 'number' ? limit : undefined));// ─── IPC: quit confirmation ─────────────────────────────────────────────────-ipcMain.handle('app:confirmClose', () => {+/** Tear the harness down and quit. Shared by the hard "kill all & quit" path+ * and the closing-time conclusion (after the god confirmed the floor saved). */+function teardownAndQuit(): void {allowQuit = true;// Each teardown step is best-effort: a throw here (e.g. a dying child or a// half-torn-down socket) must never abort the quit or pop a crash dialog.@@ -985,11 +988,28 @@ ipcMain.handle('app:confirmClose', () => {try { persist.close(); } catch (e) { console.error('[quit] persist.close:', e); }try { ptyManager.killAll(); } catch (e) { console.error('[quit] killAll:', e); }app.quit();+}+ipcMain.handle('app:confirmClose', () => {+ closingTime.cancel(); // a hard quit overrides a closing time in progress+ teardownAndQuit();});ipcMain.handle('app:cancelClose', () => {// no-op — modal will close on the renderer side});+// ─── IPC: closing time (graceful, data-loss-free shutdown) ──────────────────+// The third quit-dialog button. The god broadcasts closing time, every worker+// saves its memory and ACKs, the god concludes with CLOSING-TIME-COMPLETE —+// only then does the harness tear down. See closingTime.ts for the protocol.+const closingTime = new ClosingTimeController(+ hive,+ () => liveWebContents(),+ () => teardownAndQuit()+);+hive.setRoutedObserver((msg, targets) => closingTime.onRouted(msg, targets));+ipcMain.handle('app:startClosingTime', () => closingTime.start());+ipcMain.handle('app:cancelClosingTime', () => closingTime.cancel());+// ─── IPC: full reset (wipe data + config, relaunch into onboarding) ──────────ipcMain.handle('app:resetAll', () => {allowQuit = true;diff --git a/src/preload/index.ts b/src/preload/index.tsindex d44d7060..28dc3942 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -191,6 +191,14 @@ export interface ToolSpan {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;@@ -388,6 +396,22 @@ const api = {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. */diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsxindex 497a5189..f9f6b088 100644--- a/src/renderer/src/App.tsx+++ b/src/renderer/src/App.tsx@@ -10,7 +10,7 @@ import { AgentStrip } from '@/components/AgentStrip';import { AddAgentModal } from '@/components/AddAgentModal';import { MichaelBooting } from '@/components/MichaelBooting';import { OnboardingWizard } from '@/components/OnboardingWizard';-import { QuitWarningModal } from '@/components/QuitWarningModal';+import { QuitWarningModal, type ClosingTimeState } from '@/components/QuitWarningModal';import { SettingsModal } from '@/components/SettingsModal';import { PixelPanel } from '@/components/PixelPanel';import { PixelButton } from '@/components/PixelButton';@@ -36,6 +36,7 @@ export function App() {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@@ -48,6 +49,24 @@ export function App() {// Quit warning subscriptionuseEffect(() => window.cth.onCloseRequested((info) => setQuitWarn(info)), []);+ // 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);@@ -254,8 +273,14 @@ export function App() {{quitWarn && (<QuitWarningModalptyCount={quitWarn.ptyCount}- onCancel={() => { window.cth.cancelClose(); setQuitWarn(null); }}+ closing={closing}+ onCancel={() => {+ if (closing) cancelClosingTime();+ window.cth.cancelClose();+ setQuitWarn(null);+ }}onConfirm={async () => { await window.cth.confirmClose(); }}+ onClosingTime={startClosingTime}/>)}diff --git a/src/renderer/src/components/Icon.tsx b/src/renderer/src/components/Icon.tsxindex 257b0042..1a98f083 100644--- a/src/renderer/src/components/Icon.tsx+++ b/src/renderer/src/components/Icon.tsx@@ -6,7 +6,7 @@ import { CSSProperties } from 'react';export type IconName =| 'gear' | 'plus' | 'x' | 'check' | 'arrow-right' | 'pause' | 'play'| 'bell' | 'folder' | 'terminal' | 'code' | 'web' | 'mcp' | 'sparkle'- | 'expand' | 'minimize';+ | 'expand' | 'minimize' | 'clock';interface IconDef {ink: string; // primary color path d@@ -81,6 +81,12 @@ const paths: Record<IconName, IconDef> = {minimize: {accentColor: 'var(--cth-sky)',ink: 'M5 1h2v6H1V5h4V1zm4 0h2v4h4v2H9V1zM1 9h6v6H5v-4H1V9zm8 0h6v2h-4v4H9V9z'+ },+ // Wall clock at five o'clock — closing time. Ring as an evenodd cutout,+ // hands as a second subpath (minute hand up, hour hand toward 5).+ clock: {+ accentColor: 'var(--cth-lemon)',+ ink: 'M5 1h6v1h2v2h1v2h1v4h-1v2h-1v2h-2v1H5v-1H3v-2H2V8H1V6h1V4h1V2h2V1zm0 2H4v1H3v2H2v4h1v2h1v1h1v1h6v-1h1v-1h1v-2h1V6h-1V4h-1V3h-1V2H5v1zm2 1h2v4h2v1h1v1h-1v1h-1v-1H9v1H7V4z'}};diff --git a/src/renderer/src/components/QuitWarningModal.tsx b/src/renderer/src/components/QuitWarningModal.tsxindex 0b6df3ae..184b070b 100644--- a/src/renderer/src/components/QuitWarningModal.tsx+++ b/src/renderer/src/components/QuitWarningModal.tsx@@ -3,13 +3,27 @@ import { PixelPanel } from './PixelPanel';import { PixelButton } from './PixelButton';import { Icon } from './Icon';+/** Renderer-side closing-time view state. Mirrors the main process's+ * ClosingTimeEvent phases, plus a local 'error' for a failed start. */+export interface ClosingTimeState {+ phase: 'started' | 'progress' | 'complete' | 'timeout' | 'error';+ acked: number;+ total: number;+ error?: string;+}+export interface QuitWarningModalProps {ptyCount: number;+ /** Non-null while the closing-time protocol runs — switches the dialog into+ * the "wrapping up the floor" progress view. */+ closing?: ClosingTimeState | null;onCancel: () => void;onConfirm: () => void;+ /** Start the graceful shutdown (the third button). */+ onClosingTime?: () => void;}-export function QuitWarningModal({ ptyCount, onCancel, onConfirm }: QuitWarningModalProps) {+export function QuitWarningModal({ ptyCount, closing, onCancel, onConfirm, onClosingTime }: QuitWarningModalProps) {const [busy, setBusy] = useState(false);const confirm = async () => {@@ -18,9 +32,11 @@ export function QuitWarningModal({ ptyCount, onCancel, onConfirm }: QuitWarningM// No need to clear busy — the app is quitting.};+ const inClosingTime = !!closing && closing.phase !== 'error';+return (<div- onClick={onCancel}+ onClick={inClosingTime ? undefined : onCancel}style={{position: 'fixed', inset: 0,background: 'rgba(26, 19, 32, 0.7)',@@ -32,56 +48,152 @@ export function QuitWarningModal({ ptyCount, onCancel, onConfirm }: QuitWarningMonClick={(e) => e.stopPropagation()}style={{ width: 480, maxWidth: '92vw' }}>- <PixelPanel variant="dialog" title="QUITTING NOW?" noPadding>+ <PixelPanel variant="dialog" title={inClosingTime ? 'CLOSING TIME' : 'QUITTING NOW?'} noPadding><div style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 16 }}>- <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>- <div style={{- width: 32, height: 32,- background: 'var(--cth-coral-light)',- boxShadow: 'inset 0 0 0 2px var(--cth-ink-900)',- display: 'flex', alignItems: 'center', justifyContent: 'center',- flexShrink: 0- }}>- <Icon name="bell" />- </div>- <div style={{ flex: 1 }}>+ {inClosingTime ? (+ <>+ {/* ── Graceful shutdown in progress ──────────────────────── */}+ <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>+ <div style={{+ width: 32, height: 32,+ background: closing!.phase === 'complete' ? 'var(--cth-mint-light, #cdeccd)' : 'var(--cth-lemon-light, #f6ecc4)',+ boxShadow: 'inset 0 0 0 2px var(--cth-ink-900)',+ display: 'flex', alignItems: 'center', justifyContent: 'center',+ flexShrink: 0+ }}>+ <Icon name="bell" />+ </div>+ <div style={{ flex: 1 }}>+ <div style={{+ fontFamily: 'var(--cth-font-display)',+ fontSize: 12, lineHeight: '20px',+ color: 'var(--cth-ink-900)',+ marginBottom: 4+ }}>+ {closing!.phase === 'complete'+ ? 'FLOOR SAVED — SEE YOU TOMORROW'+ : closing!.phase === 'timeout'+ ? 'STILL WRAPPING UP…'+ : 'WRAPPING UP THE FLOOR'}+ </div>+ <div style={{ fontSize: 15, lineHeight: '22px', color: 'var(--cth-ink-700)' }}>+ {closing!.phase === 'complete' ? (+ <>Every agent saved its memory and the orchestrator confirmed the+ shutdown. The harness closes itself in a moment.</>+ ) : (+ <>The orchestrator broadcast closing time. Every worker parks its+ work, saves its memory, and reports back — the app closes only+ after the orchestrator confirms nothing will be lost.</>+ )}+ </div>+ </div>+ </div>++ {/* ACK progress */}<div style={{- fontFamily: 'var(--cth-font-display)',- fontSize: 12, lineHeight: '20px',- color: 'var(--cth-ink-900)',- marginBottom: 4+ padding: 8,+ background: 'var(--cth-cream-200)',+ boxShadow: 'inset 0 0 0 1px var(--cth-ink-700)',+ fontSize: 13, lineHeight: '18px',+ color: 'var(--cth-ink-700)',+ fontFamily: 'var(--cth-font-display)'}}>- {ptyCount} {ptyCount === 1 ? 'AGENT' : 'AGENTS'} STILL RUNNING+ {closing!.total > 0+ ? `${closing!.acked} / ${closing!.total} WORKERS CONFIRMED${closing!.acked >= closing!.total ? ' — WAITING FOR THE ORCHESTRATOR' : ''}`+ : 'NO WORKERS ON THE FLOOR — WAITING FOR THE ORCHESTRATOR'}+ {closing!.phase === 'timeout' && (+ <div style={{ marginTop: 6, fontFamily: 'var(--cth-font-body, inherit)' }}>+ This is taking a while (an agent may be mid-compaction or deep in a+ tool call). Keep waiting, or force quit and accept the data loss.+ </div>+ )}+ </div>++ <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>+ {closing!.phase !== 'complete' && (+ <>+ <PixelButton variant="secondary" size="md" onClick={onCancel} disabled={busy}>+ cancel — back to work+ </PixelButton>+ <PixelButton variant="destructive" size="md" onClick={confirm} disabled={busy}>+ {busy ? 'killing...' : 'force quit now'}+ </PixelButton>+ </>+ )}+ </div>+ </>+ ) : (+ <>+ {/* ── The classic quit warning ────────────────────────────── */}+ <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>+ <div style={{+ width: 32, height: 32,+ background: 'var(--cth-coral-light)',+ boxShadow: 'inset 0 0 0 2px var(--cth-ink-900)',+ display: 'flex', alignItems: 'center', justifyContent: 'center',+ flexShrink: 0+ }}>+ <Icon name="bell" />+ </div>+ <div style={{ flex: 1 }}>+ <div style={{+ fontFamily: 'var(--cth-font-display)',+ fontSize: 12, lineHeight: '20px',+ color: 'var(--cth-ink-900)',+ marginBottom: 4+ }}>+ {ptyCount} {ptyCount === 1 ? 'AGENT' : 'AGENTS'} STILL RUNNING+ </div>+ <div style={{ fontSize: 15, lineHeight: '22px', color: 'var(--cth-ink-700)' }}>+ Closing the harness will terminate{' '}+ {ptyCount === 1 ? 'the running claude session' : `all ${ptyCount} running claude sessions`}{' '}+ and discard any unsaved progress they were holding in memory. The conversation+ history inside each session is lost when the PTY exits.+ </div>+ </div></div>- <div style={{ fontSize: 15, lineHeight: '22px', color: 'var(--cth-ink-700)' }}>- Closing the harness will terminate{' '}- {ptyCount === 1 ? 'the running claude session' : `all ${ptyCount} running claude sessions`}{' '}- and discard any unsaved progress they were holding in memory. The conversation- history inside each session is lost when the PTY exits.++ <div style={{+ padding: 8,+ background: 'var(--cth-cream-200)',+ boxShadow: 'inset 0 0 0 1px var(--cth-ink-700)',+ fontSize: 13, lineHeight: '18px',+ color: 'var(--cth-ink-700)'+ }}>+ Tip: <strong>closing time</strong> is the safe way out — the orchestrator has+ every agent commit its work and save its memory, and the app closes itself+ once the whole floor has confirmed. No data loss.</div>- </div>- </div>- <div style={{- padding: 8,- background: 'var(--cth-cream-200)',- boxShadow: 'inset 0 0 0 1px var(--cth-ink-700)',- fontSize: 13, lineHeight: '18px',- color: 'var(--cth-ink-700)'- }}>- Tip: leave the harness open in the background if you want sessions to keep- working. You can detach individual agents by clicking <Icon name="x" /> on- their detail panel.- </div>+ {closing?.phase === 'error' && (+ <div style={{+ padding: 8,+ background: 'var(--cth-coral-light)',+ boxShadow: 'inset 0 0 0 1px var(--cth-ink-700)',+ fontSize: 13, lineHeight: '18px',+ color: 'var(--cth-ink-900)'+ }}>+ {closing.error ?? 'Closing time could not start.'}+ </div>+ )}- <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>- <PixelButton variant="secondary" size="md" onClick={onCancel} disabled={busy}>- keep them running- </PixelButton>- <PixelButton variant="destructive" size="md" onClick={confirm} disabled={busy}>- {busy ? 'killing...' : `kill ${ptyCount === 1 ? 'it' : 'all'} & quit`}- </PixelButton>- </div>+ <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, flexWrap: 'wrap' }}>+ <PixelButton variant="secondary" size="md" onClick={onCancel} disabled={busy}>+ keep them running+ </PixelButton>+ {onClosingTime && (+ <PixelButton variant="primary" size="md" onClick={onClosingTime} disabled={busy}>+ <span style={{ display: 'inline-flex', gap: 6, alignItems: 'center' }}>+ <Icon name="clock" /> closing time+ </span>+ </PixelButton>+ )}+ <PixelButton variant="destructive" size="md" onClick={confirm} disabled={busy}>+ {busy ? 'killing...' : `kill ${ptyCount === 1 ? 'it' : 'all'} & quit`}+ </PixelButton>+ </div>+ </>+ )}</div></PixelPanel></div>diff --git a/src/renderer/src/hooks/useHive.ts b/src/renderer/src/hooks/useHive.tsindex e2bcf6fe..f32783d6 100644--- a/src/renderer/src/hooks/useHive.ts+++ b/src/renderer/src/hooks/useHive.ts@@ -408,6 +408,22 @@ export function useHive(config: HarnessConfig | null): void {return () => clearInterval(iv);}, [config?.onboardingComplete]);+ // 3b) Closing time: the hive mail rails cover god + workers, but the prep+ // assistant is send-only (no inbox) — the god is even told NOT to wait+ // for it. So when the protocol starts, the harness itself asks the+ // assistant to save its memory, best-effort, directly via its terminal.+ useEffect(() => {+ return window.cth.onClosingTime?.((ev) => {+ if (ev.phase !== 'started') return;+ const asst = useStore.getState().agents.find((a) => a.isAssistant && a.ptyId);+ if (!asst?.ptyId) return;+ void submitToPty(+ asst.ptyId,+ 'CLOSING TIME — the harness is shutting down. Append your durable learnings and any in-progress context to your memory.md NOW, then stop. Do not start new work.'+ );+ });+ }, []);+// 4) Drain each agent's queued messages to its terminal, one at a time, the// moment the agent goes idle. This is what lets the user keep sending// messages while the agent's "cloud terminal" is mid-run: the messages