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

fix: recreate the resume terminal only after spawnPty accepts the replacement (#575)

Zhen Luo829598be4301
diff --git a/src/renderer/src/components/CommandCenterPanel.tsx b/src/renderer/src/components/CommandCenterPanel.tsx
index 11b28c66..60806ebc 100644
--- a/src/renderer/src/components/CommandCenterPanel.tsx
+++ b/src/renderer/src/components/CommandCenterPanel.tsx
@@ -469,19 +469,7 @@ function FloorTab({ seed }: { seed: { text: string; seq: number } }) {
if (!killed.ok && !/^no pty:/.test(killed.error ?? '')) {
throw new Error(killed.error ?? 'Could not stop the current process.');
}
- if (resume) {
- // A blank xterm can retain corrupt renderer/DOM/subscription state even
- // after its PTY is healthy. Throw that one terminal away, acquire its
- // replacement BEFORE spawning (so startup output has a listener), then
- // bump the key so React remounts only this agent's terminal card.
- disposeTerminal(a.ptyId);
- acquireTerminal(a.ptyId);
- updateAgent(a.id, {
- terminalGeneration: (a.terminalGeneration ?? 0) + 1,
- status: 'idle',
- action: 'recreating terminal…'
- });
- } else {
+ if (!resume) {
resetTerminal(a.ptyId);
}
const command = buildSpawnCommand(cfg, model, provider);
@@ -512,6 +500,25 @@ function FloorTab({ seed }: { seed: { text: string; seq: number } }) {
if (resume && res.resumed !== true) {
throw new Error('Resume was refused; no replacement session was accepted.');
}
+ if (resume) {
+ // The replacement is accepted, so NOW it is safe to throw the old
+ // terminal away. (It used to run BEFORE spawnPty, so one of the throws
+ // above left a fresh blank xterm in the pool with the scrollback gone
+ // forever — node-pty keeps none — and the label stuck at
+ // 'recreating terminal…'.) A blank xterm can retain corrupt
+ // renderer/DOM/subscription state even after its PTY is healthy, which
+ // is why the resume path replaces it at all; the spawn answer beat the
+ // CLI's first frame, so no startup output can be missed.
+ disposeTerminal(a.ptyId);
+ acquireTerminal(a.ptyId);
+ // Bump the key so React remounts only this agent's terminal card; the
+ // remount's attach re-requests a PTY redraw for anything it raced.
+ updateAgent(a.id, {
+ terminalGeneration: (a.terminalGeneration ?? 0) + 1,
+ status: 'idle',
+ action: 'recreating terminal…'
+ });
+ }
if (res.ok) {
// Record the model even on a resume. A same-provider model change now
// RESUMES the session (that is the point — you keep the conversation and
diff --git a/test/fixtures/bug-14-main.cjs b/test/fixtures/bug-14-main.cjs
new file mode 100644
index 00000000..f73186d9
--- /dev/null
+++ b/test/fixtures/bug-14-main.cjs
@@ -0,0 +1,87 @@
+'use strict';
+/**
+ * Electron fixture for the restart-terminal regression test
+ * (test/restart-terminal-preserve.cjs). Spawns via the outer plain-node driver.
+ *
+ * Boots a hidden BrowserWindow with nodeIntegration and runs the renderer
+ * payload (test/fixtures/bug-14.renderer.js) via webContents.executeJavaScript —
+ * the same protocol as test/fixtures/quit-sweep-main.cjs. The payload's result
+ * JSON arrives over ipcRenderer 'bug14:result'; it is written to the
+ * --result-file path and the app exits 0. Timeouts and crashes exit non-zero
+ * with the error inside the result file.
+ *
+ * The page loads a blank file:// document (not data:) so localStorage has a
+ * real, writable origin — the same situation as the packaged app.
+ */
+const { app, BrowserWindow, ipcMain } = require('electron');
+const fs = require('fs');
+const os = require('os');
+const path = require('path');
+
+const args = process.argv.slice(2);
+let resultFile = path.join(os.tmpdir(), 'bug14-result.json');
+let rendererJs = path.join(__dirname, 'bug-14.renderer.js');
+let repo = process.cwd();
+let blankHtml = '';
+for (const a of args) {
+ if (a.startsWith('--result-file=')) resultFile = a.slice('--result-file='.length);
+ else if (a.startsWith('--renderer=')) rendererJs = a.slice('--renderer='.length);
+ else if (a.startsWith('--repo=')) repo = a.slice('--repo='.length);
+ else if (a.startsWith('--blank=')) blankHtml = a.slice('--blank='.length);
+}
+
+function bail(message, code) {
+ try {
+ fs.writeFileSync(resultFile, JSON.stringify({ error: message }));
+ } catch { /* last resort */ }
+ console.error('[bug14-fixture] ' + message);
+ app.exit(code);
+}
+
+const TIMEOUT_MS = 90_000;
+const timer = setTimeout(() => bail('fixture self-timeout after ' + TIMEOUT_MS + 'ms', 3), TIMEOUT_MS);
+if (timer.unref) timer.unref();
+
+process.on('uncaughtException', (e) => bail('uncaughtException: ' + (e && e.stack || String(e)), 4));
+process.on('unhandledRejection', (e) => bail('unhandledRejection: ' + (e && e.stack || String(e)), 4));
+
+let got = false;
+ipcMain.on('bug14:result', (_ev, json) => {
+ if (got) return;
+ got = true;
+ clearTimeout(timer);
+ try { fs.writeFileSync(resultFile, json); } catch { /* ignore */ }
+ app.exit(0);
+});
+
+app.whenReady().then(async () => {
+ const win = new BrowserWindow({
+ show: false,
+ width: 1600,
+ height: 1200,
+ webPreferences: {
+ nodeIntegration: true,
+ contextIsolation: false,
+ backgroundThrottling: false
+ }
+ });
+
+ // A blank page on a file:// origin: localStorage works, no network. The
+ // driver creates the file (in tmp) and passes it with --blank=.
+ const blankUrl = 'file:///' + blankHtml.split(path.sep).join('/');
+ await win.loadURL(blankUrl);
+
+ const payload = fs.readFileSync(rendererJs, 'utf8');
+ const bootstrap = 'globalThis.__BUG14_REPO__=' + JSON.stringify(repo) + ';';
+ await win.webContents.executeJavaScript(bootstrap + '\n' + payload, true);
+
+ // Normal completion ships the result over IPC, which exits the app. If the
+ // payload returned early without the IPC firing, fail loudly after a grace
+ // period rather than hanging.
+ setTimeout(() => {
+ if (!got) bail('renderer finished without shipping a result', 5);
+ }, 3000);
+}).catch((e) => {
+ clearTimeout(timer);
+ bail('fixture main threw: ' + (e && e.stack || String(e)), 2);
+});
diff --git a/test/fixtures/bug-14.renderer.js b/test/fixtures/bug-14.renderer.js
new file mode 100644
index 00000000..70c2eb67
--- /dev/null
+++ b/test/fixtures/bug-14.renderer.js
@@ -0,0 +1,419 @@
+'use strict';
+/**
+ * In-page payload for test/restart-terminal-preserve.test.cjs. Runs INSIDE the
+ * real Electron renderer (nodeIntegration:true, contextIsolation:false) via
+ * webContents.executeJavaScript.
+ *
+ * It mounts the REAL CommandCenterPanel (src/renderer/src/components/
+ * CommandCenterPanel.tsx — the component that owns restartWithModel) against a
+ * scripted fake `window.cth` bridge, opens the floor tab, then clicks
+ * "restart & continue" on three agents:
+ *
+ * A spawnPty answers {ok:false,...} → the `!res.ok` throw
+ * B spawnPty answers {ok:true} with no `resumed` → the "resume was refused"
+ * throw (this is exactly what the main-process installer early-return
+ * answers when --resume is declined, src/main/index.ts:2909-2915)
+ * C spawnPty answers {ok:true, resumed:true} → success CONTROL: proves
+ * the flow still recreates the terminal once the replacement is
+ * known-good — the destroy may only ever run AFTER the spawn answer
+ *
+ * For every scenario it records the IPC call ORDER, the terminalPool entry
+ * identity before/after, the xterm buffer contents before/after, the store's
+ * agent action/status/terminalGeneration, and whether the label self-corrects —
+ * then ships the snapshot to the fixture main over ipcRenderer.
+ *
+ * Every line of restartWithModel, FloorTab, terminalPool's dispose/acquire and
+ * the zustand store is the REAL shipped code, loaded through a TS/TSX transpile
+ * loader (test/load-ts.cjs extended with JSX, '@/…'/'@shared/…' aliases and
+ * .json/.css imports). The only fakes live at module boundaries:
+ * - window.cth bridge: scripted IPC answers (no real PTY, no network)
+ * - pixi.js / react-markdown / remark-gfm: ESM-only under this Electron node,
+ * required only by tabs never mounted here → stub objects
+ */
+(async () => {
+ const REPO = globalThis.__BUG14_REPO__;
+ const fs = require('fs');
+ const path = require('path');
+ const NM = path.join(REPO, 'node_modules');
+
+ // ─── 0. window.cth bridge FIRST (the store reads it at module load) ─────────
+ const CWD = 'D:\\bug14\\proj';
+ const calls = [];
+ const record = (fn, extra) => { const c = Object.assign({ fn }, extra); calls.push(c); return c; };
+
+ const SESSION_IDS = {
+ 'bug14-a': 'sess-aaa',
+ 'bug14-b': 'sess-bbb',
+ 'bug14-c': 'sess-ccc'
+ };
+ const AGENT_IDS = Object.keys(SESSION_IDS);
+
+ // Scripted spawn answers — the ONLY failure injection in the whole repro.
+ const spawnBehavior = {
+ // mirrors the real failure contract of src/main/pty.ts spawn()
+ 'pty-bug14-a': () => ({ ok: false, error: 'cwd does not exist: ' + CWD }),
+ // mirrors the requireResume early-return (src/main/index.ts:2909-2915):
+ // ok:true with `resumed` unset — a refused resume
+ 'pty-bug14-b': () => ({ ok: true }),
+ // healthy resume (control)
+ 'pty-bug14-c': () => ({ ok: true, resumed: true })
+ };
+
+ const fakeCth = {
+ getConfig: async () => ({
+ onboardingComplete: true,
+ harnessHome: 'D:\\bug14\\hive',
+ registeredRepos: [],
+ autoMode: false,
+ defaultCommand: 'claude',
+ defaultModel: 'claude-fable-5-1'
+ }),
+ updateConfig: async () => ({ ok: true }),
+ killPty: async (id) => { record('killPty', { ptyId: id }); return { ok: true }; },
+ spawnPty: async (opts) => {
+ record('spawnPty', {
+ ptyId: opts.id, resume: true, requireResume: !!opts.requireResume,
+ resumeSessionId: opts.resumeSessionId, command: opts.command, args: opts.args
+ });
+ const behave = spawnBehavior[opts.id];
+ return behave ? behave() : { ok: true, resumed: true };
+ },
+ onPtyData: () => () => {},
+ onPtyExit: () => () => {},
+ onPtyRelaunch: () => () => {},
+ writePty: () => {},
+ resizePty: (id) => { record('resizePty', { ptyId: id }); },
+ redrawPty: (id) => { record('redrawPty', { ptyId: id }); },
+ listPtys: async () => [],
+ controlSnapshot: async () => ({ autoDeliveryPaused: false }),
+ controlAutoDelivery: async () => ({}),
+ telemetrySnapshot: async () => ({ usage: [], spans: {} }),
+ onTelemetryEvent: () => () => {},
+ onBreakerState: () => () => {},
+ telemetrySpans: async () => [],
+ hiveRegistry: async () => ({
+ godId: null,
+ agents: Object.fromEntries(AGENT_IDS.map((id) => [id, {
+ id, name: id, cwd: CWD, status: 'idle', lastSeen: 1, sessionId: SESSION_IDS[id]
+ }]))
+ }),
+ resolveSessionCwd: async () => CWD,
+ hiveSend: async () => ({ ok: true }),
+ hiveTasks: async () => [],
+ hivePatchTask: async () => ({ ok: true }),
+ hiveDeleteTask: async () => ({ ok: true }),
+ hiveLog: async () => [],
+ hiveBoard: async () => '',
+ hiveMemory: async () => '',
+ searchMemory: async () => ({ ok: true, results: [], engine: 'none' }),
+ textSearch: async () => ({ ok: true, results: [] }),
+ listWorkers: async () => ({ workers: [] }),
+ stopWorker: async () => ({ ok: true }),
+ listMissions: async () => [],
+ onMissionsUpdated: () => () => {},
+ saveMissions: async () => ({}),
+ getContextTrigger: async () => null,
+ setContextTrigger: async () => ({}),
+ listWebhooks: async () => [],
+ saveWebhooks: async () => ({}),
+ deleteWebhook: async () => ({}),
+ webhooksStatus: async () => ({ enabled: false }),
+ getOrgTrigger: async () => null,
+ setOrgTrigger: async () => ({}),
+ getContextRules: async () => [],
+ githubIssues: async () => ({ ok: false, error: 'not configured' }),
+ setAgentTokenCap: async () => ({ ok: true }),
+ historyAdd: async () => ({}),
+ trackMessageSent: async () => ({}),
+ attachFiles: async () => ({ ok: false, files: [] }),
+ attachFilesPicker: async () => ({ ok: false, files: [] }),
+ pathForFile: () => '',
+ saveClipboardImage: async () => ({ ok: false }),
+ copyToClipboard: async () => ({}),
+ readClipboard: async () => '',
+ readClipboardSync: () => '',
+ statAbs: async () => ({ exists: false }),
+ statAbsSync: () => null,
+ revealPath: async () => {},
+ openTerminalAt: () => {},
+ openExternal: async () => {},
+ skillsLocal: async () => [],
+ skillsCatalog: async () => ({ ok: true, catalog: [] }),
+ skillsInstall: async () => ({ ok: false }),
+ skillsUninstall: async () => ({ ok: true }),
+ skillsReveal: async () => {},
+ readBinary: async () => ({ ok: false }),
+ freeflowTranscribe: async () => ({ ok: false }),
+ rosterReadSync: () => null,
+ harnessHomeSync: () => 'D:\\bug14\\hive',
+ harnessHomeSyncRead: () => 'D:\\bug14\\hive',
+ rosterWrite: () => {}
+ };
+ window.cth = fakeCth;
+
+ // ─── 1. TS/TSX transpile loader (test/load-ts.cjs + JSX + aliases) ──────────
+ const ts = require(path.join(NM, 'typescript'));
+ const cache = new Map();
+
+ function resolveFrom(fromDir, request) {
+ let req = request;
+ let suffix = null;
+ const m = /^(.+)\?(url|raw)$/.exec(req);
+ if (m) { req = m[1]; suffix = m[2]; }
+
+ let base;
+ if (req.startsWith('@/')) base = path.join(REPO, 'src', 'renderer', 'src', req.slice(2));
+ else if (req.startsWith('@shared/')) base = path.join(REPO, 'src', 'shared', req.slice('@shared/'.length));
+ else if (req.startsWith('.')) base = path.resolve(fromDir, req);
+ else return null;
+
+ for (const cand of [base, `${base}.ts`, `${base}.tsx`, path.join(base, 'index.ts'),
+ path.join(base, 'index.tsx'), `${base}.json`]) {
+ if (fs.existsSync(cand) && fs.statSync(cand).isFile()) return { file: cand, suffix };
+ }
+ return null;
+ }
+
+ function loadFile(filename) {
+ const cached = cache.get(filename);
+ if (cached) return cached.exports;
+ if (filename.endsWith('.json')) {
+ const mod = { exports: JSON.parse(fs.readFileSync(filename, 'utf8')) };
+ cache.set(filename, mod);
+ return mod.exports;
+ }
+ const source = fs.readFileSync(filename, 'utf8');
+ const out = ts.transpileModule(source, {
+ compilerOptions: {
+ module: ts.ModuleKind.CommonJS,
+ target: ts.ScriptTarget.ES2022,
+ jsx: ts.JsxEmit.ReactJSX,
+ strict: true,
+ esModuleInterop: true
+ },
+ fileName: filename,
+ reportDiagnostics: true
+ });
+ if (out.diagnostics && out.diagnostics.length) {
+ throw new Error(ts.formatDiagnosticsWithColorAndContext(out.diagnostics, {
+ getCurrentDirectory: () => REPO,
+ getCanonicalFileName: (n) => n,
+ getNewLine: () => '\n'
+ }));
+ }
+ const mod = { exports: {} };
+ cache.set(filename, mod);
+ const localRequire = (request) => {
+ if (request.endsWith('.css')) return {};
+ if (request.startsWith('.') || request.startsWith('@/') || request.startsWith('@shared/')) {
+ const hit = resolveFrom(path.dirname(filename), request);
+ if (hit) {
+ if (hit.suffix === 'raw') return fs.readFileSync(hit.file, 'utf8');
+ if (hit.suffix === 'url') return hit.file;
+ return loadFile(hit.file);
+ }
+ throw new Error(`bug14 loader: cannot resolve '${request}' from ${filename}`);
+ }
+ return requireBare(request);
+ };
+ const run = new Function('module', 'exports', 'require', '__filename', '__dirname', out.outputText);
+ run(mod, mod.exports, localRequire, filename, path.dirname(filename));
+ return mod.exports;
+ }
+
+ // Bare specifiers must resolve from the REPO's node_modules regardless of
+ // where the fixture page itself lives (it is a tmp file).
+ const { createRequire } = require('module');
+ const repoRequire = createRequire(path.join(REPO, 'package.json'));
+
+ function requireBare(request) {
+ if (request === 'pixi.js') return pixiStub;
+ if (request === 'react-markdown') return reactMarkdownStub;
+ if (request === 'remark-gfm') return { default: function remarkGfmStub() { return {}; } };
+ return repoRequire(request); // xterm, codemirror, react, zustand… all resolve from the repo
+ }
+
+ // ESM-only under this Electron node — stubbed at the require boundary. They
+ // are only module-loaded for tabs never mounted in this scenario, so the
+ // stubs cannot change the behavior under test.
+ const pixiStub = new Proxy({}, {
+ get(_t, key) {
+ if (key === '__esModule') return false;
+ return function PixiStub() {};
+ }
+ });
+ const reactMarkdownStub = function ReactMarkdownStub() { return null; };
+
+ // addon-fit (and any module like it) needs `self` before first require.
+ if (typeof globalThis.self === 'undefined') globalThis.self = globalThis;
+
+ function loadTs(rel) { return loadFile(path.join(REPO, rel)); }
+
+ // ─── 2. load the REAL store + terminal pool, seed the roster ────────────────
+ const storeExports = loadTs('src/renderer/src/store/store.ts');
+ const useStore = storeExports.useStore;
+ const poolModule = loadTs('src/renderer/src/components/terminalPool.ts');
+ const realAcquire = poolModule.acquireTerminal;
+ const realDispose = poolModule.disposeTerminal;
+
+ // Recording-only pass-throughs for the pool pair: restartWithModel's destroy
+ // ordering relative to the spawn answer is the fact under test, and the raw
+ // IPC bridge cannot see it. These NEVER defer or skip — they log and delegate;
+ // the order they reveal is the component's own call order, i.e. the behavior
+ // under test, unchanged.
+ poolModule.disposeTerminal = function bug14RecordDispose(ptyId) {
+ record('disposeTerminal', { ptyId });
+ return realDispose(ptyId);
+ };
+ poolModule.acquireTerminal = function bug14RecordAcquire(ptyId, theme, fontSize) {
+ record('acquireTerminal', { ptyId });
+ return realAcquire(ptyId, theme, fontSize);
+ };
+
+ const AGENTS = [
+ {
+ id: 'bug14-a', name: 'Ada', character: 'pam', accent: 'mint',
+ description: 'watches the ledger', project: 'bug14', tmuxTarget: 't-a',
+ cwd: CWD, status: 'working', action: 'reviewing the roadmap…', progress: 0,
+ ptyId: 'pty-bug14-a', command: 'claude', provider: 'claude', model: 'claude-fable-5-1',
+ isGod: false
+ },
+ {
+ id: 'bug14-b', name: 'Ben', character: 'jim', accent: 'sky',
+ description: 'watches the queue', project: 'bug14', tmuxTarget: 't-b',
+ cwd: CWD, status: 'working', action: 'reviewing the shipped build…', progress: 0,
+ ptyId: 'pty-bug14-b', command: 'claude', provider: 'claude', model: 'claude-fable-5-1',
+ isGod: false
+ },
+ {
+ id: 'bug14-c', name: 'Cy', character: 'kevin', accent: 'lemon',
+ description: 'watches the tests', project: 'bug14', tmuxTarget: 't-c',
+ cwd: CWD, status: 'working', action: 'reviewing the backlog…', progress: 0,
+ ptyId: 'pty-bug14-c', command: 'claude', provider: 'claude', model: 'claude-fable-5-1',
+ isGod: false
+ }
+ ];
+ useStore.setState({ agents: AGENTS, selectedId: 'bug14-a' });
+
+ // ─── 3. seed scrollback into the pooled terminals (as a live session would) ─
+ // Direct term.write() — deliberately NOT through window.cth.onPtyData, so
+ // entry.onData stays unset and usePtyParser's 4s idle rewrite never fires.
+ const MARK = {
+ 'pty-bug14-a': ['IMPORTANT SCROLLBACK A1', 'IMPORTANT SCROLLBACK A2'],
+ 'pty-bug14-b': ['IMPORTANT SCROLLBACK B1', 'IMPORTANT SCROLLBACK B2'],
+ 'pty-bug14-c': ['IMPORTANT SCROLLBACK C1', 'IMPORTANT SCROLLBACK C2']
+ };
+ const writeTerm = (term, text) => new Promise((resolve) => {
+ term.write(text, () => setTimeout(resolve, 30));
+ });
+ const readBuf = (term) => {
+ const buf = term.buffer.active;
+ const out = [];
+ const n = Math.min(buf.length, 6);
+ for (let i = 0; i < n; i++) {
+ try { out.push(buf.getLine(i).translateToString(true)); } catch { out.push('<unreadable>'); }
+ }
+ return out;
+ };
+
+ const entriesBefore = {};
+ const buffersBefore = {};
+ for (const agent of AGENTS) {
+ const entry = poolModule.acquireTerminal(agent.ptyId);
+ entriesBefore[agent.ptyId] = entry;
+ for (const line of MARK[agent.ptyId]) {
+ await writeTerm(entry.term, line + '\r\n');
+ }
+ buffersBefore[agent.ptyId] = readBuf(entry.term);
+ }
+
+ // ─── 5. render the REAL CommandCenterPanel ──────────────────────────────────
+ const React = repoRequire('react');
+ const { createRoot } = repoRequire('react-dom/client');
+ const panelExports = loadTs('src/renderer/src/components/CommandCenterPanel.tsx');
+ const CommandCenterPanel = panelExports.CommandCenterPanel;
+
+ const result = {
+ calls: [],
+ scenarios: {},
+ agentsFinal: null,
+ bodyText: '',
+ error: null
+ };
+
+ function shipResult(overrides) {
+ const payload = Object.assign({}, result, overrides || {});
+ // Rich call strings: fn:ptyId(+requireResume)(=resumeSessionId)
+ payload.calls = calls.map((c) => c.fn + (c.ptyId ? ':' + c.ptyId : '')
+ + (c.requireResume ? '+requireResume' : '')
+ + (c.resumeSessionId ? '=' + c.resumeSessionId : ''));
+ payload.scenarios = result.scenarios;
+ payload.agentsFinal = useStore.getState().agents.map((a) => ({
+ id: a.id, action: a.action, status: a.status, terminalGeneration: a.terminalGeneration ?? 0
+ }));
+ payload.bodyText = (document.body.innerText || '').slice(0, 5000);
+ require('electron').ipcRenderer.send('bug14:result', JSON.stringify(payload));
+ }
+
+ const mount = document.getElementById('root');
+ const root = createRoot(mount);
+ root.render(React.createElement(CommandCenterPanel, { agent: AGENTS[0], fullscreen: true }));
+ await new Promise((r) => setTimeout(r, 700));
+
+ // Open the floor tab (label 'monitor', en.json commandCenter.tabs.floor).
+ const monitorTab = [...document.querySelectorAll('.cth-tabbar button')]
+ .find((b) => (b.textContent || '').trim() === 'monitor');
+ if (!monitorTab) {
+ shipResult({ error: 'monitor tab button not found; body=' + (document.body.innerText || '').slice(0, 800) });
+ return;
+ }
+ monitorTab.click();
+ await new Promise((r) => setTimeout(r, 600));
+
+ const findRestartButtons = () => [...document.querySelectorAll('button')]
+ .filter((b) => /restart\s*&\s*continue/i.test(b.textContent || ''));
+
+ async function runScenario(key, agent) {
+ const buttons = findRestartButtons();
+ const idx = AGENTS.indexOf(agent);
+ const btn = buttons[idx];
+ if (!btn) {
+ result.scenarios[key] = { error: 'restart&continue button #' + idx + ' not found; count=' + buttons.length };
+ return;
+ }
+ const startSeq = calls.length;
+ btn.click();
+ await new Promise((r) => requestAnimationFrame(() => r()));
+ await new Promise((r) => setTimeout(r, 800));
+
+ const entryAfter = poolModule.acquireTerminal(agent.ptyId);
+ const a = useStore.getState().agents.find((x) => x.id === agent.id);
+ result.scenarios[key] = {
+ ptyId: agent.ptyId,
+ callOrder: calls.slice(startSeq).map((c) => c.fn + (c.ptyId ? ':' + c.ptyId : '')).join(' -> '),
+ entrySwapped: entryAfter !== entriesBefore[agent.ptyId],
+ termSwapped: entryAfter.term !== entriesBefore[agent.ptyId].term,
+ bufferBefore: buffersBefore[agent.ptyId],
+ bufferAfter: readBuf(entryAfter.term),
+ action: a.action,
+ status: a.status,
+ terminalGeneration: a.terminalGeneration ?? 0
+ };
+ // Prove the label does not self-correct: wait past any pending re-render.
+ await new Promise((r) => setTimeout(r, 450));
+ const a2 = useStore.getState().agents.find((x) => x.id === agent.id);
+ result.scenarios[key].actionAfterExtraSettle = a2.action;
+ }
+
+ await runScenario('A_spawnFailed', AGENTS[0]);
+ await runScenario('B_resumeRefused', AGENTS[1]);
+ await runScenario('C_restartOk', AGENTS[2]);
+
+ shipResult();
+})().catch((e) => {
+ try {
+ require('electron').ipcRenderer.send('bug14:result', JSON.stringify({
+ error: 'renderer payload threw: ' + (e && e.stack || String(e))
+ }));
+ } catch { /* nothing else to do */ }
+});
diff --git a/test/restart-terminal-preserve.test.cjs b/test/restart-terminal-preserve.test.cjs
new file mode 100644
index 00000000..d8cbe73d
--- /dev/null
+++ b/test/restart-terminal-preserve.test.cjs
@@ -0,0 +1,216 @@
+'use strict';
+/**
+ * Regression test for the restart-terminal data loss (bug #14).
+ *
+ * The bug: restartWithModel's resume path (CommandCenterPanel.tsx) ran
+ * disposeTerminal+acquireTerminal BEFORE the spawnPty call that can still fail,
+ * then threw on `!res.ok` (spawn refused — cwd gone, CLI missing) and on a
+ * refused resume (`res.resumed !== true`, the main process's requireResume
+ * early-return). Both throws land AFTER the destroy: the catch only writes a
+ * restart-error banner, so the pool kept the fresh EMPTY xterm — the old one's
+ * scrollback is unrecoverable (node-pty keeps none; terminalPool.ts exists
+ * precisely because of that) — and the agent's action label stayed stuck at
+ * "recreating terminal…" with no correction. One failed "Restart & Continue"
+ * erased the pane the button exists to redraw.
+ *
+ * The fix reorders: the kill/reset still run pre-spawn (a killed process is
+ * already the goal, and the fresh-session path only soft-resets), but the
+ * destroy/recreate/generation-bump of the resume path now runs after the two
+ * throws — i.e. only when the replacement process was actually accepted. The
+ * spawn answer beats the CLI's first frame, so startup output cannot be missed,
+ * and the remount's attach re-requests a PTY redraw for anything it raced.
+ *
+ * HOW THIS TEST WORKS (deterministic, no network, no real PTY spawns): plain
+ * node drives the repo's own Electron binary (the quit-sweep protocol) running
+ * test/fixtures/bug-14-main.cjs, which boots a hidden window and executes
+ * test/fixtures/bug-14.renderer.js inside it. The payload mounts the REAL
+ * CommandCenterPanel + terminalPool + zustand store (loaded through a TS/TSX
+ * transpile loader) against a scripted `window.cth` bridge, seeds live-looking
+ * scrollback into the pooled xterms, and clicks "restart & continue" on three
+ * agents:
+ *
+ * A spawnPty answers {ok:false,…} → the `!res.ok` throw
+ * B spawnPty answers {ok:true}, no `resumed` → the refused-resume throw
+ * C spawnPty answers {ok:true, resumed:true} → success CONTROL
+ *
+ * The assertions then require, for the failures (A, B): the pool entry NOT
+ * swapped, the scrollback intact, and the action label never set to
+ * 'recreating terminal…' — while the success control (C) must still replace the
+ * terminal and bump the generation, only ever after the spawn answer.
+ *
+ * Electron-only (the bug lives in the renderer's terminal pool), so elsewhere
+ * this exits 0 after a smoke check — same convention as
+ * test/quit-sweep.electron.test.cjs. Run: node --test test/restart-terminal-preserve.test.cjs
+ */
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawn, execSync } = require('node:child_process');
+
+const REPO = path.resolve(__dirname, '..');
+
+if (process.platform !== 'win32' || !fs.existsSync(path.join(REPO, 'node_modules', 'electron'))) {
+ console.log(' ok (restart-terminal-preserve needs the repo\'s Electron binary; skipping elsewhere)');
+ process.exit(0);
+}
+
+// From plain Node (not inside Electron), the electron package exports the path
+// to the Electron executable.
+const electronBin = require(path.join(REPO, 'node_modules', 'electron'));
+const FIXTURE = path.join(__dirname, 'fixtures', 'bug-14-main.cjs');
+// A throwaway blank page in tmp — the fixture only needs a file:// origin with
+// a writable localStorage, never a repo artifact.
+const BLANK_HTML = path.join(os.tmpdir(), `bug14-blank-${process.pid}.html`);
+const RESULT = path.join(os.tmpdir(), `bug14-result-${process.pid}-${Date.now()}.json`);
+
+/** Minimal check harness (bug-7 house style). */
+const results = [];
+function check(name, fn) {
+ try {
+ fn();
+ results.push({ name, ok: true });
+ } catch (e) {
+ results.push({ name, ok: false, error: e });
+ }
+}
+function assertCond(cond, msg) { if (!cond) throw new Error(msg); }
+
+async function runElectron() {
+ return new Promise((resolve) => {
+ const env = Object.assign({}, process.env);
+ delete env.ELECTRON_RUN_AS_NODE; // we want the BROWSER binary
+ const args = [FIXTURE, `--result-file=${RESULT}`, `--repo=${REPO}`, `--blank=${BLANK_HTML}`];
+ const child = spawn(electronBin, args, {
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env,
+ windowsHide: true
+ });
+ let out = '';
+ let err = '';
+ child.stdout.on('data', (d) => { out += d; });
+ child.stderr.on('data', (d) => { err += d; });
+ const killHard = setTimeout(() => {
+ try {
+ if (process.platform === 'win32') {
+ execSync(`taskkill /PID ${child.pid} /T /F`, { stdio: 'ignore' });
+ } else {
+ child.kill('SIGKILL');
+ }
+ } catch { /* already gone */ }
+ resolve({ code: 'TIMEOUT', out, err: err + '\n[driver] killed after 120s' });
+ }, 120_000);
+ child.on('exit', (code) => {
+ clearTimeout(killHard);
+ resolve({ code, out, err });
+ });
+ });
+}
+
+function readResult() {
+ try { return JSON.parse(fs.readFileSync(RESULT, 'utf8')); } catch { return null; }
+}
+
+test('a failed Restart & Continue keeps the pooled terminal, scrollback and label', async () => {
+ fs.writeFileSync(BLANK_HTML, '<!doctype html><html><body><div id="root"></div></body></html>');
+ try { fs.rmSync(RESULT, { force: true }); } catch { /* fresh */ }
+
+ const run = await runElectron();
+ const res = readResult();
+
+ const dump = () => `electron exit: ${run.code}\n--- stdout ---\n${run.out.slice(-4000)}`
+ + `\n--- stderr ---\n${run.err.slice(-4000)}`;
+
+ assert.ok(res, `result file missing — the fixture never completed\n${dump()}`);
+ assert.ok(!res.error, `harness error (not a bug assertion): ${res.error}\n${dump()}`);
+
+ const S = res.scenarios || {};
+ const A = S.A_spawnFailed || {};
+ const B = S.B_resumeRefused || {};
+ const C = S.C_restartOk || {};
+
+ // ── controls (prove the click really reached restartWithModel) ──────────────
+ check('CONTROL: the click reached restartWithModel (killPty → spawnPty, requireResume)', () => {
+ assertCond(typeof A.callOrder === 'string' && A.callOrder.length > 0,
+ 'no call order recorded for scenario A: ' + JSON.stringify(A).slice(0, 400));
+ assertCond(/killPty/.test(A.callOrder) && /spawnPty/.test(A.callOrder),
+ 'expected killPty and spawnPty in the recorded order, got: ' + A.callOrder);
+ const spawnIdx = A.callOrder.indexOf('spawnPty');
+ const killIdx = A.callOrder.indexOf('killPty');
+ assertCond(killIdx !== -1 && spawnIdx > killIdx,
+ 'spawnPty must follow killPty, got: ' + A.callOrder);
+ assertCond(/requireResume/.test(JSON.stringify(res.calls)), 'spawnPty was not called with requireResume');
+ });
+
+ check('CONTROL: scenario A hit the `!res.ok` throw — the restart error banner was set', () => {
+ assertCond(/cwd does not exist/i.test(res.bodyText || ''),
+ 'the restart error banner (cwd does not exist…) is not rendered in the panel; body snippet: '
+ + res.bodyText.slice(0, 400));
+ });
+
+ check('CONTROL: scenario B hit the refused-resume throw — its banner was set', () => {
+ assertCond(/Resume was refused/i.test(res.bodyText || ''),
+ 'the refused-resume banner is not rendered in the panel; body snippet: ' + res.bodyText.slice(0, 400));
+ });
+
+ // ── the regression ──────────────────────────────────────────────────────────
+ check('A failed restart must NOT replace the pooled terminal entry', () => {
+ assertCond(A.entrySwapped === false,
+ 'the terminalPool entry WAS swapped before the failure was known: disposeTerminal+acquireTerminal '
+ + 'ran before spawnPty could answer, so the throws left the fresh empty entry in place and the '
+ + 'old xterm (with its scrollback) destroyed. Order: ' + A.callOrder);
+ });
+
+ check('the agent\'s scrollback must survive a failed "Restart & Continue"', () => {
+ assertCond(/IMPORTANT SCROLLBACK A1/.test((A.bufferBefore || []).join('\n')),
+ 'scrollback seed missing BEFORE the click — test setup broken: ' + JSON.stringify(A.bufferBefore));
+ assertCond(/IMPORTANT SCROLLBACK A1/.test((A.bufferAfter || []).join('\n')),
+ 'the scrollback was destroyed by the FAILED restart: the pooled xterm now reads '
+ + JSON.stringify(A.bufferAfter) + ' — disposeTerminal tore down the old xterm whose buffer '
+ + 'node-pty cannot restore, and acquireTerminal planted a blank one.');
+ });
+
+ check('the action label must not be left stuck at "recreating terminal…" after the failure', () => {
+ assertCond(A.action !== 'recreating terminal…',
+ 'after the failed restart the action still reads "recreating terminal…" — the destroy ran '
+ + 'before the spawn answer and the catch only writes restartErrors, never correcting it');
+ assertCond(A.actionAfterExtraSettle !== 'recreating terminal…',
+ 'the label is still stuck after an extra settle (it never self-corrects): '
+ + JSON.stringify(A.actionAfterExtraSettle));
+ });
+
+ check('a REFUSED resume (ok:true, no `resumed`) must also leave the terminal and label intact', () => {
+ assertCond(B.entrySwapped === false,
+ 'the pool entry WAS swapped on the refused resume; entrySwapped=' + B.entrySwapped);
+ assertCond(/IMPORTANT SCROLLBACK B1/.test((B.bufferAfter || []).join('\n')),
+ 'scenario B lost its scrollback to the refused resume: ' + JSON.stringify(B.bufferAfter));
+ assertCond(B.action !== 'recreating terminal…',
+ 'the stuck label was set in scenario B too: ' + JSON.stringify(B.action));
+ });
+
+ // ── the success control: the reorder must not break the recreate ────────────
+ check('a SUCCESSFUL restart still recreates the terminal (only after the spawn answer)', () => {
+ assertCond(C.entrySwapped === true,
+ 'the flow must still replace the terminal when the replacement is accepted; entrySwapped='
+ + C.entrySwapped + ', order: ' + C.callOrder);
+ assertCond(C.terminalGeneration === 1, 'success control should bump terminalGeneration, got: ' + C.terminalGeneration);
+ assertCond(C.action === 'continuing…',
+ 'success control should land on the "continuing…" action, got: ' + JSON.stringify(C.action));
+ const order = C.callOrder || '';
+ const spawnIdx = order.indexOf('spawnPty');
+ const disposeIdx = order.indexOf('disposeTerminal');
+ assertCond(disposeIdx !== -1 && spawnIdx !== -1 && disposeIdx > spawnIdx,
+ 'the successful restart must destroy the old terminal only AFTER the spawn answer; order: ' + order);
+ });
+
+ const failed = results.filter((r) => !r.ok);
+ for (const r of results) console.log(` ${r.ok ? 'ok ' : 'FAIL'} ${r.name}`);
+ if (failed.length > 0) {
+ console.log('\nfailing assertions:');
+ for (const f of failed) console.log(` - ${f.name}\n ${f.error.message}`);
+ }
+ assert.equal(failed.length, 0, `${failed.length}/${results.length} restart-terminal assertions failed`
+ + (failed.length ? `:\n - ${failed.map((f) => f.error.message).join('\n - ')}` : ''));
+});