Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Drop a killed terminal session from the window's session list (#4497)

Nick Gomez75e23431055b
diff --git a/.changeset/closed-terminal-leaves-the-session-list.md b/.changeset/closed-terminal-leaves-the-session-list.md
new file mode 100644
index 000000000..7521ef5bc
--- /dev/null
+++ b/.changeset/closed-terminal-leaves-the-session-list.md
@@ -0,0 +1,6 @@
+---
+"@inkeep/open-knowledge": patch
+"@inkeep/open-knowledge-desktop": patch
+---
+
+Reloading the desktop app's window right after you close or restart a terminal no longer brings the closed session back. It used to come back as an extra tab bound to a shell that was already shutting down, and after a restart that tab carried the same name as its replacement, such as a second `Terminal 2`. A session now leaves the window's session list when you close or restart it, rather than when its shell finishes exiting.
diff --git a/packages/app/src/components/TerminalPanel.dom.test.tsx b/packages/app/src/components/TerminalPanel.dom.test.tsx
index 6c3e36a69..8980d1cfb 100644
--- a/packages/app/src/components/TerminalPanel.dom.test.tsx
+++ b/packages/app/src/components/TerminalPanel.dom.test.tsx
@@ -2148,6 +2148,9 @@ describe('TerminalPanel', () => {
fireEvent.click(screen.getByRole('button', { name: 'Restart terminal' }));
await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(3));
expect(terminal.kill).toHaveBeenCalledExactlyOnceWith('pty-1');
+ expect(terminal.kill.mock.invocationCallOrder[0]).toBeLessThan(
+ terminal.create.mock.invocationCallOrder[2],
+ );
expect(originalTerm?.dispose).toHaveBeenCalledTimes(1);
expect(siblingTerm?.dispose).not.toHaveBeenCalled();
expect(terminal.create).toHaveBeenLastCalledWith(
diff --git a/packages/desktop/src/main/terminal-manager.ts b/packages/desktop/src/main/terminal-manager.ts
index 2f5e7d3a3..d3474cf83 100644
--- a/packages/desktop/src/main/terminal-manager.ts
+++ b/packages/desktop/src/main/terminal-manager.ts
@@ -83,6 +83,7 @@ interface SessionState {
staleToken: TimerToken | null;
pendingBytes: number;
paused: boolean;
+ killRequested: boolean;
commandRan: boolean;
customLabel: string | null;
ordinal: number | null;
@@ -100,6 +101,10 @@ interface PtyWindowHandle {
shutdownResolve: (() => void) | null;
}
+function isLiveSession(session: SessionState): boolean {
+ return session.pendingCreate === null && !session.killRequested;
+}
+
const DEFAULT_COALESCE_MS = 5;
const DEFAULT_HIGH_WATER = 1024 * 1024;
const DEFAULT_LOW_WATER = 256 * 1024;
@@ -227,7 +232,7 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage
session.outbound = '';
pushData(handle, ptyId, chunk);
session.pendingBytes += chunk.length;
- if (!session.paused && session.pendingBytes > highWater) {
+ if (!session.paused && !session.killRequested && session.pendingBytes > highWater) {
handle.utility.postMessage({ type: 'pause', ptyId });
session.paused = true;
}
@@ -408,7 +413,7 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage
pushExit(handle, { ptyId, neverStarted: true, hostExited: true });
} else {
maybeRecordSession(session);
- deps.recordShellExit?.({ crashed: true });
+ deps.recordShellExit?.({ crashed: !session.killRequested });
pushExit(handle, { ptyId, exitCode: code ?? 1, signal: null, hostExited: true });
}
}
@@ -469,6 +474,7 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage
flushToken: null,
pendingBytes: 0,
paused: false,
+ killRequested: false,
commandRan: false,
customLabel: null,
ordinal: null,
@@ -526,6 +532,12 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage
handle.sessions.delete(req.ptyId);
return;
}
+ session.killRequested = true;
+ if (session.paused) {
+ session.paused = false;
+ session.pendingBytes = 0;
+ handle.utility.postMessage({ type: 'resume', ptyId: req.ptyId });
+ }
handle.utility.postMessage({ type: 'kill', ptyId: req.ptyId });
},
@@ -544,7 +556,7 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage
const handle = handles.get(windowId);
if (!handle) return [];
return [...handle.sessions.entries()]
- .filter(([, session]) => session.pendingCreate === null)
+ .filter(([, session]) => isLiveSession(session))
.sort((a, b) => a[1].order - b[1].order)
.map(([ptyId, session]) => ({
ptyId,
@@ -579,6 +591,14 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage
const handle = handles.get(req.windowId);
const session = handle?.sessions.get(req.ptyId);
if (!handle || !session) return { ok: false, reason: 'unknown-session' };
+ if (session.killRequested) {
+ deps.logger?.warn({
+ event: 'terminal-manager-adopt-killed-session',
+ windowId: req.windowId,
+ ptyId: req.ptyId,
+ });
+ return { ok: false, reason: 'unknown-session' };
+ }
if (session.pendingCreate !== null) {
if (!req.start) {
deps.logger?.warn({
@@ -602,9 +622,7 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage
handle.webContents = req.webContents;
session.pendingCreate = null;
clearSessionTimers(session);
- const liveCount = [...handle.sessions.values()].filter(
- (live) => live.pendingCreate === null,
- ).length;
+ const liveCount = [...handle.sessions.values()].filter(isLiveSession).length;
// STOP: post and return in the same tick; TerminalPanel installs its readiness scanner after this reply, so an await below would let the shell's first output outrun it.
try {
handle.utility.postMessage(message);
diff --git a/packages/desktop/tests/main/terminal-manager.test.ts b/packages/desktop/tests/main/terminal-manager.test.ts
index 62626df82..1c3c1ad3f 100644
--- a/packages/desktop/tests/main/terminal-manager.test.ts
+++ b/packages/desktop/tests/main/terminal-manager.test.ts
@@ -280,6 +280,34 @@ describe('terminal creation waits for the renderer to subscribe', () => {
);
});
+ test('a killed session is refused by both adopt forms, and the refusal names the session', () => {
+ const h = makeManager();
+ const wc = makeWebContents();
+ createStartedTerminal(h.mgr, {
+ windowId: 1,
+ webContents: wc,
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ h.mgr.kill({ windowId: 1, ptyId: 'pty-1' });
+
+ expect(h.mgr.adoptSession({ windowId: 1, ptyId: 'pty-1', webContents: wc })).toEqual({
+ ok: false,
+ reason: 'unknown-session',
+ });
+ expect(
+ h.mgr.adoptSession({ windowId: 1, ptyId: 'pty-1', webContents: wc, start: true }),
+ ).toEqual({ ok: false, reason: 'unknown-session' });
+ expect(h.warns).toContainEqual(
+ expect.objectContaining({
+ event: 'terminal-manager-adopt-killed-session',
+ windowId: 1,
+ ptyId: 'pty-1',
+ }),
+ );
+ });
+
test('logs the reservations it reaps when the owning window closes', () => {
const h = reserve();
h.mgr.killForWindow(1);
@@ -1130,6 +1158,68 @@ describe('createTerminalManager — backpressure', () => {
expect(h.forked[0]?.posted).not.toContainEqual({ type: 'resume', ptyId: 'pty-1' });
});
+ test('a kill lifts the pause it can no longer drain, before it posts the kill', () => {
+ const h = makeManager({ highWaterBytes: 100, lowWaterBytes: 20 });
+ createStartedTerminal(h.mgr, {
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'x'.repeat(150) });
+ h.runTimers();
+ expect(h.forked[0]?.posted).toContainEqual({ type: 'pause', ptyId: 'pty-1' });
+
+ h.mgr.kill({ windowId: 1, ptyId: 'pty-1' });
+
+ const posted = h.forked[0]?.posted ?? [];
+ const resumedAt = posted.findIndex((m) => m.type === 'resume' && m.ptyId === 'pty-1');
+ const killedAt = posted.findIndex((m) => m.type === 'kill' && m.ptyId === 'pty-1');
+ expect(resumedAt).toBeGreaterThanOrEqual(0);
+ expect(killedAt).toBeGreaterThan(resumedAt);
+ });
+
+ test('post-kill output does not re-arm the pause the kill just lifted', () => {
+ const h = makeManager({ highWaterBytes: 100, lowWaterBytes: 20 });
+ createStartedTerminal(h.mgr, {
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'x'.repeat(150) });
+ h.runTimers();
+ h.mgr.kill({ windowId: 1, ptyId: 'pty-1' });
+
+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'y'.repeat(150) });
+ h.runTimers();
+
+ expect(h.dataPayloads()).toEqual(['x'.repeat(150), 'y'.repeat(150)]);
+ expect(
+ (h.forked[0]?.posted ?? []).filter((m) => m.type === 'pause' && m.ptyId === 'pty-1'),
+ ).toHaveLength(1);
+ });
+
+ test('a kill on an unpaused session posts no resume', () => {
+ const h = makeManager({ highWaterBytes: 100, lowWaterBytes: 20 });
+ createStartedTerminal(h.mgr, {
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'x'.repeat(10) });
+ h.runTimers();
+
+ h.mgr.kill({ windowId: 1, ptyId: 'pty-1' });
+
+ expect(h.forked[0]?.posted).not.toContainEqual({ type: 'resume', ptyId: 'pty-1' });
+ expect(h.forked[0]?.posted).toContainEqual({ type: 'kill', ptyId: 'pty-1' });
+ });
+
test('drain for a stale ptyId is ignored', () => {
const h = makeManager({ highWaterBytes: 100, lowWaterBytes: 20 });
createStartedTerminal(h.mgr, {
@@ -1504,6 +1594,26 @@ describe('createTerminalManager — telemetry', () => {
expect(h.concurrent).toEqual([{ count: 1 }, { count: 2 }]);
});
+ test('the concurrency count drops a killed shell at the kill, not at its exit', () => {
+ const h = makeTelemetryManager();
+ h.start(1);
+ h.start(1);
+ h.mgr.kill({ windowId: 1, ptyId: 'pty-1' });
+ h.start(1);
+ h.forked[0]?.emitMessage({ type: 'exit', ptyId: 'pty-1', exitCode: 0, signal: null });
+ h.start(1);
+ expect(h.concurrent.map((c) => c.count)).toEqual([1, 2, 2, 3]);
+ });
+
+ test('a host death books a shell the window had already closed as a clean exit', () => {
+ const h = makeTelemetryManager();
+ h.start(1);
+ h.start(1);
+ h.mgr.kill({ windowId: 1, ptyId: 'pty-1' });
+ h.forked[0]?.emitExit(1);
+ expect(h.shellExits).toEqual([{ crashed: false }, { crashed: true }]);
+ });
+
test('a spawn-error books no shell exit at all — the shell never ran', () => {
const h = makeTelemetryManager();
h.start(1);
diff --git a/packages/desktop/tests/main/terminal-reload-survival.test.ts b/packages/desktop/tests/main/terminal-reload-survival.test.ts
index 59e515100..15a272adb 100644
--- a/packages/desktop/tests/main/terminal-reload-survival.test.ts
+++ b/packages/desktop/tests/main/terminal-reload-survival.test.ts
@@ -1,3 +1,4 @@
+import type { OkPtyExit } from '@inkeep/open-knowledge-core/desktop-bridge';
import { describe, expect, test } from 'vitest';
import {
createTerminalManager,
@@ -7,7 +8,7 @@ import {
} from '../../src/main/terminal-manager.ts';
import type { SendableWebContents } from '../../src/shared/ipc-send.ts';
import type { PtyHostIncomingMessage } from '../../src/utility/pty-host.ts';
-import { createStartedTerminal } from '../support/terminal-create.test-helper.ts';
+import { createStartedTerminal, startedPtyId } from '../support/terminal-create.test-helper.ts';
class FakeUtility {
posted: PtyHostIncomingMessage[] = [];
@@ -49,6 +50,8 @@ function makeWebContents(): FakeWebContents {
function makeManager(over?: Partial<TerminalManagerDeps>) {
const forked: FakeUtility[] = [];
+ const exits: OkPtyExit[] = [];
+ const shellExits: Array<{ crashed: boolean }> = [];
let idn = 0;
const mgr = createTerminalManager({
canSpawnAt: () => true,
@@ -58,14 +61,19 @@ function makeManager(over?: Partial<TerminalManagerDeps>) {
return u as unknown as PtyUtilityLike;
},
sendData: () => {},
- sendExit: () => {},
+ sendExit: (_wc, payload) => {
+ exits.push(payload);
+ },
+ recordShellExit: (info) => {
+ shellExits.push(info);
+ },
newPtyId: () => `pty-${++idn}`,
setTimer: () => 0,
clearTimer: () => {},
logger: { warn: () => {} },
...over,
});
- return { mgr, forked };
+ return { mgr, forked, exits, shellExits };
}
function resolveLiveSessionIds(mgr: TerminalManager, windowId: number): readonly string[] | null {
@@ -434,3 +442,90 @@ describe('issue #351 — re-adopting a surviving session is edge-correct across
expect(outcome).toEqual({ ok: false, reason: 'unknown-session' });
});
});
+
+describe('a session the window asked to kill is no longer a survivor, before the host reports its exit', () => {
+ test('a killed session leaves the reload inventory at the kill, not at the exit', () => {
+ const h = makeManager();
+ const wc = makeWebContents();
+ const kept = createStartedTerminal(h.mgr, {
+ windowId: 1,
+ webContents: wc,
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ const closed = createStartedTerminal(h.mgr, {
+ windowId: 1,
+ webContents: wc,
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ const idKept = startedPtyId(kept);
+ const idClosed = startedPtyId(closed);
+
+ h.mgr.kill({ windowId: 1, ptyId: idClosed });
+
+ expect(h.forked[0]?.posted).toContainEqual({ type: 'kill', ptyId: idClosed });
+ expect(h.mgr.listSessions(1).map((s) => s.ptyId)).toEqual([idKept]);
+ expect(h.exits).toEqual([]);
+
+ h.forked[0]?.emitMessage({ type: 'exit', ptyId: idClosed, exitCode: 0, signal: null });
+
+ expect(h.exits).toEqual([{ ptyId: idClosed, exitCode: 0, signal: null }]);
+ expect(h.shellExits).toEqual([{ crashed: false }]);
+ expect(h.mgr.listSessions(1).map((s) => s.ptyId)).toEqual([idKept]);
+ });
+
+ test('a replacement spawned while the killed shell is still dying is the only session of its tab', () => {
+ const h = makeManager();
+ const wc = makeWebContents();
+ const first = createStartedTerminal(h.mgr, {
+ windowId: 1,
+ webContents: wc,
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ const idFirst = startedPtyId(first);
+ h.mgr.setSessionMeta({ windowId: 1, ptyId: idFirst, ordinal: 2 });
+
+ h.mgr.kill({ windowId: 1, ptyId: idFirst });
+ const replacement = createStartedTerminal(h.mgr, {
+ windowId: 1,
+ webContents: wc,
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ const idReplacement = startedPtyId(replacement);
+ h.mgr.setSessionMeta({ windowId: 1, ptyId: idReplacement, ordinal: 2 });
+
+ expect(h.mgr.listSessions(1)).toEqual([
+ { ptyId: idReplacement, customLabel: null, ordinal: 2 },
+ ]);
+ });
+
+ test('adopting a killed session is refused while the host still holds it', () => {
+ const h = makeManager();
+ const created = createStartedTerminal(h.mgr, {
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ const idClosed = startedPtyId(created);
+
+ h.mgr.kill({ windowId: 1, ptyId: idClosed });
+ const postedBeforeAdopt = [...(h.forked[0]?.posted ?? [])];
+ const outcome = h.mgr.adoptSession({
+ windowId: 1,
+ ptyId: idClosed,
+ webContents: makeWebContents(),
+ });
+
+ expect(outcome).toEqual({ ok: false, reason: 'unknown-session' });
+ expect(h.forked[0]?.posted).toEqual(postedBeforeAdopt);
+ });
+});
diff --git a/packages/desktop/tests/support/terminal-create.test-helper.ts b/packages/desktop/tests/support/terminal-create.test-helper.ts
index c73b80d27..a640500fc 100644
--- a/packages/desktop/tests/support/terminal-create.test-helper.ts
+++ b/packages/desktop/tests/support/terminal-create.test-helper.ts
@@ -16,3 +16,8 @@ export function createStartedTerminal(
}
return result;
}
+
+export function startedPtyId(result: ReturnType<TerminalManager['create']>): string {
+ if (!result.ok) throw new Error(result.reason);
+ return result.ptyId;
+}