Compare commits

..
Author SHA1 Message Date
Julius Marminge e6fd90df22 Guard delayed terminal exit callback
- Skip `onSessionExited` if exit handling was reset before timeout runs
- Prevent stale async exit callbacks from firing in terminal drawer
2026-02-27 18:02:09 -08:00
Julius Marminge dd5b985d26 Handle terminal exit writes and auto-close exited terminal view
- Ignore late write calls after a terminal session has already exited
- Add regression test for trailing writes after exit
- Close terminal drawer session once an exit event is handled
2026-02-27 17:55:47 -08:00
5 changed files with 56 additions and 73 deletions

No files matched your search

@@ -394,6 +394,21 @@ describe("TerminalManager", () => {
manager.dispose();
});
it("ignores trailing writes after terminal exit", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitExit({ exitCode: 0, signal: 0 });
await expect(manager.write({ threadId: "thread-1", data: "\r" })).resolves.toBeUndefined();
expect(process.writes).toEqual([]);
manager.dispose();
});
it("emits subprocess activity events when child-process state changes", async () => {
let hasRunningSubprocess = false;
const { manager } = makeManager(5, {
@@ -438,6 +438,9 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
const input = decodeTerminalWriteInput(raw);
const session = this.requireSession(input.threadId, input.terminalId);
if (!session.process || session.status !== "running") {
if (session.status === "exited") {
return;
}
throw new Error(
`Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`,
);
@@ -25,7 +25,6 @@ import {
MAX_THREAD_TERMINAL_COUNT,
type ThreadTerminalGroup,
} from "../types";
import { isIgnorableTerminalWriteError } from "../terminal-errors";
import { readNativeApi } from "~/nativeApi";
const MIN_DRAWER_HEIGHT = 180;
@@ -113,7 +112,7 @@ interface TerminalViewportProps {
terminalId: string;
cwd: string;
runtimeEnv?: Record<string, string>;
onCloseTerminal: (terminalId: string) => void;
onSessionExited: () => void;
focusRequestId: number;
autoFocus: boolean;
resizeEpoch: number;
@@ -125,7 +124,7 @@ function TerminalViewport({
terminalId,
cwd,
runtimeEnv,
onCloseTerminal,
onSessionExited,
focusRequestId,
autoFocus,
resizeEpoch,
@@ -134,6 +133,12 @@ function TerminalViewport({
const containerRef = useRef<HTMLDivElement>(null);
const terminalRef = useRef<Terminal | null>(null);
const fitAddonRef = useRef<FitAddon | null>(null);
const onSessionExitedRef = useRef(onSessionExited);
const hasHandledExitRef = useRef(false);
useEffect(() => {
onSessionExitedRef.current = onSessionExited;
}, [onSessionExited]);
useEffect(() => {
const mount = containerRef.current;
@@ -159,12 +164,6 @@ function TerminalViewport({
const api = readNativeApi();
if (!api) return;
let closeRequested = false;
const requestTerminalClose = () => {
if (closeRequested) return;
closeRequested = true;
onCloseTerminal(terminalId);
};
const sendTerminalInput = async (data: string, fallbackError: string) => {
const activeTerminal = terminalRef.current;
@@ -172,10 +171,6 @@ function TerminalViewport({
try {
await api.terminal.write({ threadId, terminalId, data });
} catch (error) {
if (isIgnorableTerminalWriteError(error)) {
requestTerminalClose();
return;
}
writeSystemMessage(activeTerminal, error instanceof Error ? error.message : fallbackError);
}
};
@@ -256,13 +251,12 @@ function TerminalViewport({
const inputDisposable = terminal.onData((data) => {
void api.terminal
.write({ threadId, terminalId, data })
.catch((err) => {
if (isIgnorableTerminalWriteError(err)) {
requestTerminalClose();
return;
}
writeSystemMessage(terminal, err instanceof Error ? err.message : "Terminal write failed");
});
.catch((err) =>
writeSystemMessage(
terminal,
err instanceof Error ? err.message : "Terminal write failed",
),
);
});
const themeObserver = new MutationObserver(() => {
@@ -320,6 +314,7 @@ function TerminalViewport({
}
if (event.type === "started" || event.type === "restarted") {
hasHandledExitRef.current = false;
activeTerminal.write("\u001bc");
if (event.snapshot.history.length > 0) {
activeTerminal.write(event.snapshot.history);
@@ -339,7 +334,26 @@ function TerminalViewport({
}
if (event.type === "exited") {
requestTerminalClose();
const details = [
typeof event.exitCode === "number" ? `code ${event.exitCode}` : null,
typeof event.exitSignal === "number" ? `signal ${event.exitSignal}` : null,
]
.filter((value): value is string => value !== null)
.join(", ");
writeSystemMessage(
activeTerminal,
details.length > 0 ? `Process exited (${details})` : "Process exited",
);
if (hasHandledExitRef.current) {
return;
}
hasHandledExitRef.current = true;
window.setTimeout(() => {
if (!hasHandledExitRef.current) {
return;
}
onSessionExitedRef.current();
}, 0);
}
});
@@ -375,7 +389,7 @@ function TerminalViewport({
fitAddonRef.current = null;
terminal.dispose();
};
}, [cwd, onCloseTerminal, runtimeEnv, terminalId, threadId]);
}, [cwd, runtimeEnv, terminalId, threadId]);
useEffect(() => {
if (!autoFocus) return;
@@ -788,7 +802,7 @@ export default function ThreadTerminalDrawer({
terminalId={terminalId}
cwd={cwd}
{...(runtimeEnv ? { runtimeEnv } : {})}
onCloseTerminal={onCloseTerminal}
onSessionExited={() => onCloseTerminal(terminalId)}
focusRequestId={focusRequestId}
autoFocus={terminalId === resolvedActiveTerminalId}
resizeEpoch={resizeEpoch}
@@ -806,7 +820,7 @@ export default function ThreadTerminalDrawer({
terminalId={resolvedActiveTerminalId}
cwd={cwd}
{...(runtimeEnv ? { runtimeEnv } : {})}
onCloseTerminal={onCloseTerminal}
onSessionExited={() => onCloseTerminal(resolvedActiveTerminalId)}
focusRequestId={focusRequestId}
autoFocus
resizeEpoch={resizeEpoch}
-29
View File
@@ -1,29 +0,0 @@
import { describe, expect, it } from "vitest";
import { isIgnorableTerminalWriteError } from "./terminal-errors";
describe("isIgnorableTerminalWriteError", () => {
it("treats not-running terminal errors as ignorable", () => {
expect(
isIgnorableTerminalWriteError(
new Error("Terminal is not running for thread: thread-1, terminal: default"),
),
).toBe(true);
});
it("treats unknown terminal thread errors as ignorable", () => {
expect(
isIgnorableTerminalWriteError(
`TerminalError: Failed to write to terminal
├─ cause: Error: Unknown terminal thread: thread-1, terminal: default`,
),
).toBe(true);
});
it("does not ignore unrelated terminal write failures", () => {
expect(isIgnorableTerminalWriteError(new Error("Request timed out: terminal.write"))).toBe(
false,
);
expect(isIgnorableTerminalWriteError(null)).toBe(false);
});
});
-20
View File
@@ -1,20 +0,0 @@
const BENIGN_TERMINAL_WRITE_ERROR_MARKERS = [
"terminal is not running",
"unknown terminal thread",
] as const;
function errorMessage(error: unknown): string | null {
if (error instanceof Error) {
return error.message;
}
if (typeof error === "string") {
return error;
}
return null;
}
export function isIgnorableTerminalWriteError(error: unknown): boolean {
const message = errorMessage(error)?.toLowerCase();
if (!message) return false;
return BENIGN_TERMINAL_WRITE_ERROR_MARKERS.some((marker) => message.includes(marker));
}