Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Report a Windows terminal that never attached as a start failure (#4914)

Nick Gomez087f7c740100
diff --git a/.changeset/windows-terminal-attach-failure-not-started.md b/.changeset/windows-terminal-attach-failure-not-started.md
new file mode 100644
index 000000000..42d29a2b3
--- /dev/null
+++ b/.changeset/windows-terminal-attach-failure-not-started.md
@@ -0,0 +1,6 @@
+---
+"@inkeep/open-knowledge": patch
+"@inkeep/open-knowledge-desktop": patch
+---
+
+On Windows, a terminal whose console never attaches now reports "The terminal couldn't start." with Try again, instead of a session that appeared to exit.
diff --git a/packages/desktop/src/main/terminal-manager.ts b/packages/desktop/src/main/terminal-manager.ts
index 3b3480ff8..016e00085 100644
--- a/packages/desktop/src/main/terminal-manager.ts
+++ b/packages/desktop/src/main/terminal-manager.ts
@@ -295,8 +295,13 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage
? (raw as PtyHostOutgoingMessage)
: null;
case 'spawn-error':
- return (typeof m.message === 'string' && m.launchFailure === undefined) ||
- (m.message === undefined && isWindowsShellLaunchFailureReason(m.launchFailure))
+ return (m.shellNeverAttached === undefined &&
+ ((typeof m.message === 'string' && m.launchFailure === undefined) ||
+ (m.message === undefined && isWindowsShellLaunchFailureReason(m.launchFailure)))) ||
+ (m.shellNeverAttached === true &&
+ m.message === undefined &&
+ m.launchFailure === undefined &&
+ (m.exitCode === undefined || typeof m.exitCode === 'number'))
? (raw as PtyHostOutgoingMessage)
: null;
case 'shell-notice':
@@ -371,6 +376,22 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage
const { ptyId } = message;
clearSessionTimers(session);
handle.sessions.delete(ptyId);
+ const elapsedMs =
+ session.spawnedAt === null ? null : Math.max(0, Date.now() - session.spawnedAt);
+ const killRequested = session.killRequested;
+ if (message.shellNeverAttached === true) {
+ deps.logger?.warn({
+ event: 'terminal-manager-spawn-error',
+ windowId,
+ ptyId,
+ shellNeverAttached: true,
+ exitCode: message.exitCode ?? null,
+ elapsedMs,
+ killRequested,
+ });
+ pushExit(handle, { ptyId, neverStarted: true });
+ break;
+ }
deps.logger?.warn({
event: 'terminal-manager-spawn-error',
windowId,
@@ -378,6 +399,8 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage
...(message.launchFailure === undefined
? { message: message.message }
: { launchFailure: message.launchFailure }),
+ elapsedMs,
+ killRequested,
});
pushExit(
handle,
diff --git a/packages/desktop/src/utility/pty-host.ts b/packages/desktop/src/utility/pty-host.ts
index 270ce688b..0357f4905 100644
--- a/packages/desktop/src/utility/pty-host.ts
+++ b/packages/desktop/src/utility/pty-host.ts
@@ -101,12 +101,22 @@ type PtySpawnErrorMessage =
ptyId: string;
message: string;
launchFailure?: undefined;
+ shellNeverAttached?: undefined;
}
| {
type: 'spawn-error';
ptyId: string;
message?: undefined;
launchFailure: WindowsShellLaunchFailureReason;
+ shellNeverAttached?: undefined;
+ }
+ | {
+ type: 'spawn-error';
+ ptyId: string;
+ message?: undefined;
+ launchFailure?: undefined;
+ shellNeverAttached: true;
+ exitCode: number | undefined;
};
type PtyShellNoticeMessage =
| {
@@ -562,6 +572,17 @@ function conptyDllLoadFailureReason(
return prefix === undefined ? null : CONPTY_DLL_LOAD_ERROR_PREFIXES[prefix];
}
+function classifyNodePtyEnding(
+ ptyId: string,
+ pidAtExit: number,
+ { exitCode, signal }: { exitCode: number | undefined; signal?: number },
+): PtyExitMessage | Extract<PtySpawnErrorMessage, { shellNeverAttached: true }> {
+ if (pidAtExit === 0) {
+ return { type: 'spawn-error', ptyId, shellNeverAttached: true, exitCode };
+ }
+ return { type: 'exit', ptyId, exitCode, signal: signal ?? null };
+}
+
export function setupPtyHost(deps: SetupPtyHostDeps): PtyHostHandle {
const env = deps.env ?? (process.env as Record<string, string | undefined>);
const platform = deps.platform ?? process.platform;
@@ -768,10 +789,10 @@ export function setupPtyHost(deps: SetupPtyHostDeps): PtyHostHandle {
pty.onData((data) => {
if (sessions.get(ptyId) === pty) post({ type: 'data', ptyId, data });
});
- pty.onExit(({ exitCode, signal }) => {
+ pty.onExit((event) => {
clearKillEscalate(ptyId);
if (sessions.get(ptyId) === pty) sessions.delete(ptyId);
- post({ type: 'exit', ptyId, exitCode, signal: signal ?? null });
+ post(classifyNodePtyEnding(ptyId, pty.pid, event));
if (shuttingDown && sessions.size === 0) finishShutdown();
});
}
diff --git a/packages/desktop/tests/main/terminal-manager.test.ts b/packages/desktop/tests/main/terminal-manager.test.ts
index 2d58b0856..896cb243a 100644
--- a/packages/desktop/tests/main/terminal-manager.test.ts
+++ b/packages/desktop/tests/main/terminal-manager.test.ts
@@ -1319,6 +1319,107 @@ describe('createTerminalManager — exit + crash surfacing', () => {
);
});
+ test('reports a pty that ended before its shell attached as a start failure, keeping the exit code in the log', () => {
+ const h = makeManager();
+ createStartedTerminal(h.mgr, {
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ h.forked[0]?.emitMessage({
+ type: 'spawn-error',
+ ptyId: 'pty-1',
+ shellNeverAttached: true,
+ exitCode: 2,
+ });
+ expect(h.exits()).toEqual([{ ptyId: 'pty-1', neverStarted: true }]);
+ expect(h.warns).toContainEqual(
+ expect.objectContaining({
+ event: 'terminal-manager-spawn-error',
+ ptyId: 'pty-1',
+ shellNeverAttached: true,
+ exitCode: 2,
+ }),
+ );
+ });
+
+ test.each([
+ { failure: 'the shell never attached', reported: { shellNeverAttached: true, exitCode: -1 } },
+ { failure: 'the host reports a message', reported: { message: 'EMFILE: too many open files' } },
+ { failure: 'the launch could not be composed', reported: { launchFailure: 'unsafe-argument' } },
+ ])(
+ 'logs how long a start took to fail when $failure, so a readiness timeout reads apart from an immediate failure',
+ ({ reported }) => {
+ const now = vi.spyOn(Date, 'now');
+ try {
+ const h = makeManager();
+ now.mockReturnValue(1_000);
+ createStartedTerminal(h.mgr, {
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ now.mockReturnValue(6_000);
+ h.forked[0]?.emitMessage({ type: 'spawn-error', ptyId: 'pty-1', ...reported });
+ expect(h.warns).toContainEqual(
+ expect.objectContaining({
+ event: 'terminal-manager-spawn-error',
+ ...reported,
+ elapsedMs: 5_000,
+ }),
+ );
+ } finally {
+ now.mockRestore();
+ }
+ },
+ );
+
+ test.each(
+ [
+ { failure: 'the shell never attached', reported: { shellNeverAttached: true, exitCode: -1 } },
+ {
+ failure: 'the host reports a message',
+ reported: { message: 'EMFILE: too many open files' },
+ },
+ {
+ failure: 'the launch could not be composed',
+ reported: { launchFailure: 'unsafe-argument' },
+ },
+ ].flatMap((row) => [
+ { ...row, killRequested: true },
+ { ...row, killRequested: false },
+ ]),
+ )(
+ 'states killRequested: $killRequested on the start-failure warning when $failure, without booking a shell exit',
+ ({ reported, killRequested }) => {
+ const recordShellExit = vi.fn();
+ const h = makeManager({ recordShellExit });
+ createStartedTerminal(h.mgr, {
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ if (killRequested) h.mgr.kill({ windowId: 1, ptyId: 'pty-1' });
+ h.forked[0]?.emitMessage({ type: 'spawn-error', ptyId: 'pty-1', ...reported });
+ expect(h.warns).toContainEqual(
+ expect.objectContaining({
+ event: 'terminal-manager-spawn-error',
+ ptyId: 'pty-1',
+ ...reported,
+ killRequested,
+ }),
+ );
+ expect(h.infos.filter((line) => line.ptyId === 'pty-1')).toEqual([]);
+ expect(recordShellExit).not.toHaveBeenCalled();
+ },
+ );
+
test('rejects a spawn-error that carries neither a message nor a known launch reason', () => {
const h = makeManager();
createStartedTerminal(h.mgr, {
@@ -1383,6 +1484,39 @@ describe('createTerminalManager — exit + crash surfacing', () => {
);
});
+ test.each([
+ { shape: 'also carries a message', extra: { exitCode: -1, message: 'EACCES' } },
+ {
+ shape: 'also carries a launch reason',
+ extra: { exitCode: -1, launchFailure: 'unsafe-argument' },
+ },
+ { shape: 'carries a non-numeric exit code', extra: { exitCode: '-1' } },
+ ])('rejects a never-attached spawn-error that $shape', ({ extra }) => {
+ const h = makeManager();
+ createStartedTerminal(h.mgr, {
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ h.forked[0]?.emitMessage({
+ type: 'spawn-error',
+ ptyId: 'pty-1',
+ shellNeverAttached: true,
+ ...extra,
+ });
+ expect(h.exits()).toEqual([{ ptyId: 'pty-1', neverStarted: true }]);
+ expect(h.warns).toContainEqual(
+ expect.objectContaining({
+ event: 'pty-host-unexpected-message',
+ ptyId: 'pty-1',
+ rawType: 'spawn-error',
+ reaped: true,
+ }),
+ );
+ });
+
test('a reaped spawn-error drops its session and lands its exit before the best-effort kill post', () => {
const h = makeManager();
createStartedTerminal(h.mgr, {
diff --git a/packages/desktop/tests/support/pty-readiness.test-helper.ts b/packages/desktop/tests/support/pty-readiness.test-helper.ts
index 272db1a87..03e606752 100644
--- a/packages/desktop/tests/support/pty-readiness.test-helper.ts
+++ b/packages/desktop/tests/support/pty-readiness.test-helper.ts
@@ -41,7 +41,12 @@ export function createPtyHostProbe(options: PtyHostProbeOptions): PtyHostProbe {
else if (msg.type === 'exit')
exits.set(msg.ptyId, { exitCode: msg.exitCode, signal: msg.signal });
else if (msg.type === 'spawn-error')
- errors.set(msg.ptyId, msg.message ?? msg.launchFailure);
+ errors.set(
+ msg.ptyId,
+ msg.shellNeverAttached === true
+ ? `shell never attached (exit code ${msg.exitCode ?? 'none'})`
+ : (msg.message ?? msg.launchFailure),
+ );
},
},
spawn: options.spawn,
@@ -148,12 +153,15 @@ export async function waitForCondition(
): Promise<void> {
const intervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS;
const timeoutMs = requireDuration(options.timeoutMs ?? DEFAULT_TIMEOUT_MS, 'timeout', label);
- const deadline = performance.now() + timeoutMs;
+ const startedAt = performance.now();
+ const deadline = startedAt + timeoutMs;
for (;;) {
if (predicate()) return;
const failure = stream.failure();
if (failure !== null) {
- throw new Error(`shell failed before ${label}: ${failure}`);
+ throw new Error(
+ `shell failed before ${label}: ${failure} (after ${Math.round(performance.now() - startedAt)}ms, received ${describeReceived(stream.read())})`,
+ );
}
if (performance.now() >= deadline) {
throw new Error(
@@ -312,7 +320,7 @@ async function waitForShellFirstOutput(
const failure = stream.failure();
if (failure !== null) {
throw new Error(
- `shell died before producing output for ${label}, probe unwritten: ${failure}`,
+ `shell died before producing output for ${label}, probe unwritten: ${failure} (after ${Math.round(performance.now() - startedAt)}ms, received ${describeReceived(stream.read())})`,
);
}
if (performance.now() >= deadline) {
diff --git a/packages/desktop/tests/utility/pty-host-conpty-attach.test.ts b/packages/desktop/tests/utility/pty-host-conpty-attach.test.ts
new file mode 100644
index 000000000..d0d0a8407
--- /dev/null
+++ b/packages/desktop/tests/utility/pty-host-conpty-attach.test.ts
@@ -0,0 +1,380 @@
+import { execFileSync } from 'node:child_process';
+import { closeSync, constants as fsConstants, mkdtempSync, openSync, rmSync } from 'node:fs';
+import { createRequire } from 'node:module';
+import { createServer, type Server, type Socket } from 'node:net';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { Worker } from 'node:worker_threads';
+import type { IPty } from 'node-pty';
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi } from 'vitest';
+import {
+ type PtyHostOutgoingMessage,
+ type PtySpawnOptions,
+ type SpawnPty,
+ setupPtyHost,
+} from '../../src/utility/pty-host.ts';
+
+type Backend = 'bundled-conpty-dll' | 'os-conpty-fallback';
+
+type AttachPlan =
+ | { kind: 'readiness-bound-fires-before-worker' }
+ | { kind: 'worker-cannot-reach-conout' }
+ | { kind: 'connect-throws'; message: string }
+ | { kind: 'attached-then-silent-exit'; shellPid: number; nativeExitCode: number };
+
+interface NativeConptyFake {
+ startProcess(...args: unknown[]): { pty: number; fd: number; conin: string; conout: string };
+ connect(...args: unknown[]): { pid: number };
+ kill(...args: unknown[]): void;
+ resize(...args: unknown[]): void;
+ clear(...args: unknown[]): void;
+}
+
+interface Scenario {
+ backend: Backend;
+ plan: AttachPlan;
+ dir: string;
+ coninPath: string;
+ coninReaderFd: number;
+ conoutPath: string;
+ conoutServer: Server;
+ conoutSockets: Socket[];
+ pseudoconsoles: number;
+ connectCalls: number;
+ nativeExit: ((exitCode: number) => void) | null;
+ terminals: IPty[];
+ nodePtyExit: { pid: number; exitCode: number | undefined } | null;
+}
+
+interface CreateOutcome {
+ nodePtyExit: { pid: number; exitCode: number | undefined } | null;
+ connectCalls: number;
+ forwardedData: string;
+ terminalMessages: PtyHostOutgoingMessage[];
+}
+
+const PTY_ID = 'attach-probe';
+const PWSH = 'C:\\Program Files\\PowerShell\\7\\pwsh.exe';
+const WINDOWS_ENV = {
+ SystemRoot: 'C:\\Windows',
+ ProgramFiles: 'C:\\Program Files',
+ USERPROFILE: 'C:\\Users\\runneradmin',
+ LOCALAPPDATA: 'C:\\Users\\runneradmin\\AppData\\Local',
+ Path: 'C:\\Windows\\System32',
+};
+const ATTACH_OUTCOME_LIVENESS_BOUND_MS = 15_000;
+const POLL_INTERVAL_MS = 10;
+const ENCODING_WARNING = 'Setting encoding on Windows is not supported';
+
+const realSetTimeout = globalThis.setTimeout;
+const requireFromDesktop = createRequire(import.meta.url);
+const nodePtyUtils = requireFromDesktop('node-pty/lib/utils.js') as {
+ loadNativeModule: (name: string) => { dir: string; module: unknown };
+};
+const { WindowsPtyAgent } = requireFromDesktop('node-pty/lib/windowsPtyAgent.js') as {
+ WindowsPtyAgent: { prototype: { _getConsoleProcessList: () => Promise<number[]> } };
+};
+const { WindowsTerminal } = requireFromDesktop('node-pty/lib/windowsTerminal.js') as {
+ WindowsTerminal: new (file: string, args: string[] | string, options: PtySpawnOptions) => IPty;
+};
+const workerThreads = requireFromDesktop('node:worker_threads') as {
+ Worker: typeof Worker;
+};
+
+const RealWorker = workerThreads.Worker;
+const originalLoadNativeModule = nodePtyUtils.loadNativeModule;
+const originalGetConsoleProcessList = WindowsPtyAgent.prototype._getConsoleProcessList;
+const spawnedWorkers: Worker[] = [];
+let active: Scenario | null = null;
+
+function activeScenario(): Scenario {
+ if (active === null) throw new Error('native ConPTY fake called outside a scenario');
+ return active;
+}
+
+const nativeConptyFake: NativeConptyFake = {
+ startProcess(...args) {
+ if (args.length !== 7) {
+ throw new Error(
+ 'Usage: pty.startProcess(file, cols, rows, debug, pipeName, inheritCursor, useConptyDll)',
+ );
+ }
+ const scenario = activeScenario();
+ const useConptyDll = args[6] === true;
+ if (useConptyDll && scenario.backend === 'os-conpty-fallback') {
+ throw new Error(
+ 'Cannot find conpty.dll at D:\\a\\node-pty\\build\\Release\\conpty\\conpty.dll, error code: 2',
+ );
+ }
+ scenario.pseudoconsoles += 1;
+ return {
+ pty: scenario.pseudoconsoles,
+ fd: -1,
+ conin: scenario.coninPath,
+ conout:
+ scenario.plan.kind === 'worker-cannot-reach-conout'
+ ? join(scenario.dir, 'no-conout-listener')
+ : scenario.conoutPath,
+ };
+ },
+ connect(...args) {
+ if (args.length !== 6) {
+ throw new Error('Usage: pty.connect(id, cmdline, cwd, env, useConptyDll, exitCallback)');
+ }
+ const scenario = activeScenario();
+ scenario.connectCalls += 1;
+ const plan = scenario.plan;
+ if (plan.kind === 'connect-throws') throw new Error(plan.message);
+ if (plan.kind !== 'attached-then-silent-exit') {
+ throw new Error(`connect reached under plan ${plan.kind}`);
+ }
+ scenario.nativeExit = args[5] as (exitCode: number) => void;
+ return { pid: plan.shellPid };
+ },
+ kill() {},
+ resize() {},
+ clear() {},
+};
+
+class RecordedWorker extends RealWorker {
+ constructor(...args: ConstructorParameters<typeof RealWorker>) {
+ super(...args);
+ spawnedWorkers.push(this);
+ }
+}
+
+const recordedSignals: Array<{ pid: number; signal: string | number | undefined }> = [];
+
+function refuseRealSignal(pid: number, signal?: string | number): true {
+ recordedSignals.push({ pid, signal });
+ throw new Error('the ConPTY attach suite never sends a real signal');
+}
+
+async function openScenario(backend: Backend, plan: AttachPlan): Promise<Scenario> {
+ const dir = mkdtempSync(join(tmpdir(), 'okcpty-'));
+ const coninPath = join(dir, 'conin');
+ execFileSync('mkfifo', [coninPath]);
+ const coninReaderFd = openSync(coninPath, fsConstants.O_RDONLY | fsConstants.O_NONBLOCK);
+ const conoutPath = join(dir, 'conout');
+ const conoutSockets: Socket[] = [];
+ const conoutServer = createServer((socket) => {
+ socket.on('error', () => {});
+ conoutSockets.push(socket);
+ });
+ await new Promise<void>((resolve) => conoutServer.listen(conoutPath, resolve));
+ return {
+ backend,
+ plan,
+ dir,
+ coninPath,
+ coninReaderFd,
+ conoutPath,
+ conoutServer,
+ conoutSockets,
+ pseudoconsoles: 0,
+ connectCalls: 0,
+ nativeExit: null,
+ terminals: [],
+ nodePtyExit: null,
+ };
+}
+
+async function closeScenario(scenario: Scenario): Promise<void> {
+ await Promise.all(spawnedWorkers.splice(0).map((worker) => worker.terminate()));
+ for (const socket of scenario.conoutSockets) socket.destroy();
+ await new Promise<void>((resolve) => scenario.conoutServer.close(() => resolve()));
+ closeSync(scenario.coninReaderFd);
+ rmSync(scenario.dir, { recursive: true, force: true });
+}
+
+async function waitFor(predicate: () => boolean, what: string): Promise<void> {
+ const deadline = Date.now() + ATTACH_OUTCOME_LIVENESS_BOUND_MS;
+ while (!predicate()) {
+ if (Date.now() >= deadline) {
+ throw new Error(`liveness bound reached waiting for ${what}`);
+ }
+ await new Promise((resolve) => realSetTimeout(resolve, POLL_INTERVAL_MS));
+ }
+}
+
+async function createThroughPtyHost(scenario: Scenario): Promise<CreateOutcome> {
+ const posted: PtyHostOutgoingMessage[] = [];
+ let handler: ((event: { data: unknown }) => void) | null = null;
+ const spawn: SpawnPty = (file, args, options) => {
+ const terminal = new WindowsTerminal(file, args, options);
+ scenario.terminals.push(terminal);
+ terminal.onExit(({ exitCode }) => {
+ scenario.nodePtyExit = { pid: terminal.pid, exitCode };
+ });
+ return terminal;
+ };
+ const host = setupPtyHost({
+ parentPort: {
+ on(_event, h) {
+ handler = h;
+ },
+ postMessage(message) {
+ posted.push(message);
+ },
+ },
+ spawn,
+ env: WINDOWS_ENV,
+ platform: 'win32',
+ shellExists: (path) => path === PWSH,
+ pathProbe: () => null,
+ });
+ const isTerminal = (message: PtyHostOutgoingMessage) =>
+ message.ptyId === PTY_ID && (message.type === 'exit' || message.type === 'spawn-error');
+ handler?.({
+ data: { type: 'create', ptyId: PTY_ID, cwd: scenario.dir, cols: 80, rows: 24 },
+ });
+
+ const plan = scenario.plan;
+ if (plan.kind === 'readiness-bound-fires-before-worker') {
+ expect(vi.getTimerCount(), 'only the ConPTY worker readiness bound is pending').toBe(1);
+ vi.advanceTimersToNextTimer();
+ } else if (plan.kind === 'attached-then-silent-exit') {
+ await waitFor(
+ () => scenario.terminals.at(-1)?.pid === plan.shellPid,
+ 'the shell to attach and report its pid',
+ );
+ scenario.nativeExit?.(plan.nativeExitCode);
+ for (const socket of scenario.conoutSockets) socket.end();
+ }
+ await waitFor(() => posted.some(isTerminal), 'the pty host to report how the session ended');
+ host.killActive();
+
+ return {
+ nodePtyExit: scenario.nodePtyExit,
+ connectCalls: scenario.connectCalls,
+ forwardedData: posted
+ .filter((message) => message.ptyId === PTY_ID && message.type === 'data')
+ .map((message) => (message.type === 'data' ? message.data : ''))
+ .join(''),
+ terminalMessages: posted.filter(isTerminal),
+ };
+}
+
+const BACKENDS: readonly Backend[] = ['bundled-conpty-dll', 'os-conpty-fallback'];
+
+const NEVER_ATTACHED: ReadonlyArray<{
+ name: string;
+ plan: AttachPlan;
+ connectCalls: number;
+ nodePtyExitCode: number;
+}> = [
+ {
+ name: 'the ConPTY output worker is not ready within the node-pty readiness bound',
+ plan: { kind: 'readiness-bound-fires-before-worker' },
+ connectCalls: 0,
+ nodePtyExitCode: -1,
+ },
+ {
+ name: 'the ConPTY output worker fails before it is ready',
+ plan: { kind: 'worker-cannot-reach-conout' },
+ connectCalls: 0,
+ nodePtyExitCode: -1,
+ },
+ {
+ name: 'ConPTY cannot create the shell process',
+ plan: { kind: 'connect-throws', message: 'Cannot create process, error code: 2' },
+ connectCalls: 1,
+ nodePtyExitCode: 2,
+ },
+];
+
+const SILENT_SHELL_PID = 4242;
+
+describe.skipIf(process.platform === 'win32')(
+ 'pty host over the real node-pty Windows terminal: how a session that ends is reported',
+ () => {
+ let signalSeam: ReturnType<typeof vi.spyOn>;
+ let warnSeam: ReturnType<typeof vi.spyOn>;
+ let scenario: Scenario | null = null;
+
+ beforeAll(() => {
+ nodePtyUtils.loadNativeModule = (name) => {
+ if (name !== 'conpty') throw new Error(`unexpected native module ${name}`);
+ return { dir: 'unverified-native-fake', module: nativeConptyFake };
+ };
+ WindowsPtyAgent.prototype._getConsoleProcessList = () => Promise.resolve([]);
+ workerThreads.Worker = RecordedWorker;
+ });
+
+ afterAll(() => {
+ nodePtyUtils.loadNativeModule = originalLoadNativeModule;
+ WindowsPtyAgent.prototype._getConsoleProcessList = originalGetConsoleProcessList;
+ workerThreads.Worker = RealWorker;
+ });
+
+ beforeEach(() => {
+ recordedSignals.length = 0;
+ signalSeam = vi.spyOn(process, 'kill').mockImplementation(refuseRealSignal);
+ const forwardWarn = console.warn.bind(console);
+ warnSeam = vi.spyOn(console, 'warn').mockImplementation((...args: unknown[]) => {
+ if (args[0] !== ENCODING_WARNING) forwardWarn(...args);
+ });
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ });
+
+ afterEach(async () => {
+ vi.useRealTimers();
+ active = null;
+ if (scenario !== null) await closeScenario(scenario);
+ scenario = null;
+ signalSeam.mockRestore();
+ warnSeam.mockRestore();
+ expect(recordedSignals, 'no real signal may leave the suite').toEqual([]);
+ });
+
+ async function run(backend: Backend, plan: AttachPlan): Promise<CreateOutcome> {
+ scenario = await openScenario(backend, plan);
+ active = scenario;
+ return createThroughPtyHost(scenario);
+ }
+
+ describe.each(BACKENDS)('%s', (backend) => {
+ test.each(NEVER_ATTACHED)(
+ 'reports a start failure, not a shell exit, when $name',
+ async ({ plan, connectCalls, nodePtyExitCode }) => {
+ const outcome = await run(backend, plan);
+
+ expect(outcome.connectCalls, 'scenario reached the intended attach step').toBe(
+ connectCalls,
+ );
+ expect(
+ outcome.nodePtyExit,
+ 'node-pty drift: a never-attached Windows pty must still report pid 0 at exit',
+ ).toEqual({ pid: 0, exitCode: nodePtyExitCode });
+ expect(outcome.forwardedData).toBe('');
+ expect(outcome.terminalMessages).toEqual([
+ {
+ type: 'spawn-error',
+ ptyId: PTY_ID,
+ shellNeverAttached: true,
+ exitCode: nodePtyExitCode,
+ },
+ ]);
+ },
+ );
+
+ test('still reports a shell exit when an attached shell exits -1 without output', async () => {
+ const outcome = await run(backend, {
+ kind: 'attached-then-silent-exit',
+ shellPid: SILENT_SHELL_PID,
+ nativeExitCode: -1,
+ });
+
+ expect(outcome.connectCalls, 'scenario reached the intended attach step').toBe(1);
+ expect(
+ outcome.nodePtyExit,
+ 'node-pty drift: an attached Windows pty must report the shell pid at exit',
+ ).toEqual({ pid: SILENT_SHELL_PID, exitCode: -1 });
+ expect(outcome.forwardedData).toBe('');
+ expect(outcome.terminalMessages).toEqual([
+ { type: 'exit', ptyId: PTY_ID, exitCode: -1, signal: null },
+ ]);
+ });
+ });
+ },
+);
diff --git a/packages/desktop/tests/utility/pty-host.test.ts b/packages/desktop/tests/utility/pty-host.test.ts
index 0c9d21f44..69f38e2f4 100644
--- a/packages/desktop/tests/utility/pty-host.test.ts
+++ b/packages/desktop/tests/utility/pty-host.test.ts
@@ -516,6 +516,53 @@ describe('setupPtyHost — exit', () => {
});
});
+describe('setupPtyHost — Windows session that ends before its shell attached', () => {
+ const WINDOWS_HOST = {
+ platform: 'win32',
+ env: { SystemRoot: 'C:\\Windows' },
+ shellExists: () => false,
+ pathProbe: () => null,
+ } as const;
+ const endings = (posted: PtyHostOutgoingMessage[]) =>
+ posted.filter((message) => message.type === 'exit' || message.type === 'spawn-error');
+
+ test('a pty that exits while still reporting pid 0 is reported as never started', () => {
+ const pty = Object.assign(makeFakePty(), { pid: 0 });
+ const h = makeHarness({ pty, ...WINDOWS_HOST });
+ h.fire(CREATE({ ptyId: 'unattached', cwd: 'C:\\project' }));
+ pty.emitExit({ exitCode: -1, signal: undefined });
+
+ expect(endings(h.posted)).toEqual([
+ { type: 'spawn-error', ptyId: 'unattached', shellNeverAttached: true, exitCode: -1 },
+ ]);
+ });
+
+ test('a pty whose shell attached and then exited -1 without output is still a shell exit', () => {
+ const pty = makeFakePty();
+ const h = makeHarness({ pty, ...WINDOWS_HOST });
+ h.fire(CREATE({ ptyId: 'attached', cwd: 'C:\\project' }));
+ pty.emitExit({ exitCode: -1, signal: undefined });
+
+ expect(endings(h.posted)).toEqual([
+ { type: 'exit', ptyId: 'attached', exitCode: -1, signal: null },
+ ]);
+ });
+
+ test('a never-attached pty that ends during shutdown still lets the host exit', () => {
+ const pty = Object.assign(makeFakePty(), { pid: 0 });
+ const exitHost = vi.fn();
+ const h = makeHarness({ pty, exitHost, ...WINDOWS_HOST });
+ h.fire(CREATE({ ptyId: 'unattached', cwd: 'C:\\project' }));
+ h.fire({ type: 'shutdown' });
+ expect(exitHost).not.toHaveBeenCalled();
+
+ pty.emitExit({ exitCode: -1, signal: undefined });
+
+ expect(exitHost).toHaveBeenCalledTimes(1);
+ expect(exitHost).toHaveBeenCalledWith(0);
+ });
+});
+
describe('setupPtyHost — containment (AC5: host survives a PTY failure)', () => {
test.each([
'Cannot find conpty.dll beside conpty.node',