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

feat(floor): auto-revive wedged terminals on wake

Chaitanya Girid7f09aa0b03d
diff --git a/src/preload/index.ts b/src/preload/index.ts
index fb66d182..7c7d0831 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -308,6 +308,17 @@ export interface ToolSpan {
error?: string;
}
+/** Power-resume signal (mirrors the emitter in src/main). Fired after the Mac
+ * wakes from sleep / unlocks: `dead` lists PTY ids that were live before sleep
+ * but emitted nothing after resume (wedged terminals); `total` is how many were
+ * checked. The renderer auto-respawns exactly the `dead` ids. */
+export interface PowerResumeEvent {
+ reason: string;
+ awayMs: number | null;
+ dead: string[];
+ total: number;
+}
+
/** Closing-time progress event (mirrors src/main/closingTime.ts). */
export interface ClosingTimeEvent {
phase: 'started' | 'progress' | 'complete' | 'timeout' | 'cancelled';
@@ -585,6 +596,17 @@ const api = {
confirmClose: (): Promise<void> => ipcRenderer.invoke('app:confirmClose'),
cancelClose: (): Promise<void> => ipcRenderer.invoke('app:cancelClose'),
+ // ─── Power / wake (auto-revive wedged PTYs after sleep/lock) ────────────────
+ /** Subscribe to the main-process power-resume signal; returns an unsubscribe
+ * fn. The main process catches up after a sleep/unlock and reports the PTY
+ * ids that wedged across it in `dead` — the renderer respawns ONLY those
+ * (empty `dead[]` = no-op). Same main→renderer push pattern as onClosingTime. */
+ onPowerResume: (cb: (e: PowerResumeEvent) => void): (() => void) => {
+ const listener = (_e: IpcRendererEvent, payload: PowerResumeEvent) => cb(payload);
+ ipcRenderer.on('power:resume', listener);
+ return () => ipcRenderer.removeListener('power:resume', listener);
+ },
+
// ─── 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. */
diff --git a/src/renderer/src/hooks/useHive.ts b/src/renderer/src/hooks/useHive.ts
index 563870b8..adfca4d1 100644
--- a/src/renderer/src/hooks/useHive.ts
+++ b/src/renderer/src/hooks/useHive.ts
@@ -8,6 +8,7 @@ import {
tokenizeCommand,
type HarnessConfig
} from '@/store/config';
+import { acquireTerminal, resetTerminal } from '@/components/terminalPool';
const GOD_ID = 'god';
const GOD_PTY = `pty-${GOD_ID}`;
@@ -178,6 +179,11 @@ export function useHive(config: HarnessConfig | null): void {
// collides with /remote-control + the orientation prompt.
const bootGraceUntil = useRef<Record<string, number>>({});
const seenTerminalHandoffs = useRef<Set<string>>(new Set());
+ // Per-pty timestamp guarding auto-revive (effect #7) against a double-respawn
+ // when power-resume + screen-unlock arrive back-to-back: an id revived (or
+ // mid-revive) within REVIVE_DEBOUNCE_MS is skipped. Set BEFORE the async spawn
+ // so a re-entrant event can't race a second respawn for the same id.
+ const reviving = useRef<Record<string, number>>({});
// Reactive so the assistant bootstrap (effect #1b) re-runs once Michael is ready.
const godStatus = useStore((s) => s.godStatus);
// #5C/#7C.4 — latest circuit-breaker level per agent. When 'constrained'/
@@ -628,4 +634,85 @@ export function useHive(config: HarnessConfig | null): void {
}
});
}, [config?.onboardingComplete]);
+
+ // 7) Auto-revive wedged PTYs after the Mac sleeps/locks. Kevin's main-process
+ // keepalive catches up its schedules on wake and DETECTS terminals that were
+ // live before sleep but went silent after resume — it reports those ids on
+ // `power:resume`. We respawn EXACTLY those, resuming each agent's prior CLI
+ // session (--resume) so the terminal self-heals instead of the user clicking
+ // "Restart & Continue". This reuses the same resume-spawn flow as that button
+ // (CommandCenterPanel.restartWithModel) and restoreTeam's worktree handling.
+ // Pure addition: an empty `dead[]` is a no-op; healthy PTYs are never touched.
+ useEffect(() => {
+ if (!config?.onboardingComplete) return;
+ // Skip an id we revived (or are mid-reviving) within this window — coalesces
+ // a resume + unlock that arrive back-to-back (main also coalesces on its side).
+ const REVIVE_DEBOUNCE_MS = 8000;
+
+ const revive = async (deadId: string): Promise<void> => {
+ const now = Date.now();
+ if (now - (reviving.current[deadId] ?? 0) < REVIVE_DEBOUNCE_MS) return;
+ reviving.current[deadId] = now; // claim BEFORE any await so re-entry can't double-spawn
+ // Only respawn a PTY we actually own; never touch an unknown/healthy id.
+ const a = useStore.getState().agents.find((x) => x.ptyId === deadId);
+ if (!a) return;
+ try {
+ const cfg = await window.cth.getConfig();
+ // Isolated agents run inside their worktree (a.cwd is the base repo); re-enter
+ // it if it still exists, else fall back to the base cwd — same as restoreTeam.
+ let cwd = a.cwd;
+ if (a.worktreePath && (await window.cth.gitIsRepo(a.worktreePath))) cwd = a.worktreePath;
+ await window.cth.killPty(deadId);
+ // Soft-reset the pooled xterm in place (no-op if none): re-arm input and
+ // clear the stale frame so the revived TUI paints clean — like the button.
+ resetTerminal(deadId);
+ const provider = inferAgentProvider(a.command, a.provider);
+ // Prefer the agent's exact recorded command (same model/flags); fall back to
+ // a rebuilt one only if it predates the persisted `command` field.
+ const command = (a.command ?? '').trim() || buildSpawnCommand(cfg, a.model, provider);
+ const [exe, ...args] = tokenizeCommand(command);
+ const hive = a.isGod
+ ? { id: a.id, name: a.name, cwd, provider, isGod: true, role: 'orchestrator (god)' }
+ : a.isAssistant
+ ? { id: a.id, name: a.name, cwd, provider, isAssistant: true, role: "Michael's prep assistant" }
+ : { id: a.id, name: a.name, cwd, provider, role: a.description };
+ // Spawn at the terminal's real grid so the TUI's absolute cursor moves land
+ // in the right cells (a size mismatch scatters the redraw).
+ const entry = acquireTerminal(deadId);
+ let cols = 100, rows = 30;
+ try { entry.fit.fit(); cols = entry.term.cols; rows = entry.term.rows; } catch { /* host not sized yet */ }
+ const res = await window.cth.spawnPty({
+ id: deadId,
+ cwd,
+ command: exe,
+ provider,
+ args,
+ cols,
+ rows,
+ // The worktree (if any) already exists on disk — re-enter it, do NOT
+ // re-isolate (that conflicts on the existing path/branch).
+ isolate: false,
+ // Reattach the agent's prior session so no context is lost on revive.
+ resume: true,
+ hive
+ });
+ if (res.ok) {
+ reviving.current[deadId] = Date.now(); // re-stamp so the debounce covers the spawn
+ useStore.getState().updateAgent(a.id, { status: 'idle', action: 'revived after sleep' });
+ } else {
+ delete reviving.current[deadId]; // let a later power:resume retry it
+ console.error('[autorevive] respawn failed for', a.id, res.error);
+ }
+ } catch (err) {
+ delete reviving.current[deadId];
+ console.error('[autorevive] respawn threw for', deadId, err);
+ }
+ };
+
+ return window.cth.onPowerResume?.((e) => {
+ const dead = Array.isArray(e?.dead) ? e.dead : [];
+ if (!dead.length) return; // healthy wake — nothing wedged, no-op
+ for (const id of dead) void revive(id);
+ });
+ }, [config?.onboardingComplete]);
}