Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Log why a terminal session ended; make the launch barrier truthful (#4765)
Nick Gomez8332b5225a46
diff --git a/.changeset/terminal-session-end-logging.md b/.changeset/terminal-session-end-logging.mdnew file mode 100644index 000000000..572599ecd--- /dev/null+++ b/.changeset/terminal-session-end-logging.md@@ -0,0 +1,6 @@+---+"@inkeep/open-knowledge": patch+"@inkeep/open-knowledge-desktop": patch+---++Desktop logs now record why a running terminal session ended. To do that the app now tracks two new facts per session — whether it ever produced output, and how long it ran; nothing else new is collected about you or your documents.diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex 02614f863..6b5397f75 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -476,6 +476,7 @@ import {} from './terminal-dock-persistence.ts';import { observeTerminalLaunch } from './terminal-gate-observation.ts';import { type TerminalReaper, wireWindowTerminalReap } from './terminal-lifecycle.ts';+import type { AppShutdownCause } from './terminal-manager.ts';import {clampPtyDimension,createTerminalManager,@@ -965,6 +966,10 @@ function attachSpellcheckMenuToWindow(win: BrowserWindow): void {let navigatorWindow: BrowserWindowLike | null = null;let wm: WindowManager;let terminalReaper: TerminalReaper | null = null;+let announcedShutdownCause: AppShutdownCause = 'quit';+const noteRestartPending = (): void => {+ announcedShutdownCause = 'relaunch';+};function sweepConsoleHostsBeforeUpdate(): WindowsUpdateSurvivorSweepResult {const logger = getLogger('updater');@@ -3793,6 +3798,7 @@ function registerIpcHandlers() {clearTimer: (token) => clearTimeout(token as ReturnType<typeof setTimeout>),logger: {warn: (data) => getLogger('terminal').warn(data, String(data.event ?? 'terminal-manager')),+ info: (data) => getLogger('terminal').info(data, String(data.event ?? 'terminal-manager')),},canSpawnAt: (projectRoot) => isTerminalConsented(projectRoot),recordShellExit,@@ -6474,6 +6480,7 @@ function bootPrimaryInstance(): void {},copyCommandToClipboard: (command) => clipboard.writeText(command),relaunchApp: () => {+ noteRestartPending();app.relaunch();app.quit();},@@ -6503,7 +6510,7 @@ function bootPrimaryInstance(): void {prepareForRelaunch: async () => {freezeFocusTracking('prepare-for-relaunch');captureWindowRestoreSnapshot('prepare-for-relaunch');- await terminalReaper?.killAll();+ await terminalReaper?.killAll('relaunch');await wm?.stopAllOwnedServers();flushDesktopLogger();},@@ -6559,7 +6566,13 @@ function bootPrimaryInstance(): void {infoPlistPath,getCurrentVersion: () => app.getVersion(),dialog,- app,+ app: {+ relaunch: (options) => {+ noteRestartPending();+ app.relaunch(options);+ },+ quit: () => app.quit(),+ },});}})@@ -6570,7 +6583,8 @@ function bootPrimaryInstance(): void {});app.on('before-quit', () => {- getLogger('lifecycle').info({}, 'before-quit');+ getLogger('lifecycle').info({ cause: announcedShutdownCause }, 'before-quit');+ terminalReaper?.noteAppShutdown(announcedShutdownCause);freezeFocusTracking('before-quit');captureWindowRestoreSnapshot('before-quit');autoUpdaterHandle?.recordInstallHandoffOnQuit();@@ -6582,7 +6596,7 @@ function bootPrimaryInstance(): void {getLogger('updater').info({}, 'before-quit-for-update — update install will relaunch the app');freezeFocusTracking('before-quit-for-update');captureWindowRestoreSnapshot('before-quit-for-update');- void (terminalReaper?.killAll() ?? Promise.resolve()).then(() => {+ void (terminalReaper?.killAll('update-install') ?? Promise.resolve()).then(() => {const result = sweepConsoleHostsBeforeUpdate();if (result.scanFailed || result.revalidationFailed || result.failedCount > 0) {getLogger('updater').warn(@@ -6599,7 +6613,7 @@ function bootPrimaryInstance(): void {defer: (callback) => setImmediate(callback),drain: async () => {const [terminalResult] = await Promise.allSettled([- terminalReaper?.killAll() ?? Promise.resolve(),+ terminalReaper?.killAll('quit') ?? Promise.resolve(),slidesDeckRegistry.reapAll(),]);if (terminalResult.status === 'rejected') {diff --git a/packages/desktop/src/main/terminal-lifecycle.ts b/packages/desktop/src/main/terminal-lifecycle.tsindex 3175dd715..c622256e0 100644--- a/packages/desktop/src/main/terminal-lifecycle.ts+++ b/packages/desktop/src/main/terminal-lifecycle.ts@@ -1,6 +1,9 @@+import type { AppShutdownCause } from './terminal-manager.ts';+export interface TerminalReaper {+ noteAppShutdown(cause: AppShutdownCause): void;killForWindow(windowId: number): void;- killAll(): Promise<void>;+ killAll(cause: AppShutdownCause): Promise<void>;}export interface ClosableWindow {diff --git a/packages/desktop/src/main/terminal-manager.ts b/packages/desktop/src/main/terminal-manager.tsindex d3474cf83..ffaada45b 100644--- a/packages/desktop/src/main/terminal-manager.ts+++ b/packages/desktop/src/main/terminal-manager.ts@@ -46,7 +46,10 @@ export interface TerminalManagerDeps {lowWaterBytes?: number;replayCapBytes?: number;shutdownMs?: number;- logger?: { warn: (o: Record<string, unknown>) => void };+ logger?: {+ warn: (o: Record<string, unknown>) => void;+ info?: (o: Record<string, unknown>) => void;+ };recordShellExit?: (info: { crashed: boolean }) => void;recordTerminalSession?: () => void;recordConcurrentSessions?: (info: { count: number }) => void;@@ -85,6 +88,8 @@ interface SessionState {paused: boolean;killRequested: boolean;commandRan: boolean;+ sawOutput: boolean;+ spawnedAt: number | null;customLabel: string | null;ordinal: number | null;order: number;@@ -92,6 +97,19 @@ interface SessionState {shellNoticeReason: Extract<TerminalShellNoticeReason, 'unsupported-family'> | null;}+export type AppShutdownCause = 'quit' | 'update-install' | 'relaunch';++type SessionEndOutcome =+ | { reason: 'shell-exit'; exitCode: number | null; signal: number | null }+ | { reason: 'host-exited'; exitCode: number | null }+ | { reason: 'window-closed' }+ | { reason: 'app-shutdown'; cause: AppShutdownCause }+ | { reason: 'cancelled-before-spawn' };++function assertNeverSessionEndOutcome(value: never): never {+ throw new Error(`unhandled session end outcome: ${JSON.stringify(value)}`);+}+interface PtyWindowHandle {webContents: SendableWebContents;utility: PtyUtilityLike;@@ -141,8 +159,9 @@ export interface TerminalManager {): void;setSessionOrder(req: { windowId: number; orderedPtyIds: readonly string[] }): void;adoptSession(req: TerminalAdoptRequest): OkPtyAdoptResult;+ noteAppShutdown(cause: AppShutdownCause): void;killForWindow(windowId: number): void;- killAll(): Promise<void>;+ killAll(cause: AppShutdownCause): Promise<void>;}export function createTerminalManager(deps: TerminalManagerDeps): TerminalManager {@@ -153,6 +172,7 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManageconst shutdownMs = deps.shutdownMs ?? DEFAULT_SHUTDOWN_MS;const handles = new Map<number, PtyWindowHandle>();const pendingShutdowns = new Set<Promise<void>>();+ let announcedShutdown: AppShutdownCause | null = null;function safeKillUtility(handle: PtyWindowHandle): void {try {@@ -323,6 +343,7 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManageswitch (message.type) {case 'data':+ session.sawOutput = true;session.outbound += message.data;session.replay += message.data;if (session.replay.length > replayCap) {@@ -332,16 +353,18 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManagebreak;case 'exit': {const { ptyId } = message;+ const exitCode = message.exitCode ?? -1;clearSessionTimers(session);deliver(handle, ptyId, session);maybeRecordSession(session);handle.sessions.delete(ptyId);deps.recordShellExit?.({ crashed: false });- pushExit(handle, {- ptyId,- exitCode: message.exitCode ?? -1,+ logSessionEnd(windowId, ptyId, session, {+ reason: 'shell-exit',+ exitCode: message.exitCode ?? null,signal: message.signal,});+ pushExit(handle, { ptyId, exitCode, signal: message.signal });break;}case 'spawn-error': {@@ -414,12 +437,47 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage} else {maybeRecordSession(session);deps.recordShellExit?.({ crashed: !session.killRequested });+ logSessionEnd(windowId, ptyId, session, { reason: 'host-exited', exitCode: code });pushExit(handle, { ptyId, exitCode: code ?? 1, signal: null, hostExited: true });}}handle.sessions.clear();}+ function endedRoutinely(session: SessionState, outcome: SessionEndOutcome): boolean {+ if (session.killRequested) return true;+ switch (outcome.reason) {+ case 'shell-exit':+ return session.sawOutput && outcome.signal === null;+ case 'host-exited':+ return false;+ case 'window-closed':+ case 'app-shutdown':+ case 'cancelled-before-spawn':+ return true;+ default:+ return assertNeverSessionEndOutcome(outcome);+ }+ }++ function logSessionEnd(+ windowId: number,+ ptyId: string,+ session: SessionState,+ outcome: SessionEndOutcome,+ ): void {+ deps.logger?.[endedRoutinely(session, outcome) ? 'info' : 'warn']?.({+ event: 'terminal-manager-session-exit',+ windowId,+ ptyId,+ ...outcome,+ killRequested: session.killRequested,+ sawOutput: session.sawOutput,+ shellFamily: session.shellFamily,+ uptimeMs: session.spawnedAt === null ? null : Math.max(0, Date.now() - session.spawnedAt),+ });+ }+function maybeRecordSession(session: SessionState): void {if (!session.commandRan) return;session.commandRan = false;@@ -476,6 +534,8 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManagepaused: false,killRequested: false,commandRan: false,+ sawOutput: false,+ spawnedAt: null,customLabel: null,ordinal: null,order: nextOrder,@@ -527,12 +587,13 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManageconst handle = handles.get(req.windowId);const session = handle?.sessions.get(req.ptyId);if (!handle || !session) return;+ session.killRequested = true;if (session.pendingCreate !== null) {clearSessionTimers(session);handle.sessions.delete(req.ptyId);+ logSessionEnd(req.windowId, req.ptyId, session, { reason: 'cancelled-before-spawn' });return;}- session.killRequested = true;if (session.paused) {session.paused = false;session.pendingBytes = 0;@@ -634,6 +695,7 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage});return { ok: false, reason: 'host-unavailable' };}+ session.spawnedAt = Date.now();deps.recordConcurrentSessions?.({ count: liveCount });return { ok: true, replay: '' };}@@ -661,14 +723,27 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage};},+ noteAppShutdown(cause): void {+ announcedShutdown = cause;+ },+killForWindow(windowId): void {const handle = handles.get(windowId);if (!handle) return;let reserved = 0;- for (const session of handle.sessions.values()) {+ for (const [ptyId, session] of handle.sessions) {clearSessionTimers(session);maybeRecordSession(session);if (session.pendingCreate !== null) reserved += 1;+ else+ logSessionEnd(+ windowId,+ ptyId,+ session,+ announcedShutdown === null+ ? { reason: 'window-closed' }+ : { reason: 'app-shutdown', cause: announcedShutdown },+ );}if (reserved > 0)deps.logger?.warn({ event: 'terminal-manager-reaped-reservations', windowId, reserved });@@ -676,14 +751,15 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManagevoid beginHostShutdown(handle);},- async killAll(): Promise<void> {+ async killAll(cause): Promise<void> {const shutdowns: Promise<void>[] = [];for (const [windowId, handle] of handles) {let reserved = 0;- for (const session of handle.sessions.values()) {+ for (const [ptyId, session] of handle.sessions) {clearSessionTimers(session);maybeRecordSession(session);if (session.pendingCreate !== null) reserved += 1;+ else logSessionEnd(windowId, ptyId, session, { reason: 'app-shutdown', cause });}if (reserved > 0)deps.logger?.warn({ event: 'terminal-manager-reaped-reservations', windowId, reserved });diff --git a/packages/desktop/src/main/terminal-window.test.ts b/packages/desktop/src/main/terminal-window.test.tsindex 43faa2b4c..8293f3f4c 100644--- a/packages/desktop/src/main/terminal-window.test.ts+++ b/packages/desktop/src/main/terminal-window.test.ts@@ -1,6 +1,7 @@import { afterEach, describe, expect, test, vi } from 'vitest';import type { ShowGateRegistry } from './show-gate.ts';import type { TerminalReaper } from './terminal-lifecycle.ts';+import type { AppShutdownCause } from './terminal-manager.ts';import {createTerminalWindow,resolveTerminalWindowProject,@@ -48,6 +49,7 @@ function makeDeps(opts: {const showGate = { register, fireThemeApplied: () => {} } as unknown as ShowGateRegistry;const killForWindow = vi.fn((_id: number) => {});const terminalReaper = {+ noteAppShutdown: (_cause: AppShutdownCause) => {},killForWindow,killAll: () => Promise.resolve(),} satisfies TerminalReaper;diff --git a/packages/desktop/tests/integration/terminal-shutdown-wiring.test.ts b/packages/desktop/tests/integration/terminal-shutdown-wiring.test.tsnew file mode 100644index 000000000..c9a5f0e21--- /dev/null+++ b/packages/desktop/tests/integration/terminal-shutdown-wiring.test.ts@@ -0,0 +1,187 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { describe, expect, test } from 'vitest';++const indexTsPath = resolve(fileURLToPath(new URL('../../src/main/index.ts', import.meta.url)));+const src = readFileSync(indexTsPath, 'utf-8');++const FIX = (what: string): string =>+ `\n[terminal-shutdown] ${what}\n\n` ++ `Electron closes every window before it emits will-quit, so an ordinary Quit reaps each live\n` ++ `terminal through killForWindow. Without the before-quit notice arriving first, those sessions\n` ++ `are logged window-closed and app-shutdown describes only the update paths, which is the exact\n` ++ `defect this wiring was added to fix. The manager-level tests cannot see it: they call\n` ++ `noteAppShutdown() directly, so they stay green while this registration rots.\n`;++describe('terminal shutdown-notice wiring (bypass-pin)', () => {+ const beforeQuitBody = (): string => {+ const handler = /app\.on\('before-quit',\s*\(\)\s*=>\s*\{([\s\S]*?)\n {2}\}\);/.exec(src);+ expect(+ handler,+ FIX('the before-quit handler is no longer recognisable at module scope.'),+ ).not.toBeNull();+ return handler?.[1] ?? '';+ };++ test('before-quit tells the reaper a quit began, ahead of any window teardown', () => {+ const body = beforeQuitBody();+ expect(+ /terminalReaper\?\.noteAppShutdown\(announcedShutdownCause\);/.test(body),+ FIX('before-quit no longer announces the marked cause to the terminal reaper.'),+ ).toBe(true);++ const notice = body.indexOf('noteAppShutdown');+ const snapshot = body.indexOf('captureWindowRestoreSnapshot');+ expect(+ snapshot,+ FIX(+ 'captureWindowRestoreSnapshot is gone from before-quit, so the statement this clause ' ++ 'orders the notice against no longer exists. Re-anchor the ordering check rather than ' ++ 'letting it pass on an absent anchor.',+ ),+ ).toBeGreaterThan(-1);+ expect(+ notice < snapshot,+ FIX('the shutdown notice no longer precedes window teardown inside before-quit.'),+ ).toBe(true);+ });++ test('the notice is armed only where a shutdown is irrevocable', () => {+ const arms = src.match(/noteAppShutdown\(/g) ?? [];+ expect(+ arms.length,+ FIX(+ 'noteAppShutdown is armed somewhere other than before-quit. The announced cause is never ' ++ 'cleared, so arming it on a path that can be abandoned (a failed update relaunch) ' ++ 'latches it and mislabels every later window close. killAll tags its own sessions, so ' ++ 'the update paths do not need it.',+ ),+ ).toBe(1);+ });++ test('each shutdown path tells killAll its own lifecycle event', () => {+ const scoped: ReadonlyArray<readonly [RegExp, string, string]> = [+ [+ /prepareForRelaunch:\s*async\s*\(\)\s*=>\s*\{([\s\S]*?)\n\s{8}\},/,+ 'relaunch',+ 'the relaunch preparation',+ ],+ [+ /electronAutoUpdater\.on\('before-quit-for-update',\s*\(\)\s*=>\s*\{([\s\S]*?)\n {2}\}\);/,+ 'update-install',+ 'the before-quit-for-update handler',+ ],+ [+ /const runTerminalQuitDrain = createTerminalQuitDrain\(\{([\s\S]*?)\n {2}\}\);/,+ 'quit',+ 'the quit drain',+ ],+ ];+ for (const [shape, cause, what] of scoped) {+ const found = shape.exec(src);+ expect(+ found,+ FIX(`${what} is no longer recognisable, so its cause cannot be checked.`),+ ).not.toBeNull();+ const body = found?.[1] ?? '';+ expect(+ body.includes(`killAll('${cause}')`),+ FIX(+ `${what} no longer passes '${cause}' to killAll. Checking the whole file would miss two ` ++ 'handlers exchanging their causes, which is why each is scoped to its own body.',+ ),+ ).toBe(true);+ }++ const calls = src.match(/killAll\(/g) ?? [];+ expect(+ calls.length,+ FIX('a killAll call site was added or removed; every one has to name its own cause.'),+ ).toBe(3);+ });++ test('a restart driven by an update marks relaunch, in each path that needs it', () => {+ const setter =+ /const noteRestartPending = \(\): void => \{\s*announcedShutdownCause = '([a-z-]+)';\s*\};/.exec(+ src,+ );+ expect(+ setter,+ FIX('noteRestartPending no longer assigns announcedShutdownCause in a recognisable form.'),+ ).not.toBeNull();+ expect(+ setter?.[1],+ FIX(+ 'the restart mark no longer sets relaunch, so both update-driven restarts announce an ' ++ 'ordinary quit while the identifier and the call count stay unchanged.',+ ),+ ).toBe('relaunch');++ const sites: ReadonlyArray<readonly [RegExp, string, boolean]> = [+ [+ /relaunchApp:\s*\(\)\s*=>\s*\{([\s\S]*?)\n\s+\},/,+ "the Linux manual-install fallback's relaunch button",+ true,+ ],+ [+ /relaunch:\s*\(options\)\s*=>\s*\{([\s\S]*?)\n\s+\},/,+ "the bundle-replace detector's restart",+ false,+ ],+ ];+ for (const [shape, what, quitsHere] of sites) {+ const found = shape.exec(src);+ expect(+ found,+ FIX(`${what} is no longer recognisable, so its mark cannot be checked.`),+ ).not.toBeNull();+ const body = found?.[1] ?? '';+ expect(+ body.includes('noteRestartPending()'),+ FIX(`${what} no longer marks the cause, so it is recorded as an ordinary user quit.`),+ ).toBe(true);+ const quit = body.indexOf('quit()');+ expect(+ quit > -1,+ FIX(+ `${what} ${quitsHere ? 'no longer quits' : 'now quits'} in its own body, so the ordering ` ++ 'this case declares for it no longer describes the code. Update the declaration and ' ++ 'the assertion together rather than letting either pass on an absent anchor.',+ ),+ ).toBe(quitsHere);+ if (quitsHere) {+ expect(+ body.indexOf('noteRestartPending()') < quit,+ FIX(+ `${what} marks the cause after it quits. before-quit reads the marked value, so a ` ++ 'mark that lands after the quit is read too late and the session records a quit.',+ ),+ ).toBe(true);+ }+ }++ const marks = src.match(/noteRestartPending\(\)/g) ?? [];+ expect(+ marks.length,+ FIX(+ 'the number of restart marks no longer matches the sites this case enumerates. A mark ' ++ 'added elsewhere announces a relaunch from a path nothing here checks; the bound and ' ++ 'the enumerated sites move together.',+ ),+ ).toBe(sites.length);+ });++ test('the lifecycle line says which shutdown it is, with or without a terminal open', () => {+ const body = beforeQuitBody();+ expect(+ /getLogger\('lifecycle'\)\.info\(\{ cause: announcedShutdownCause \}, 'before-quit'\);/.test(+ body,+ ),+ FIX(+ 'the before-quit lifecycle line no longer records the cause, so a relaunch and an ' ++ 'ordinary quit are byte-identical in the log whenever no terminal session is open.',+ ),+ ).toBe(true);+ });+});diff --git a/packages/desktop/tests/main/terminal-lifecycle.test.ts b/packages/desktop/tests/main/terminal-lifecycle.test.tsindex 10df6e4de..ac58183c2 100644--- a/packages/desktop/tests/main/terminal-lifecycle.test.ts+++ b/packages/desktop/tests/main/terminal-lifecycle.test.ts@@ -77,7 +77,7 @@ function makeRig() {clearTimer: (token) => {if (typeof token === 'number' && timers[token]) timers[token].cancelled = true;},- logger: { warn: (event) => warnings.push(event) },+ logger: { warn: (event) => warnings.push(event), info: () => {} },});const reaper: TerminalReaper = mgr;function openTerminalWindow(id: number): { win: FakeWindow; ptyId: string } {@@ -180,7 +180,7 @@ describe('terminal lifecycle — app quit reap', () => {rig.openTerminalWindow(1);rig.openTerminalWindow(2);- rig.reaper.killAll();+ rig.reaper.killAll('quit');expect(rig.forked[0]?.posted.at(-1)).toEqual({ type: 'shutdown' });expect(rig.forked[1]?.posted.at(-1)).toEqual({ type: 'shutdown' });rig.runTimers();diff --git a/packages/desktop/tests/main/terminal-manager.test.ts b/packages/desktop/tests/main/terminal-manager.test.tsindex 1c3c1ad3f..af65d5eaf 100644--- a/packages/desktop/tests/main/terminal-manager.test.ts+++ b/packages/desktop/tests/main/terminal-manager.test.ts@@ -69,6 +69,7 @@ function makeManager(over?: Partial<TerminalManagerDeps>) {const timers: Array<(() => void) | null> = [];const timerDelays: number[] = [];const warns: Array<Record<string, unknown>> = [];+ const infos: Array<Record<string, unknown>> = [];let idn = 0;const mgr = createTerminalManager({canSpawnAt: () => true,@@ -101,7 +102,7 @@ function makeManager(over?: Partial<TerminalManagerDeps>) {coalesceMs: 12,highWaterBytes: 100,lowWaterBytes: 20,- logger: { warn: (o) => warns.push(o) },+ logger: { warn: (o) => warns.push(o), info: (o) => infos.push(o) },...over,});const runTimers = (): void => {@@ -126,6 +127,7 @@ function makeManager(over?: Partial<TerminalManagerDeps>) {sent,forked,warns,+ infos,runTimers,dataPayloads,exits,@@ -314,14 +316,20 @@ describe('terminal creation waits for the renderer to subscribe', () => {expect(h.warns).toContainEqual(expect.objectContaining({ event: 'terminal-manager-reaped-reservations', reserved: 1 }),);+ expect(+ [...h.warns, ...h.infos].filter((w) => w.event === 'terminal-manager-session-exit'),+ ).toEqual([]);});test('logs the reservations it reaps when the app quits', () => {const h = reserve();- h.mgr.killAll();+ h.mgr.killAll('quit');expect(h.warns).toContainEqual(expect.objectContaining({ event: 'terminal-manager-reaped-reservations', reserved: 1 }),);+ expect(+ [...h.warns, ...h.infos].filter((w) => w.event === 'terminal-manager-session-exit'),+ ).toEqual([]);});test('refuses to spawn when consent was withdrawn between the create and the start', () => {@@ -860,6 +868,404 @@ describe('createTerminalManager — exit + crash surfacing', () => {expect(h.exits()[0]).toEqual({ ptyId: 'pty-1', exitCode: -1, signal: null });});+ test('records a session-exit log line for a session that never produced output', () => {+ const h = makeManager();+ createStartedTerminal(h.mgr, {+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });+ h.forked[0]?.emitMessage({ type: 'exit', ptyId: 'pty-1', exitCode: undefined, signal: null });++ const line = h.warns.find((w) => w.event === 'terminal-manager-session-exit');+ expect(line).toBeDefined();+ expect(line?.ptyId).toBe('pty-1');+ expect(line?.exitCode).toBeNull();+ expect(line?.signal).toBeNull();+ expect(line?.killRequested).toBe(false);+ expect(line?.sawOutput).toBe(false);+ });++ test('warns when a spawned shell produces nothing and exits cleanly without a kill', () => {+ const h = makeManager();+ createStartedTerminal(h.mgr, {+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });+ h.forked[0]?.emitMessage({ type: 'exit', ptyId: 'pty-1', exitCode: 0, signal: null });++ const line = h.warns.find((w) => w.event === 'terminal-manager-session-exit');+ expect(line).toBeDefined();+ expect(line?.sawOutput).toBe(false);+ expect(line?.exitCode).toBe(0);+ expect(line?.signal).toBeNull();+ expect(line?.killRequested).toBe(false);+ expect(h.infos.filter((w) => w.event === 'terminal-manager-session-exit')).toEqual([]);+ });++ test('routes a shell that produced output and exited non-zero without a signal to info', () => {+ const h = makeManager();+ createStartedTerminal(h.mgr, {+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'boom\r\n' });+ h.forked[0]?.emitMessage({ type: 'exit', ptyId: 'pty-1', exitCode: 127, signal: null });++ expect(h.warns.filter((w) => w.event === 'terminal-manager-session-exit')).toEqual([]);+ const line = h.infos.find((w) => w.event === 'terminal-manager-session-exit');+ expect(line).toBeDefined();+ expect(line?.exitCode).toBe(127);+ expect(line?.sawOutput).toBe(true);+ });++ test('explains a reservation cancelled before the shell was ever spawned', () => {+ const h = makeManager();+ const created = h.mgr.create({+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });+ expect(created.ok).toBe(true);++ h.mgr.kill({ windowId: 1, ptyId: 'pty-1' });++ expect(h.warns.filter((w) => w.event === 'terminal-manager-session-exit')).toEqual([]);+ const line = h.infos.find((w) => w.event === 'terminal-manager-session-exit');+ expect(line).toBeDefined();+ expect(line?.reason).toBe('cancelled-before-spawn');+ expect(line?.ptyId).toBe('pty-1');+ expect(line?.killRequested).toBe(true);+ expect(line?.sawOutput).toBe(false);+ expect(line?.uptimeMs).toBeNull();+ });++ test('routes a killed session that produced output to info, not warn', () => {+ const h = makeManager();+ createStartedTerminal(h.mgr, {+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'hello' });+ h.mgr.kill({ windowId: 1, ptyId: 'pty-1' });+ h.forked[0]?.emitMessage({ type: 'exit', ptyId: 'pty-1', exitCode: 0, signal: null });++ expect(h.warns.filter((w) => w.event === 'terminal-manager-session-exit')).toEqual([]);+ const line = h.infos.find((w) => w.event === 'terminal-manager-session-exit');+ expect(line).toBeDefined();+ expect(line?.reason).toBe('shell-exit');+ expect(line?.killRequested).toBe(true);+ expect(line?.sawOutput).toBe(true);+ });++ test('routes a shell killed before it ever printed anything to info', () => {+ const h = makeManager();+ createStartedTerminal(h.mgr, {+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });+ h.mgr.kill({ windowId: 1, ptyId: 'pty-1' });+ h.forked[0]?.emitMessage({ type: 'exit', ptyId: 'pty-1', exitCode: 0, signal: null });++ expect(h.warns.filter((w) => w.event === 'terminal-manager-session-exit')).toEqual([]);+ const line = h.infos.find((w) => w.event === 'terminal-manager-session-exit');+ expect(line).toBeDefined();+ expect(line?.reason).toBe('shell-exit');+ expect(line?.killRequested).toBe(true);+ expect(line?.sawOutput).toBe(false);+ });++ test('routes a shell that exited on its own after producing output to info', () => {+ const h = makeManager();+ createStartedTerminal(h.mgr, {+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'hello' });+ h.forked[0]?.emitMessage({ type: 'exit', ptyId: 'pty-1', exitCode: 0, signal: null });++ expect(h.warns.filter((w) => w.event === 'terminal-manager-session-exit')).toEqual([]);+ expect(h.infos.find((w) => w.event === 'terminal-manager-session-exit')).toBeDefined();+ });++ test('warns when a shell that was not killed dies on a signal', () => {+ const h = makeManager();+ createStartedTerminal(h.mgr, {+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'hello' });+ h.forked[0]?.emitMessage({ type: 'exit', ptyId: 'pty-1', exitCode: 0, signal: 9 });++ const line = h.warns.find((w) => w.event === 'terminal-manager-session-exit');+ expect(line).toBeDefined();+ expect(line?.signal).toBe(9);+ expect(h.infos.filter((w) => w.event === 'terminal-manager-session-exit')).toEqual([]);+ });++ test('measures uptime from the spawn, not from the reservation that preceded it', () => {+ const now = vi.spyOn(Date, 'now');+ try {+ const h = makeManager();+ now.mockReturnValue(1_000);+ const created = h.mgr.create({+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });+ expect(created.ok).toBe(true);+ now.mockReturnValue(6_000);+ expect(+ h.mgr.adoptSession({+ windowId: 1,+ start: true,+ ptyId: 'pty-1',+ webContents: makeWebContents(),+ }).ok,+ ).toBe(true);+ now.mockReturnValue(6_250);+ h.forked[0]?.emitMessage({ type: 'exit', ptyId: 'pty-1', exitCode: 1, signal: null });++ const line = h.warns.find((w) => w.event === 'terminal-manager-session-exit');+ expect(line).toBeDefined();+ expect(line?.uptimeMs).toBe(250);+ } finally {+ now.mockRestore();+ }+ });++ test('explains every live session when the pty host dies under them', () => {+ const h = makeManager();+ for (let i = 0; i < 2; i += 1) {+ createStartedTerminal(h.mgr, {+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });+ }+ h.mgr.kill({ windowId: 1, ptyId: 'pty-2' });+ h.forked[0]?.emitExit(7);++ const lines = [...h.warns, ...h.infos].filter(+ (w) => w.event === 'terminal-manager-session-exit',+ );+ expect(lines.map((w) => w.ptyId).sort()).toEqual(['pty-1', 'pty-2']);+ for (const line of lines) {+ expect(line.reason).toBe('host-exited');+ expect(line.exitCode).toBe(7);+ expect(typeof line.uptimeMs).toBe('number');+ }+ expect(h.warns.filter((w) => w.event === 'terminal-manager-session-exit')).toHaveLength(1);+ expect(h.warns.find((w) => w.event === 'terminal-manager-session-exit')?.ptyId).toBe('pty-1');+ });++ test('explains a live session that a closing window takes down with it', () => {+ const h = makeManager();+ createStartedTerminal(h.mgr, {+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'hello' });++ h.mgr.killForWindow(1);++ expect(h.warns.filter((w) => w.event === 'terminal-manager-session-exit')).toEqual([]);+ const line = h.infos.find((w) => w.event === 'terminal-manager-session-exit');+ expect(line).toBeDefined();+ expect(line?.reason).toBe('window-closed');+ expect(line?.ptyId).toBe('pty-1');+ expect(line?.sawOutput).toBe(true);+ expect(line?.killRequested).toBe(false);+ });++ test('explains a live session that an app shutdown takes down with it', () => {+ const h = makeManager();+ createStartedTerminal(h.mgr, {+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'hello' });++ h.mgr.killAll('quit');++ expect(h.warns.filter((w) => w.event === 'terminal-manager-session-exit')).toEqual([]);+ const line = h.infos.find((w) => w.event === 'terminal-manager-session-exit');+ expect(line).toBeDefined();+ expect(line?.reason).toBe('app-shutdown');+ expect(line?.ptyId).toBe('pty-1');+ expect(line?.sawOutput).toBe(true);+ expect(line?.killRequested).toBe(false);+ });++ test('a window reaped during app shutdown is logged app-shutdown, not window-closed', () => {+ const h = makeManager();+ createStartedTerminal(h.mgr, {+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });+ h.mgr.noteAppShutdown('quit');+ h.mgr.killForWindow(1);++ const line = h.infos.find((w) => w.event === 'terminal-manager-session-exit');+ expect(line?.reason).toBe('app-shutdown');+ });++ test('a window reaped after a non-quit announcement carries that cause, not a hardcoded quit', () => {+ const h = makeManager();+ createStartedTerminal(h.mgr, {+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });+ h.mgr.noteAppShutdown('update-install');+ h.mgr.killForWindow(1);++ const line = h.infos.find((w) => w.event === 'terminal-manager-session-exit');+ expect(line?.reason).toBe('app-shutdown');+ expect(line?.cause).toBe('update-install');+ });++ test('a window closed while the app keeps running is still logged window-closed', () => {+ const h = makeManager();+ createStartedTerminal(h.mgr, {+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });+ h.mgr.killForWindow(1);++ const line = h.infos.find((w) => w.event === 'terminal-manager-session-exit');+ expect(line?.reason).toBe('window-closed');+ });++ test('a host death after real output stays warn even though output was seen', () => {+ const h = makeManager();+ createStartedTerminal(h.mgr, {+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'hello' });+ h.forked[0]?.emitExit(1);++ const line = h.warns.find((w) => w.event === 'terminal-manager-session-exit');+ expect(line?.reason).toBe('host-exited');+ expect(line?.sawOutput).toBe(true);+ expect(h.infos.filter((w) => w.event === 'terminal-manager-session-exit')).toEqual([]);+ });++ test('a killed session whose exit carries a signal still routes to info', () => {+ const h = makeManager();+ createStartedTerminal(h.mgr, {+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });+ h.mgr.kill({ windowId: 1, ptyId: 'pty-1' });+ h.forked[0]?.emitMessage({ type: 'exit', ptyId: 'pty-1', exitCode: 0, signal: 9 });++ const line = h.infos.find((w) => w.event === 'terminal-manager-session-exit');+ expect(line?.killRequested).toBe(true);+ expect(line?.signal).toBe(9);+ expect(h.warns.filter((w) => w.event === 'terminal-manager-session-exit')).toEqual([]);+ });++ test('a host death that reported no exit code records exitCode null, not a number', () => {+ const h = makeManager();+ createStartedTerminal(h.mgr, {+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });+ h.forked[0]?.emitExit(null);++ const line = h.warns.find((w) => w.event === 'terminal-manager-session-exit');+ expect(line?.reason).toBe('host-exited');+ expect(line?.exitCode).toBeNull();+ });++ test('the exit line carries the shell family the host resolved for that session', () => {+ const h = makeManager();+ createStartedTerminal(h.mgr, {+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });+ h.forked[0]?.emitMessage({+ type: 'shell-notice',+ ptyId: 'pty-1',+ notice: 'shell-resolved',+ shellFamily: 'powershell',+ });+ h.forked[0]?.emitMessage({ type: 'exit', ptyId: 'pty-1', exitCode: 0, signal: null });++ const line = [...h.infos, ...h.warns].find((w) => w.event === 'terminal-manager-session-exit');+ expect(line?.shellFamily).toBe('powershell');+ });++ test('an app shutdown names its cause, so an update install is not read as a quit', () => {+ const h = makeManager();+ createStartedTerminal(h.mgr, {+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });+ void h.mgr.killAll('update-install');++ const line = h.infos.find((w) => w.event === 'terminal-manager-session-exit');+ expect(line?.reason).toBe('app-shutdown');+ expect(line?.cause).toBe('update-install');+ });+test('maps a host spawn-error to a never-started exit carrying the message', () => {const h = makeManager();createStartedTerminal(h.mgr, {@@ -1341,7 +1747,7 @@ describe('createTerminalManager — lifecycle reap', () => {cols: 80,rows: 24,});- h.mgr.killAll();+ h.mgr.killAll('quit');expect(h.forked[0]?.posted.at(-1)).toEqual({ type: 'shutdown' });expect(h.forked[1]?.posted.at(-1)).toEqual({ type: 'shutdown' });expect(h.forked[0]?.killed).toBe(0);@@ -1370,7 +1776,7 @@ describe('createTerminalManager — lifecycle reap', () => {});let settled = false;- const quit = h.mgr.killAll().then(() => {+ const quit = h.mgr.killAll('quit').then(() => {settled = true;});await new Promise((resolve) => setImmediate(resolve));@@ -1392,7 +1798,7 @@ describe('createTerminalManager — lifecycle reap', () => {});let settled = false;- const quit = h.mgr.killAll().then(() => {+ const quit = h.mgr.killAll('quit').then(() => {settled = true;});await new Promise((resolve) => setImmediate(resolve));@@ -1434,7 +1840,7 @@ describe('createTerminalManager — lifecycle reap', () => {});}- expect(() => mgr.killAll()).not.toThrow();+ expect(() => mgr.killAll('quit')).not.toThrow();for (const timer of timers) expect(() => timer()).not.toThrow();expect(forked.map((u) => u.killAttempts)).toEqual([1, 1, 1]);});@@ -1656,7 +2062,7 @@ describe('createTerminalManager — telemetry', () => {h.start(1);h.start(2);h.mgr.input({ windowId: 1, ptyId: 'pty-1', data: 'build\r' });- h.mgr.killAll();+ h.mgr.killAll('quit');expect(h.sessions).toHaveLength(1);expect(h.shellExits).toEqual([]);});diff --git a/packages/desktop/tests/main/terminal-reload-survival.test.ts b/packages/desktop/tests/main/terminal-reload-survival.test.tsindex 15a272adb..90e1babfa 100644--- a/packages/desktop/tests/main/terminal-reload-survival.test.ts+++ b/packages/desktop/tests/main/terminal-reload-survival.test.ts@@ -70,7 +70,7 @@ function makeManager(over?: Partial<TerminalManagerDeps>) {newPtyId: () => `pty-${++idn}`,setTimer: () => 0,clearTimer: () => {},- logger: { warn: () => {} },+ logger: { warn: () => {}, info: () => {} },...over,});return { mgr, forked, exits, shellExits };@@ -385,7 +385,7 @@ describe('issue #351 — re-adopting a surviving session is edge-correct acrosstest('a host that dies between the presence check and the resume post is refused and warned', () => {const warns: Record<string, unknown>[] = [];- const h = makeManager({ logger: { warn: (o) => warns.push(o) } });+ const h = makeManager({ logger: { warn: (o) => warns.push(o), info: () => {} } });const created = createStartedTerminal(h.mgr, {windowId: 1,webContents: makeWebContents(),diff --git a/packages/desktop/tests/main/terminal-window-attach-survival.test.ts b/packages/desktop/tests/main/terminal-window-attach-survival.test.tsindex 0aae10839..08f49d4a8 100644--- a/packages/desktop/tests/main/terminal-window-attach-survival.test.ts+++ b/packages/desktop/tests/main/terminal-window-attach-survival.test.ts@@ -70,7 +70,7 @@ function makeTerminalManager() {return shutdownTimers.length;},clearTimer: () => {},- logger: { warn: () => {} },+ logger: { warn: () => {}, info: () => {} },});const runShutdownTimers = (): void => {for (const cb of shutdownTimers) cb();diff --git a/packages/desktop/tests/main/terminal-window-pty.test.ts b/packages/desktop/tests/main/terminal-window-pty.test.tsindex c04b2c984..8c47941e0 100644--- a/packages/desktop/tests/main/terminal-window-pty.test.ts+++ b/packages/desktop/tests/main/terminal-window-pty.test.ts@@ -42,7 +42,7 @@ function makeManager() {newPtyId: () => `pty-${++idn}`,setTimer: () => 0,clearTimer: () => {},- logger: { warn: () => {} },+ logger: { warn: () => {}, info: () => {} },});return { mgr, forked };}diff --git a/packages/desktop/tests/smoke/terminal-dock.e2e.ts b/packages/desktop/tests/smoke/terminal-dock.e2e.tsindex f572d7607..6c9582b7f 100644--- a/packages/desktop/tests/smoke/terminal-dock.e2e.ts+++ b/packages/desktop/tests/smoke/terminal-dock.e2e.ts@@ -249,6 +249,12 @@ const terminalStatus = (page: Page) => page.locator('[data-terminal-status]');const readinessBanner = (page: Page) =>page.getByRole('tabpanel').getByTestId('terminal-readiness-banner');+const activeTerminalOutput = (page: Page) =>+ page+ .getByRole('tabpanel')+ .getByRole('region', { name: 'Terminal', exact: true })+ .locator('.xterm-accessibility');+async function waitForRendererResponsive(page: Page): Promise<void> {await expect(async () => {for (let probe = 0; probe < 3; probe += 1) {@@ -1005,9 +1011,7 @@ test.describe('Docked terminal — live Electron', () => {);const beforeRestart = await page.evaluate(() => window.okDesktop?.terminal.list());expect(beforeRestart).toHaveLength(2);- const terminalOutput = page- .getByRole('region', { name: 'Terminal', exact: true })- .locator('.xterm-accessibility');+ const terminalOutput = activeTerminalOutput(page);await expect(terminalOutput).toContainText('FAKE_CLAUDE_TUI_READY');await restartNotice.getByRole('button', { name: 'Restart terminal' }).click();await expect(restartNotice).toHaveCount(0);@@ -1060,6 +1064,9 @@ test.describe('Docked terminal — live Electron', () => {page.getByRole('tablist', { name: 'Terminal sessions' }).getByRole('tab'),).toHaveCount(index + 2);await expect(readinessBanner(page)).toBeVisible({ timeout: 15_000 });+ await expect(activeTerminalOutput(page)).toContainText('FAKE_CLAUDE_TUI_READY', {+ timeout: 15_000,+ });}const sessionsBefore = await page.evaluate(() => window.okDesktop?.terminal.list());expect(sessionsBefore).toHaveLength(3);