Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Trace Windows PTY startup in the real I/O harness (#5191)
Nick Gomez6ccf845d2b4d
diff --git a/packages/desktop/src/utility/pty-host.ts b/packages/desktop/src/utility/pty-host.tsindex 4b776394f..be0b8f390 100644--- a/packages/desktop/src/utility/pty-host.ts+++ b/packages/desktop/src/utility/pty-host.ts@@ -192,7 +192,116 @@ export function installPtyImportFailureReply(});}+export type PtyStartupBackend = 'bundled' | 'inbox' | 'posix';+export type PtyStartupSnapshotReason =+ | 'failure'+ | 'before-cleanup'+ | 'before-replacement'+ | 'before-kill'+ | 'before-shutdown'+ | 'exit';++export interface PtyStartupNativeSnapshot {+ shell: {+ pid: number | null;+ nativeExitObserved: boolean;+ exitCode: number | null;+ osState: 'unobserved';+ };+ console: {+ backend: PtyStartupBackend;+ connection: 'pending' | 'entered' | 'returned' | 'failed';+ outputConnectionDisposed: boolean;+ osState: 'unobserved';+ };+ worker: {+ threadId: number;+ online: boolean;+ readyReceived: boolean;+ errorObserved: boolean;+ writerError: boolean;+ exitCode: number | null;+ osState: 'unobserved';+ };+ transport: {+ capture: 'installed' | 'missing';+ nativeBytes: number;+ workerSubmittedBytes: number;+ mainBytes: number;+ nativeConnected: boolean;+ forwardingConnected: boolean;+ nativeClosed: boolean;+ forwardingClosed: boolean;+ nativeError: boolean;+ forwardingError: boolean;+ mainDestroyed: boolean;+ mainConnecting: boolean;+ mainReadableLength: number;+ inputWritableLength: number;+ };+}++export type PtyStartupObservation =+ | { stage: 'worker-online' | 'worker-ready-received' | 'data-pipe-connected' | 'worker-error' }+ | { stage: 'native-connect-enter'; boundary: 'agent-complete-connection' }+ | { stage: 'native-connect-return'; shellPid: number | null }+ | { stage: 'native-connect-failed' }+ | { stage: 'native-shell-exit'; shellPid: number | null; exitCode: number }+ | { stage: 'worker-exit'; exitCode: number }+ | { stage: 'observer-unavailable'; reason: 'unsupported-node-pty-shape' };++type PtyStartupHostObservation =+ | PtyStartupObservation+ | { stage: 'lookup-start' }+ | {+ stage: 'lookup-complete';+ lookup: 'probe' | 'cache' | 'override' | 'platform';+ rung: ShellResolutionRung;+ }+ | { stage: 'spawn-start' | 'spawn-return'; backend: PtyStartupBackend }+ | {+ stage: 'spawn-failed';+ backend: PtyStartupBackend;+ reason: 'spawn-error' | 'conpty-dll-unavailable';+ }+ | { stage: 'first-output'; currentSession: boolean }+ | { stage: 'first-forward' }+ | { stage: 'terminal-exit'; exitCode: number | undefined }+ | {+ stage: 'snapshot';+ reason: PtyStartupSnapshotReason;+ receivedBytes: number;+ forwardedBytes: number;+ publicPid: number | null;+ terminalExitObserved: boolean;+ native: PtyStartupNativeSnapshot | null;+ };++export interface PtyStartupSpawnContext {+ traceId: number;+ attempt: number;+ startedAt: number;+ backend: PtyStartupBackend;+ emit(observation: PtyStartupObservation): void;+}++export interface PtyStartupObservedProcess {+ pty: PtyProcessLike;+ snapshot?(): PtyStartupNativeSnapshot;+ dispose?(): void;+}++export interface PtyStartupTraceOptions {+ aroundSpawn?(+ next: () => PtyProcessLike,+ context: PtyStartupSpawnContext,+ ): PtyStartupObservedProcess;+}++let nextStartupTraceId = 0;+export interface SetupPtyHostDeps {+ startupTrace?: PtyStartupTraceOptions;parentPort: PtyHostParentPort | null;spawn: SpawnPty;exitHost?: (code: number) => void;@@ -303,6 +412,7 @@ function asIncomingMessage(raw: unknown): PtyHostIncomingMessage | null {}export interface PtyHostHandle {+ snapshotStartup?(): void;killActive(): void;}@@ -743,6 +853,28 @@ export function setupPtyHost(deps: SetupPtyHostDeps): PtyHostHandle {const env = deps.env ?? (process.env as Record<string, string | undefined>);const platform = deps.platform ?? process.platform;const sessions = new Map<string, PtyProcessLike>();+ const startupTraces = deps.startupTrace+ ? new WeakMap<+ PtyProcessLike,+ {+ emit(+ observation:+ | PtyStartupObservation+ | { stage: 'terminal-exit'; exitCode: number | undefined },+ ): void;+ snapshot(reason: PtyStartupSnapshotReason): void;+ receive(data: string, currentSession: boolean): void;+ forward(data: string): void;+ exited(): void;+ dispose(): void;+ }+ >()+ : undefined;++ function snapshot(pty: PtyProcessLike, reason: PtyStartupSnapshotReason): void {+ startupTraces?.get(pty)?.snapshot(reason);+ }+const cursorSyncGates = new WeakMap<PtyProcessLike, ConptyCursorSyncGate>();const shutdownMs = deps.shutdownMs ?? 1_500;const setHostTimer = deps.setTimer ?? setTimeout;@@ -799,19 +931,52 @@ export function setupPtyHost(deps: SetupPtyHostDeps): PtyHostHandle {const { ptyId } = message;const stale = sessions.get(ptyId);if (stale) {+ snapshot(stale, 'before-replacement');+ startupTraces?.get(stale)?.dispose();safeKill(stale);sessions.delete(ptyId);}+ const traceId = deps.startupTrace ? ++nextStartupTraceId : undefined;+ const startedAt =+ traceId === undefined ? undefined : performance.timeOrigin + performance.now();+ let attempt = 0;+ let sequence = 0;+ let lookup: 'probe' | 'cache' | 'override' | 'platform' = message.shell+ ? 'override'+ : 'platform';+ const emit =+ startedAt === undefined+ ? undefined+ : (observation: PtyStartupHostObservation, observedAttempt = attempt): void => {+ deps.logger?.info?.({+ event: 'pty-host-startup',+ traceId,+ attempt: observedAttempt,+ sequence: ++sequence,+ elapsedMs: performance.timeOrigin + performance.now() - startedAt,+ producer: 'host',+ ...observation,+ });+ };+ emit?.({ stage: 'lookup-start' });const resolution = resolveShellWithDetails(env, {platform,override: message.shell,overrideInvalidReason: message.shellInvalidReason,userInfoShell: deps.userInfoShell,shellExists: deps.shellExists,- pathProbe: platform === 'win32' ? probeWindowsShellPath : deps.pathProbe,+ pathProbe:+ platform === 'win32'+ ? (command, probeEnv) => {+ if (traceId !== undefined)+ lookup = cachedWindowsPaths.has(command) ? 'cache' : 'probe';+ return probeWindowsShellPath(command, probeEnv);+ }+ : deps.pathProbe,listDirectory: deps.listDirectory,logger: deps.logger,});+ emit?.({ stage: 'lookup-complete', lookup, rung: resolution.rung });if (resolution.invalidOverride) {const reason = resolution.invalidOverrideReason ?? 'invalid-value';deps.logger?.warn({@@ -915,9 +1080,39 @@ export function setupPtyHost(deps: SetupPtyHostDeps): PtyHostHandle {env: buildLaunchEnv(platform, shellEnv, launchCommand),encoding: 'utf8',};+ let observation: PtyStartupObservedProcess | undefined;+ const spawnAttempt = (options: PtySpawnOptions): PtyProcessLike => {+ if (traceId === undefined || startedAt === undefined || emit === undefined)+ return deps.spawn(shell, shellArgs, options);+ attempt += 1;+ const backend: PtyStartupBackend =+ platform === 'win32' ? (options.useConptyDll ? 'bundled' : 'inbox') : 'posix';+ emit({ stage: 'spawn-start', backend });+ try {+ const next = () => deps.spawn(shell, shellArgs, options);+ const observedAttempt = attempt;+ observation = deps.startupTrace?.aroundSpawn?.(next, {+ traceId,+ attempt,+ startedAt,+ backend,+ emit: (entry) => emit(entry, observedAttempt),+ }) ?? { pty: next() };+ emit({ stage: 'spawn-return', backend });+ return observation.pty;+ } catch (error) {+ emit({+ stage: 'spawn-failed',+ backend,+ reason:+ conptyDllLoadFailureReason(error) === null ? 'spawn-error' : 'conpty-dll-unavailable',+ });+ throw error;+ }+ };let pty: PtyProcessLike;try {- pty = deps.spawn(shell, shellArgs, {+ pty = spawnAttempt({...spawnOptions,...(platform === 'win32' ? { useConptyDll: true } : {}),});@@ -929,7 +1124,7 @@ export function setupPtyHost(deps: SetupPtyHostDeps): PtyHostHandle {reason: conptyFailureReason,});try {- pty = deps.spawn(shell, shellArgs, { ...spawnOptions, useConptyDll: false });+ pty = spawnAttempt({ ...spawnOptions, useConptyDll: false });} catch (fallbackErr) {const fallbackMessage =fallbackErr instanceof Error ? fallbackErr.message : String(fallbackErr);@@ -950,13 +1145,61 @@ export function setupPtyHost(deps: SetupPtyHostDeps): PtyHostHandle {),);}+ if (emit !== undefined) {+ let receivedBytes = 0;+ let forwardedBytes = 0;+ let terminalExitObserved = false;+ let received = false;+ let forwarded = false;+ startupTraces?.set(pty, {+ emit,+ snapshot(reason) {+ emit({+ stage: 'snapshot',+ reason,+ receivedBytes,+ forwardedBytes,+ publicPid: pty.pid > 0 ? pty.pid : null,+ terminalExitObserved,+ native: observation?.snapshot?.() ?? null,+ });+ },+ receive(data, currentSession) {+ receivedBytes += Buffer.byteLength(data);+ if (!received) {+ received = true;+ emit({ stage: 'first-output', currentSession });+ }+ },+ forward(data) {+ forwardedBytes += Buffer.byteLength(data);+ if (!forwarded) {+ forwarded = true;+ emit({ stage: 'first-forward' });+ }+ },+ exited() {+ terminalExitObserved = true;+ },+ dispose() {+ observation?.dispose?.();+ },+ });+ }sessions.set(ptyId, pty);pty.onData((data) => {+ startupTraces?.get(pty)?.receive(data, sessions.get(ptyId) === pty);if (sessions.get(ptyId) !== pty) return;cursorSyncGates.get(pty)?.observeOutput(data);post({ type: 'data', ptyId, data });+ startupTraces?.get(pty)?.forward(data);});pty.onExit((event) => {+ const trace = startupTraces?.get(pty);+ trace?.exited();+ trace?.emit({ stage: 'terminal-exit', exitCode: event.exitCode });+ trace?.snapshot('exit');+ trace?.dispose();clearKillEscalate(ptyId);if (sessions.get(ptyId) === pty) sessions.delete(ptyId);post(classifyNodePtyEnding(ptyId, pty.pid, event));@@ -982,6 +1225,7 @@ export function setupPtyHost(deps: SetupPtyHostDeps): PtyHostHandle {const pty = sessions.get(message.ptyId);if (!pty) return;const ptyId = message.ptyId;+ snapshot(pty, 'before-kill');safeKill(pty);if (sessions.get(ptyId) !== pty) return;clearKillEscalate(ptyId);@@ -1004,7 +1248,11 @@ export function setupPtyHost(deps: SetupPtyHostDeps): PtyHostHandle {function killActiveSessions(): void {clearAllKillEscalates();- for (const pty of sessions.values()) safeKill(pty);+ for (const pty of sessions.values()) {+ snapshot(pty, 'before-cleanup');+ startupTraces?.get(pty)?.dispose();+ safeKill(pty);+ }sessions.clear();}@@ -1029,7 +1277,11 @@ export function setupPtyHost(deps: SetupPtyHostDeps): PtyHostHandle {if (shuttingDown) return;shuttingDown = true;clearAllKillEscalates();- for (const pty of sessions.values()) safeKill(pty);+ for (const pty of sessions.values()) {+ snapshot(pty, 'before-shutdown');+ startupTraces?.get(pty)?.dispose();+ safeKill(pty);+ }if (sessions.size === 0) {finishShutdown();return;@@ -1079,6 +1331,10 @@ export function setupPtyHost(deps: SetupPtyHostDeps): PtyHostHandle {});return {+ snapshotStartup(): void {+ if (!startupTraces) return;+ for (const pty of sessions.values()) snapshot(pty, 'failure');+ },killActive(): void {killActiveSessions();},diff --git a/packages/desktop/tests/support/pty-readiness.test-helper.ts b/packages/desktop/tests/support/pty-readiness.test-helper.tsindex 3d9551ce5..9adb5aa9d 100644--- a/packages/desktop/tests/support/pty-readiness.test-helper.ts+++ b/packages/desktop/tests/support/pty-readiness.test-helper.ts@@ -1,3 +1,7 @@+import { type SpawnOptions, spawn } from 'node:child_process';+import { closeSync, openSync, readFileSync } from 'node:fs';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';import {type PtyHostIncomingMessage,type PtyHostOutgoingMessage,@@ -5,6 +9,8 @@ import {type SpawnPty,setupPtyHost,} from '../../src/utility/pty-host.ts';+import { windowsPtyStartupTrace } from './pty-startup-trace.test-helper.ts';+import { harnessScenarioTitles } from './real-io-harness-roster.test-helper.ts';export interface PtyStream {read(): string;@@ -17,6 +23,7 @@ export interface PtyHostProbe {dataOf(ptyId: string): string;exitOf(ptyId: string): { exitCode: number | undefined; signal: number | null } | null;errorOf(ptyId: string): string | null;+ snapshotStartup(): void;killActive(): void;}@@ -26,6 +33,9 @@ export interface PtyHostProbeOptions {platform?: NodeJS.Platform;shellExists?: (path: string) => boolean;logger?: SetupPtyHostDeps['logger'];+ startupTrace?:+ | (NonNullable<SetupPtyHostDeps['startupTrace']> & { native?: never })+ | { native: boolean; aroundSpawn?: never };}export function createPtyHostProbe(options: PtyHostProbeOptions): PtyHostProbe {@@ -52,6 +62,7 @@ export function createPtyHostProbe(options: PtyHostProbeOptions): PtyHostProbe {},},spawn: options.spawn,+ startupTrace: options.startupTrace?.native ? windowsPtyStartupTrace : options.startupTrace,env: options.env,...(options.platform === undefined ? {} : { platform: options.platform }),shellExists: options.shellExists,@@ -66,6 +77,7 @@ export function createPtyHostProbe(options: PtyHostProbeOptions): PtyHostProbe {dataOf,exitOf,errorOf,+ snapshotStartup: () => handle.snapshotStartup?.(),killActive: () => handle.killActive(),streamOf: (ptyId) => ({read: () => dataOf(ptyId),@@ -489,3 +501,102 @@ export function buildCwdFileProofCommand(platform: NodeJS.Platform, fileName: st}return `printf 'CWD_PROOF=%s\\n' "$(cat './${fileName}')"`;}++const HARNESS = fileURLToPath(new URL('../utility/pty-host.real-io-harness.ts', import.meta.url));+const TRACE_PRELOAD = new URL('./pty-startup-trace-preload.test-helper.mjs', import.meta.url).href;+const HARNESS_TIMEOUTS = harnessTimeouts(process.platform);+const SUCCESS_RESULT = `HARNESS_RESULT ok=${harnessScenarioTitles(process.platform).length} fail=0 refused=0`;++interface HarnessProcess {+ once(event: 'error', listener: (error: Error) => void): unknown;+ once(event: 'exit', listener: (code: number | null, signal: string | null) => void): unknown;+ kill(): unknown;+ unref(): unknown;+}++export type HarnessSpawn = (file: string, args: string[], options: SpawnOptions) => HarnessProcess;++export async function runHarness(+ outputDir: string,+ extraEnv: Record<string, string> = {},+ spawnChild: HarnessSpawn = spawn,+): Promise<string> {+ const outputPath = join(outputDir, 'output.log');+ const outputFd = openSync(outputPath, 'w');+ const child = (() => {+ try {+ return spawnChild(process.execPath, ['--import', TRACE_PRELOAD, HARNESS], {+ env: {+ ...process.env,+ TEMP: outputDir,+ TMP: outputDir,+ TMPDIR: outputDir,+ ...extraEnv,+ },+ stdio: ['ignore', outputFd, outputFd],+ windowsHide: true,+ });+ } finally {+ closeSync(outputFd);+ }+ })();++ let spawnError = null as Error | null;+ let exitResult = null as { code: number | null; signal: string | null } | null;+ let resolveExit: () => void = () => undefined;+ const exitPromise = new Promise<void>((resolve) => {+ resolveExit = resolve;+ });+ child.once('error', (error) => {+ spawnError = error;+ });+ child.once('exit', (code, signal) => {+ exitResult = { code, signal };+ resolveExit();+ });++ async function terminateChild(): Promise<void> {+ if (exitResult === null) {+ child.kill();+ await Promise.race([exitPromise, sleep(HARNESS_CHILD_KILL_WAIT_MS)]);+ }+ child.unref();+ }++ try {+ const deadline = Date.now() + HARNESS_TIMEOUTS.verdictDeadlineMs;+ while (Date.now() < deadline) {+ const output = readFileSync(outputPath, 'utf8');+ if (spawnError !== null) {+ throw new Error(`real-PTY harness could not start: ${spawnError.message}\n${output}`);+ }++ const completeLines = output.split(/\r?\n/u);+ completeLines.pop();+ const resultLine = completeLines.find((line) => line.startsWith('HARNESS_RESULT '));+ if (resultLine !== undefined) {+ if (resultLine !== SUCCESS_RESULT) {+ throw new Error(`real-PTY harness reported failure:\n${output}`);+ }+ if (exitResult !== null && exitResult.code !== 0) {+ throw new Error(+ `real-PTY harness exited ${exitResult.code ?? exitResult.signal} after success:\n${output}`,+ );+ }+ return output;+ }++ if (exitResult !== null) {+ throw new Error(+ `real-PTY harness exited ${exitResult.code ?? exitResult.signal} without a verdict:\n${output}`,+ );+ }+ await sleep(HARNESS_VERDICT_POLL_INTERVAL_MS);+ }++ const output = readFileSync(outputPath, 'utf8');+ throw new Error(`real-PTY harness timed out without a verdict:\n${output}`);+ } finally {+ await terminateChild();+ }+}diff --git a/packages/desktop/tests/support/pty-readiness.type-tests.ts b/packages/desktop/tests/support/pty-readiness.type-tests.tsnew file mode 100644index 000000000..5ee7344a6--- /dev/null+++ b/packages/desktop/tests/support/pty-readiness.type-tests.ts@@ -0,0 +1,21 @@+import type { PtyStartupTraceOptions } from '../../src/utility/pty-host.ts';+import type { PtyHostProbeOptions } from './pty-readiness.test-helper.ts';++type ProbeStartupTrace = PtyHostProbeOptions['startupTrace'];+declare const aroundSpawn: NonNullable<PtyStartupTraceOptions['aroundSpawn']>;++const _noTrace: ProbeStartupTrace = {};+void _noTrace;+const _nativeOff: ProbeStartupTrace = { native: false };+void _nativeOff;+const _callerHook: ProbeStartupTrace = { aroundSpawn };+void _callerHook;++// @ts-expect-error -- native selects the built-in Windows observer, so a caller aroundSpawn beside it would be silently dropped.+const _nativeWithHook: ProbeStartupTrace = { native: true, aroundSpawn };+void _nativeWithHook;++const _builtElsewhere = { native: true, aroundSpawn };+// @ts-expect-error -- the exclusivity must hold through a widened variable, where excess-property checking does not fire; the `?: never` arms are what reject it.+const _widenedNativeWithHook: ProbeStartupTrace = _builtElsewhere;+void _widenedNativeWithHook;diff --git a/packages/desktop/tests/support/pty-startup-socket-error.test-helper.mjs b/packages/desktop/tests/support/pty-startup-socket-error.test-helper.mjsnew file mode 100644index 000000000..3b6ee5ce3--- /dev/null+++ b/packages/desktop/tests/support/pty-startup-socket-error.test-helper.mjs@@ -0,0 +1,34 @@+import { errorMonitor } from 'node:events';+import net from 'node:net';+import { pathToFileURL } from 'node:url';+import { parentPort, workerData } from 'node:worker_threads';++let nativeSocket;+let forwardingSocket;+const connect = net.Socket.prototype.connect;+net.Socket.prototype.connect = function (...args) {+ if (args[0] === workerData.conoutPipeName) {+ nativeSocket = this;+ net.Socket.prototype.connect = connect;+ }+ return Reflect.apply(connect, this, args);+};+const createServer = net.createServer;+net.createServer = function (listener, ...args) {+ net.createServer = createServer;+ return Reflect.apply(createServer, this, [+ function (socket) {+ forwardingSocket = socket;+ return Reflect.apply(listener, this, [socket]);+ },+ ...args,+ ]);+};+parentPort.on('message', (surface) => {+ const socket = surface === 'native' ? nativeSocket : forwardingSocket;+ socket.once(errorMonitor, () => {+ setImmediate(() => parentPort.postMessage('socket-error-consumed'));+ });+ socket.destroy(new Error('owned output socket failed'));+});+await import(pathToFileURL(workerData.workerFile).href);diff --git a/packages/desktop/tests/support/pty-startup-trace-preload.test-helper.mjs b/packages/desktop/tests/support/pty-startup-trace-preload.test-helper.mjsnew file mode 100644index 000000000..83299a1b2--- /dev/null+++ b/packages/desktop/tests/support/pty-startup-trace-preload.test-helper.mjs@@ -0,0 +1,130 @@+import { errorMonitor } from 'node:events';+import { writeSync } from 'node:fs';+import net from 'node:net';+import { getEnvironmentData, isMainThread, parentPort, workerData } from 'node:worker_threads';++const key = 'ok-pty-startup-worker-trace-v1';+const context = getEnvironmentData(key);+const pipeName = workerData?.conoutPipeName;++if (+ !isMainThread &&+ context?.tag === key &&+ Number.isSafeInteger(context.traceId) &&+ Number.isSafeInteger(context.attempt) &&+ typeof context.startedAt === 'number' &&+ typeof pipeName === 'string' &&+ pipeName.length > 0 &&+ context.counters instanceof SharedArrayBuffer+) {+ const state = new BigInt64Array(context.counters);+ if (state.length >= 11) {+ const nativeBytes = 0;+ const submittedBytes = 1;+ const nativeConnected = 2;+ const forwardingConnected = 3;+ const nativeClosed = 4;+ const forwardingClosed = 5;+ const nativeError = 6;+ const forwardingError = 7;+ const writerError = 8;+ const captureInstalled = 9;+ const persistedRecords = 10;+ const outputFd =+ Number.isSafeInteger(context.outputFd) && context.outputFd >= 0 ? context.outputFd : 1;+ let sequence = 0;+ const base = {+ event: 'pty-host-startup',+ traceId: context.traceId,+ attempt: context.attempt,+ backend: context.backend,+ producer: 'conout-worker',+ };+ const persist = (stage) => {+ sequence += 1;+ try {+ writeSync(+ outputFd,+ `PTY_HOST info ${JSON.stringify({+ ...base,+ stage,+ sequence,+ elapsedMs: performance.timeOrigin + performance.now() - context.startedAt,+ nativeBytes: Number(Atomics.load(state, nativeBytes)),+ workerSubmittedBytes: Number(Atomics.load(state, submittedBytes)),+ })}\n`,+ );+ Atomics.add(state, persistedRecords, 1n);+ Atomics.notify(state, persistedRecords);+ } catch {+ Atomics.store(state, writerError, 1n);+ Atomics.notify(state, writerError);+ }+ };+ Atomics.store(state, captureInstalled, 1n);+ persist('worker-preload-installed');+ if (parentPort) {+ const originalPostMessage = parentPort.postMessage;+ parentPort.postMessage = function (...args) {+ const result = Reflect.apply(originalPostMessage, this, args);+ if (args[0] === 1) {+ parentPort.postMessage = originalPostMessage;+ persist('worker-ready-sent');+ }+ return result;+ };+ }+ const originalConnect = net.Socket.prototype.connect;+ net.Socket.prototype.connect = function (...args) {+ if (args[0] !== pipeName) return Reflect.apply(originalConnect, this, args);+ net.Socket.prototype.connect = originalConnect;+ let firstRead = false;+ const originalPush = this.push;+ this.push = function (chunk, encoding) {+ if (chunk !== null) {+ Atomics.add(state, nativeBytes, BigInt(Buffer.byteLength(chunk, encoding)));+ Atomics.notify(state, nativeBytes);+ if (!firstRead) {+ firstRead = true;+ persist('worker-native-first-read');+ }+ }+ return Reflect.apply(originalPush, this, [chunk, encoding]);+ };+ this.on('connect', () => {+ Atomics.store(state, nativeConnected, 1n);+ persist('worker-native-pipe-connected');+ });+ this.on('close', () => Atomics.store(state, nativeClosed, 1n));+ this.on(errorMonitor, () => Atomics.store(state, nativeError, 1n));+ return Reflect.apply(originalConnect, this, args);+ };++ const originalCreateServer = net.createServer;+ net.createServer = function (...args) {+ net.createServer = originalCreateServer;+ const listener = args[0];+ if (typeof listener !== 'function') return Reflect.apply(originalCreateServer, this, args);+ const observedListener = function (socket) {+ Atomics.store(state, forwardingConnected, 1n);+ persist('worker-forwarding-socket-accepted');+ let firstSubmit = false;+ const originalWrite = socket.write;+ socket.write = function (chunk, ...writeArgs) {+ const result = Reflect.apply(originalWrite, this, [chunk, ...writeArgs]);+ Atomics.add(state, submittedBytes, BigInt(Buffer.byteLength(chunk)));+ Atomics.notify(state, submittedBytes);+ if (!firstSubmit) {+ firstSubmit = true;+ persist('worker-first-submit');+ }+ return result;+ };+ socket.on('close', () => Atomics.store(state, forwardingClosed, 1n));+ socket.on(errorMonitor, () => Atomics.store(state, forwardingError, 1n));+ return Reflect.apply(listener, this, [socket]);+ };+ return Reflect.apply(originalCreateServer, this, [observedListener, ...args.slice(1)]);+ };+ }+}diff --git a/packages/desktop/tests/support/pty-startup-trace-state.test-helper.mjs b/packages/desktop/tests/support/pty-startup-trace-state.test-helper.mjsnew file mode 100644index 000000000..8e3f9ebde--- /dev/null+++ b/packages/desktop/tests/support/pty-startup-trace-state.test-helper.mjs@@ -0,0 +1,10 @@+import net from 'node:net';+import { parentPort } from 'node:worker_threads';++const connect = net.Socket.prototype.connect;+const createServer = net.createServer;+await import('./pty-startup-trace-preload.test-helper.mjs');+parentPort.postMessage({+ connectUnchanged: net.Socket.prototype.connect === connect,+ serverUnchanged: net.createServer === createServer,+});diff --git a/packages/desktop/tests/support/pty-startup-trace.test-helper.ts b/packages/desktop/tests/support/pty-startup-trace.test-helper.tsnew file mode 100644index 000000000..41e0b2183--- /dev/null+++ b/packages/desktop/tests/support/pty-startup-trace.test-helper.ts@@ -0,0 +1,374 @@+import { getEnvironmentData, setEnvironmentData, type Worker } from 'node:worker_threads';+import type {+ PtyStartupNativeSnapshot,+ PtyStartupSpawnContext,+ PtyStartupTraceOptions,+} from '../../src/utility/pty-host.ts';++export const PTY_STARTUP_WORKER_CONTEXT = 'ok-pty-startup-worker-trace-v1';++const NATIVE_BYTES = 0;+const WORKER_SUBMITTED_BYTES = 1;+const NATIVE_CONNECTED = 2;+const FORWARDING_CONNECTED = 3;+const NATIVE_CLOSED = 4;+const FORWARDING_CLOSED = 5;+const NATIVE_ERROR = 6;+const FORWARDING_ERROR = 7;+const WORKER_WRITER_ERROR = 8;+const CAPTURE_INSTALLED = 9;+const COUNTER_LENGTH = 11;++interface WorkerTraceContext {+ tag: 'ok-pty-startup-worker-trace-v1';+ traceId: number;+ attempt: number;+ startedAt: number;+ backend: PtyStartupSpawnContext['backend'];+ counters: SharedArrayBuffer;+ outputFd?: number;+}++interface EventSource {+ on(event: string, listener: (...args: never[]) => void): unknown;+ off(event: string, listener: (...args: never[]) => void): unknown;+ prependListener(event: string, listener: (...args: never[]) => void): unknown;+}++interface SocketState extends EventSource {+ destroyed: boolean;+ connecting: boolean;+ bytesRead: number;+ readableLength: number;+ writableLength: number;+}++interface ConoutState {+ _worker: Worker;+ _isDisposed: boolean;+}++interface AgentState {+ _conoutSocketWorker: ConoutState;+ _outSocket: SocketState;+ _inSocket: SocketState;+ _completePtyConnection: () => unknown;+ _$onProcessExit: (exitCode: number) => unknown;+ _pendingPtyInfo: unknown;+ innerPid: number;+ exitCode: number | undefined;+}++interface TerminalState {+ _agent: AgentState;+}++function isEventSource(value: unknown): value is EventSource {+ if (typeof value !== 'object' || value === null) return false;+ const source = value as Partial<EventSource>;+ return (+ typeof source.on === 'function' &&+ typeof source.off === 'function' &&+ typeof source.prependListener === 'function'+ );+}++function isSocketState(value: unknown): value is SocketState {+ if (!isEventSource(value)) return false;+ const socket = value as Partial<SocketState>;+ return (+ typeof socket.destroyed === 'boolean' &&+ typeof socket.connecting === 'boolean' &&+ typeof socket.bytesRead === 'number' &&+ typeof socket.readableLength === 'number' &&+ typeof socket.writableLength === 'number'+ );+}++function inspectTerminal(value: unknown): TerminalState | null {+ if (typeof value !== 'object' || value === null || !('_agent' in value)) return null;+ const agent = value._agent;+ if (typeof agent !== 'object' || agent === null) return null;+ if (!('_conoutSocketWorker' in agent) || !('_outSocket' in agent) || !('_inSocket' in agent))+ return null;+ if (!isSocketState(agent._outSocket) || !isSocketState(agent._inSocket)) return null;+ const conout = agent._conoutSocketWorker;+ if (typeof conout !== 'object' || conout === null || !('_worker' in conout)) return null;+ const worker = conout._worker;+ if (+ !isEventSource(worker) ||+ !('threadId' in worker) ||+ typeof worker.threadId !== 'number' ||+ !('_isDisposed' in conout) ||+ typeof conout._isDisposed !== 'boolean' ||+ !('_completePtyConnection' in agent) ||+ typeof agent._completePtyConnection !== 'function' ||+ !('_$onProcessExit' in agent) ||+ typeof agent._$onProcessExit !== 'function' ||+ !('_pendingPtyInfo' in agent) ||+ !('innerPid' in agent) ||+ typeof agent.innerPid !== 'number' ||+ ('exitCode' in agent && agent.exitCode !== undefined && typeof agent.exitCode !== 'number')+ )+ return null;+ return value as TerminalState;+}++export function createPtyStartupWorkerContext(+ context: PtyStartupSpawnContext,+ outputFd?: number,+): WorkerTraceContext {+ return {+ tag: 'ok-pty-startup-worker-trace-v1',+ traceId: context.traceId,+ attempt: context.attempt,+ startedAt: context.startedAt,+ backend: context.backend,+ counters: new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT * COUNTER_LENGTH),+ ...(outputFd === undefined ? {} : { outputFd }),+ };+}++export const windowsPtyStartupTrace: PtyStartupTraceOptions = {+ aroundSpawn(next, context) {+ const previous = getEnvironmentData(PTY_STARTUP_WORKER_CONTEXT);+ const workerContext = createPtyStartupWorkerContext(context);+ let pty: ReturnType<typeof next>;+ setEnvironmentData(PTY_STARTUP_WORKER_CONTEXT, workerContext);+ try {+ pty = next();+ } finally {+ setEnvironmentData(PTY_STARTUP_WORKER_CONTEXT, previous);+ }++ const terminal = inspectTerminal(pty);+ if (terminal === null) {+ context.emit({ stage: 'observer-unavailable', reason: 'unsupported-node-pty-shape' });+ return { pty };+ }++ const agent = terminal._agent;+ const conout = agent._conoutSocketWorker;+ const worker = conout._worker;+ const output = agent._outSocket;+ const input = agent._inSocket;+ const counters = new BigInt64Array(workerContext.counters);+ let online = false;+ let readyReceived = false;+ let errorObserved = false;+ let workerExitCode: number | null = null;+ let nativeExitObserved = false;+ let nativeExitCode: number | null = null;+ let connection: PtyStartupNativeSnapshot['console']['connection'] = 'pending';+ let disposed = false;++ const listeners: Array<{+ source: EventSource;+ event: string;+ listener: (...args: never[]) => void;+ }> = [];+ const observe = (+ source: EventSource,+ event: string,+ listener: (...args: never[]) => void,+ prepend = false,+ ) => {+ if (prepend) source.prependListener(event, listener);+ else source.on(event, listener);+ listeners.push({ source, event, listener });+ };++ observe(worker, 'online', () => {+ online = true;+ context.emit({ stage: 'worker-online' });+ });+ observe(+ worker,+ 'message',+ (message: unknown) => {+ if (message !== 1 || readyReceived) return;+ readyReceived = true;+ context.emit({ stage: 'worker-ready-received' });+ },+ true,+ );+ observe(+ worker,+ 'error',+ () => {+ errorObserved = true;+ context.emit({ stage: 'worker-error' });+ },+ true,+ );+ observe(+ worker,+ 'exit',+ (code: number) => {+ workerExitCode = code;+ context.emit({ stage: 'worker-exit', exitCode: code });+ },+ true,+ );+ observe(output, 'connect', () => context.emit({ stage: 'data-pipe-connected' }));++ const complete = agent._completePtyConnection;+ const observedComplete = function (this: AgentState) {+ if (!this._pendingPtyInfo) return Reflect.apply(complete, this, []);+ connection = 'entered';+ context.emit({ stage: 'native-connect-enter', boundary: 'agent-complete-connection' });+ try {+ const result = Reflect.apply(complete, this, []);+ if (this.innerPid > 0 && this.exitCode === undefined) {+ connection = 'returned';+ context.emit({ stage: 'native-connect-return', shellPid: this.innerPid });+ } else {+ connection = 'failed';+ context.emit({ stage: 'native-connect-failed' });+ }+ return result;+ } catch (error) {+ connection = 'failed';+ context.emit({ stage: 'native-connect-failed' });+ throw error;+ }+ };+ agent._completePtyConnection = observedComplete;++ const onProcessExit = agent._$onProcessExit;+ const observedExit = function (this: AgentState, exitCode: number) {+ nativeExitObserved = true;+ nativeExitCode = exitCode;+ context.emit({+ stage: 'native-shell-exit',+ shellPid: this.innerPid > 0 ? this.innerPid : null,+ exitCode,+ });+ return Reflect.apply(onProcessExit, this, [exitCode]);+ };+ agent._$onProcessExit = observedExit;++ return {+ pty,+ snapshot() {+ return {+ shell: {+ pid: agent.innerPid > 0 ? agent.innerPid : null,+ nativeExitObserved,+ exitCode: nativeExitCode,+ osState: 'unobserved',+ },+ console: {+ backend: context.backend,+ connection,+ outputConnectionDisposed: conout._isDisposed,+ osState: 'unobserved',+ },+ worker: {+ threadId: worker.threadId,+ online,+ readyReceived,+ errorObserved,+ writerError: Atomics.load(counters, WORKER_WRITER_ERROR) !== 0n,+ exitCode: workerExitCode,+ osState: 'unobserved',+ },+ transport: {+ capture: Atomics.load(counters, CAPTURE_INSTALLED) !== 0n ? 'installed' : 'missing',+ nativeBytes: Number(Atomics.load(counters, NATIVE_BYTES)),+ workerSubmittedBytes: Number(Atomics.load(counters, WORKER_SUBMITTED_BYTES)),+ mainBytes: output.bytesRead,+ nativeConnected: Atomics.load(counters, NATIVE_CONNECTED) !== 0n,+ forwardingConnected: Atomics.load(counters, FORWARDING_CONNECTED) !== 0n,+ nativeClosed: Atomics.load(counters, NATIVE_CLOSED) !== 0n,+ forwardingClosed: Atomics.load(counters, FORWARDING_CLOSED) !== 0n,+ nativeError: Atomics.load(counters, NATIVE_ERROR) !== 0n,+ forwardingError: Atomics.load(counters, FORWARDING_ERROR) !== 0n,+ mainDestroyed: output.destroyed,+ mainConnecting: output.connecting,+ mainReadableLength: output.readableLength,+ inputWritableLength: input.writableLength,+ },+ } satisfies PtyStartupNativeSnapshot;+ },+ dispose() {+ if (disposed) return;+ disposed = true;+ for (const { source, event, listener } of listeners) source.off(event, listener);+ if (agent._completePtyConnection === observedComplete)+ agent._completePtyConnection = complete;+ if (agent._$onProcessExit === observedExit) agent._$onProcessExit = onProcessExit;+ },+ };+ },+};++interface HarnessScenarioHost {+ snapshot(): void;+ release(): void;+}++interface HarnessScenarioRunnerOptions {+ titles: readonly string[];+ grantMs(before: string): number;+ isRefusal(error: unknown): boolean;+ print(line: string): void;+}++type ScenarioOutcome = 'passed' | 'failed' | 'refused';++export function createHarnessScenarioRunner(options: HarnessScenarioRunnerOptions) {+ const results: Array<{ name: string; outcome: ScenarioOutcome; detail?: string }> = [];+ const unrun = new Set(options.titles);+ const owned: HarnessScenarioHost[] = [];+ let inFlight: string | null = null;++ const tally = (outcome: ScenarioOutcome): number =>+ results.filter((result) => result.outcome === outcome).length;++ const producedNoResult = (): number => unrun.size + (inFlight === null ? 0 : 1);++ const verdictLine = (detail: string): string =>+ `HARNESS_RESULT ok=${tally('passed')} fail=${tally('failed') + producedNoResult()} refused=${tally('refused')}${detail}`;++ return {+ own(host: HarnessScenarioHost): void {+ owned.push(host);+ },+ async run(name: string, fn: (deadlineAt: number) => Promise<void>): Promise<void> {+ if (!unrun.delete(name)) {+ results.push({+ name,+ outcome: 'failed',+ detail: 'not a title the harness roster declares',+ });+ options.print(`FAIL ${name} :: not a title the harness roster declares`);+ return;+ }+ inFlight = name;+ try {+ const deadlineAt = performance.now() + options.grantMs('this scenario started');+ await fn(deadlineAt);+ results.push({ name, outcome: 'passed' });+ options.print(`PASS ${name}`);+ } catch (err) {+ for (const host of owned) host.snapshot();+ const outcome = options.isRefusal(err) ? 'refused' : 'failed';+ results.push({ name, outcome, detail: (err as Error).message });+ options.print(+ `${outcome === 'refused' ? 'REFUSED' : 'FAIL'} ${name} :: ${(err as Error).message}`,+ );+ } finally {+ inFlight = null;+ for (const host of owned.splice(0)) host.release();+ }+ },+ verdictLine,+ hardTimeoutVerdict(): string {+ for (const host of owned) host.snapshot();+ return verdictLine(` :: hard timeout during ${inFlight ?? 'startup'}`);+ },+ unrunTitles: (): string[] => [...unrun],+ passed: (): boolean => tally('failed') === 0 && tally('refused') === 0,+ };+}diff --git a/packages/desktop/tests/utility/pty-host-conpty-attach.test.ts b/packages/desktop/tests/utility/pty-host-conpty-attach.test.tsindex d0d0a8407..1c3278f89 100644--- a/packages/desktop/tests/utility/pty-host-conpty-attach.test.ts+++ b/packages/desktop/tests/utility/pty-host-conpty-attach.test.ts@@ -13,6 +13,7 @@ import {type SpawnPty,setupPtyHost,} from '../../src/utility/pty-host.ts';+import { createPtyHostProbe } from '../support/pty-readiness.test-helper.ts';type Backend = 'bundled-conpty-dll' | 'os-conpty-fallback';@@ -44,6 +45,7 @@ interface Scenario {nativeExit: ((exitCode: number) => void) | null;terminals: IPty[];nodePtyExit: { pid: number; exitCode: number | undefined } | null;+ onNativeConnect?: () => void;}interface CreateOutcome {@@ -123,6 +125,7 @@ const nativeConptyFake: NativeConptyFake = {}const scenario = activeScenario();scenario.connectCalls += 1;+ scenario.onNativeConnect?.();const plan = scenario.plan;if (plan.kind === 'connect-throws') throw new Error(plan.message);if (plan.kind !== 'attached-then-silent-exit') {@@ -197,10 +200,8 @@ async function waitFor(predicate: () => boolean, what: string): Promise<void> {}}-async function createThroughPtyHost(scenario: Scenario): Promise<CreateOutcome> {- const posted: PtyHostOutgoingMessage[] = [];- let handler: ((event: { data: unknown }) => void) | null = null;- const spawn: SpawnPty = (file, args, options) => {+function scenarioSpawn(scenario: Scenario): SpawnPty {+ return (file, args, options) => {const terminal = new WindowsTerminal(file, args, options);scenario.terminals.push(terminal);terminal.onExit(({ exitCode }) => {@@ -208,6 +209,11 @@ async function createThroughPtyHost(scenario: Scenario): Promise<CreateOutcome>});return terminal;};+}++async function createThroughPtyHost(scenario: Scenario): Promise<CreateOutcome> {+ const posted: PtyHostOutgoingMessage[] = [];+ let handler: ((event: { data: unknown }) => void) | null = null;const host = setupPtyHost({parentPort: {on(_event, h) {@@ -217,7 +223,7 @@ async function createThroughPtyHost(scenario: Scenario): Promise<CreateOutcome>posted.push(message);},},- spawn,+ spawn: scenarioSpawn(scenario),env: WINDOWS_ENV,platform: 'win32',shellExists: (path) => path === PWSH,@@ -333,6 +339,68 @@ describe.skipIf(process.platform === 'win32')(return createThroughPtyHost(scenario);}+ async function runTraced(backend: Backend, plan: AttachPlan, observeNativeExit = false) {+ scenario = await openScenario(backend, plan);+ active = scenario;+ const current = scenario;+ const entries: Record<string, unknown>[] = [];+ let atNativeConnect: Record<string, unknown>[] = [];+ let afterNativeExit: Record<string, unknown>[] = [];+ const trace = () => entries.filter((entry) => entry.event === 'pty-host-startup');+ current.onNativeConnect = () => {+ atNativeConnect = trace();+ };+ const options = {+ spawn: scenarioSpawn(current),+ env: WINDOWS_ENV,+ platform: 'win32' as const,+ shellExists: (path: string) => path === PWSH,+ startupTrace: { native: true },+ logger: {+ info: (entry: Record<string, unknown>) => entries.push(entry),+ warn: (entry: Record<string, unknown>) => entries.push(entry),+ },+ };+ const host = createPtyHostProbe(options);+ try {+ host.send({+ type: 'create',+ ptyId: PTY_ID,+ cwd: current.dir,+ cols: 80,+ rows: 24,+ shell: PWSH,+ });+ if (plan.kind === 'readiness-bound-fires-before-worker') vi.advanceTimersToNextTimer();+ if (plan.kind === 'attached-then-silent-exit') {+ await waitFor(+ () => current.terminals.at(-1)?.pid === plan.shellPid,+ 'the traced shell to attach',+ );+ if (observeNativeExit) {+ current.nativeExit?.(plan.nativeExitCode);+ afterNativeExit = trace();+ for (const socket of current.conoutSockets) socket.end();+ await waitFor(() => host.exitOf(PTY_ID) !== null, 'the traced terminal to exit');+ }+ } else {+ await waitFor(+ () => host.errorOf(PTY_ID) !== null,+ 'the traced host to report the connection failure',+ );+ }+ } finally {+ host.killActive();+ }+ return {+ trace: trace(),+ atNativeConnect,+ afterNativeExit,+ connectCalls: current.connectCalls,+ nodePtyExit: current.nodePtyExit,+ };+ }+describe.each(BACKENDS)('%s', (backend) => {test.each(NEVER_ATTACHED)('reports a start failure, not a shell exit, when $name',@@ -375,6 +443,176 @@ describe.skipIf(process.platform === 'win32')({ type: 'exit', ptyId: PTY_ID, exitCode: -1, signal: null },]);});++ test('startup diagnostics preserve READY and connection entry before native connect runs', async () => {+ const outcome = await runTraced(backend, {+ kind: 'attached-then-silent-exit',+ shellPid: SILENT_SHELL_PID,+ nativeExitCode: -1,+ });++ expect(outcome.connectCalls).toBe(1);+ expect(+ outcome.atNativeConnect+ .map((entry) => entry.stage)+ .filter(+ (stage) => stage === 'worker-ready-received' || stage === 'native-connect-enter',+ ),+ ).toEqual(['worker-ready-received', 'native-connect-enter']);+ const connected = outcome.trace.find((entry) => entry.stage === 'native-connect-return');+ expect(connected).toEqual(+ expect.objectContaining({+ traceId: expect.any(Number),+ attempt: expect.any(Number),+ shellPid: SILENT_SHELL_PID,+ }),+ );+ expect(outcome.trace).toContainEqual(+ expect.objectContaining({+ stage: 'snapshot',+ reason: 'before-cleanup',+ publicPid: SILENT_SHELL_PID,+ terminalExitObserved: false,+ receivedBytes: 0,+ forwardedBytes: 0,+ }),+ );+ const snapshot = outcome.trace.find((entry) => entry.stage === 'snapshot');+ expect(snapshot).toEqual(+ expect.objectContaining({+ native: expect.objectContaining({+ shell: {+ pid: SILENT_SHELL_PID,+ nativeExitObserved: false,+ exitCode: null,+ osState: 'unobserved',+ },+ console: expect.objectContaining({+ connection: 'returned',+ outputConnectionDisposed: false,+ osState: 'unobserved',+ }),+ worker: expect.objectContaining({+ online: true,+ readyReceived: true,+ errorObserved: false,+ exitCode: null,+ osState: 'unobserved',+ }),+ transport: expect.objectContaining({+ capture: 'missing',+ nativeBytes: 0,+ workerSubmittedBytes: 0,+ mainBytes: 0,+ }),+ }),+ }),+ );+ const starts = outcome.trace.filter((entry) => entry.stage === 'spawn-start');+ expect(starts.map((entry) => entry.backend)).toEqual(+ backend === 'bundled-conpty-dll' ? ['bundled'] : ['bundled', 'inbox'],+ );+ expect(new Set(starts.map((entry) => entry.traceId)).size).toBe(1);+ expect(new Set(starts.map((entry) => entry.attempt)).size).toBe(starts.length);+ expect(connected).toEqual(+ expect.objectContaining({+ traceId: starts.at(-1)?.traceId,+ attempt: starts.at(-1)?.attempt,+ }),+ );+ expect(outcome.trace.map((entry) => entry.stage)).not.toContain('native-connect-failed');+ });++ test('startup diagnostics preserve a worker error observed before READY', async () => {+ const outcome = await runTraced(backend, { kind: 'worker-cannot-reach-conout' });+ expect(outcome.trace).toContainEqual(expect.objectContaining({ stage: 'worker-error' }));+ expect(outcome.trace).toContainEqual(+ expect.objectContaining({+ stage: 'snapshot',+ native: expect.objectContaining({+ shell: expect.objectContaining({ pid: null, nativeExitObserved: false }),+ console: expect.objectContaining({ connection: 'pending' }),+ worker: expect.objectContaining({ readyReceived: false, errorObserved: true }),+ }),+ }),+ );+ expect(outcome.trace.map((entry) => entry.stage)).not.toContain('native-connect-enter');+ });++ test('startup diagnostics preserve a worker readiness deadline before native creation', async () => {+ const outcome = await runTraced(backend, { kind: 'readiness-bound-fires-before-worker' });+ expect(outcome.trace).toContainEqual(+ expect.objectContaining({+ stage: 'snapshot',+ native: expect.objectContaining({+ shell: expect.objectContaining({ pid: null, nativeExitObserved: false }),+ console: expect.objectContaining({ connection: 'pending' }),+ worker: expect.objectContaining({ readyReceived: false }),+ }),+ }),+ );+ expect(outcome.trace.map((entry) => entry.stage)).not.toContain('native-connect-enter');+ });++ test('startup diagnostics distinguish a caught connection failure from a successful return', async () => {+ const outcome = await runTraced(backend, {+ kind: 'connect-throws',+ message: 'Cannot create process, error code: 2',+ });++ expect(outcome.connectCalls).toBe(1);+ expect(outcome.nodePtyExit).toEqual({ pid: 0, exitCode: 2 });+ expect(+ outcome.trace+ .map((entry) => entry.stage)+ .filter(+ (stage) =>+ stage === 'worker-ready-received' ||+ stage === 'native-connect-enter' ||+ stage === 'native-connect-return' ||+ stage === 'native-connect-failed',+ ),+ ).toEqual(['worker-ready-received', 'native-connect-enter', 'native-connect-failed']);+ expect(outcome.trace.map((entry) => entry.stage)).not.toContain('native-shell-exit');+ expect(outcome.trace).toContainEqual(+ expect.objectContaining({ stage: 'terminal-exit', exitCode: 2 }),+ );+ });++ test('startup diagnostics distinguish native shell exit from later terminal transport closure', async () => {+ const outcome = await runTraced(+ backend,+ {+ kind: 'attached-then-silent-exit',+ shellPid: SILENT_SHELL_PID,+ nativeExitCode: -1,+ },+ true,+ );++ expect(outcome.nodePtyExit).toEqual({ pid: SILENT_SHELL_PID, exitCode: -1 });+ expect(outcome.afterNativeExit).toContainEqual(+ expect.objectContaining({+ stage: 'native-shell-exit',+ shellPid: SILENT_SHELL_PID,+ exitCode: -1,+ }),+ );+ expect(outcome.afterNativeExit.map((entry) => entry.stage)).not.toContain('terminal-exit');+ expect(+ outcome.trace+ .map((entry) => entry.stage)+ .filter((stage) => stage === 'native-shell-exit' || stage === 'terminal-exit'),+ ).toEqual(['native-shell-exit', 'terminal-exit']);+ expect(outcome.trace).toContainEqual(+ expect.objectContaining({+ stage: 'snapshot',+ reason: 'exit',+ publicPid: SILENT_SHELL_PID,+ terminalExitObserved: true,+ }),+ );+ });});},);diff --git a/packages/desktop/tests/utility/pty-host-real-io.test.ts b/packages/desktop/tests/utility/pty-host-real-io.test.tsindex d366f0cd3..1ae3f1a30 100644--- a/packages/desktop/tests/utility/pty-host-real-io.test.ts+++ b/packages/desktop/tests/utility/pty-host-real-io.test.ts@@ -1,111 +1,18 @@-import { spawn } from 'node:child_process';-import { closeSync, mkdtempSync, openSync, readFileSync } from 'node:fs';+import { mkdtempSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { fileURLToPath } from 'node:url';import { describe, expect, test } from 'vitest';import { isTerminalPlatform } from '../../src/shared/terminal-platform.ts';-import {- HARNESS_CHILD_KILL_WAIT_MS,- HARNESS_VERDICT_POLL_INTERVAL_MS,- harnessTimeouts,-} from '../support/pty-readiness.test-helper.ts';+import { harnessTimeouts, runHarness } from '../support/pty-readiness.test-helper.ts';import { harnessScenarioTitles } from '../support/real-io-harness-roster.test-helper.ts';import { removeTempDirBestEffort } from '../support/temp-dir-cleanup.test-helper.ts';-const HARNESS = fileURLToPath(new URL('./pty-host.real-io-harness.ts', import.meta.url));const HARNESS_TIMEOUTS = harnessTimeouts(process.platform);const TERMINAL_PLATFORM = isTerminalPlatform(process.platform);const SCENARIO_COUNT = harnessScenarioTitles(process.platform).length;const SUCCESS_RESULT = `HARNESS_RESULT ok=${SCENARIO_COUNT} fail=0 refused=0`;-const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));--async function runHarness(- outputDir: string,- extraEnv: Record<string, string> = {},-): Promise<string> {- const outputPath = join(outputDir, 'output.log');- const outputFd = openSync(outputPath, 'w');- const child = (() => {- try {- return spawn(process.execPath, [HARNESS], {- env: {- ...process.env,- TEMP: outputDir,- TMP: outputDir,- TMPDIR: outputDir,- ...extraEnv,- },- stdio: ['ignore', outputFd, outputFd],- windowsHide: true,- });- } finally {- closeSync(outputFd);- }- })();-- let spawnError: Error | null = null;- let exitResult: { code: number | null; signal: string | null } | null = null;- let resolveExit: () => void = () => undefined;- const exitPromise = new Promise<void>((resolve) => {- resolveExit = resolve;- });- child.once('error', (error) => {- spawnError = error;- });- child.once('exit', (code, signal) => {- exitResult = { code, signal };- resolveExit();- });-- async function terminateChild(): Promise<void> {- if (exitResult === null) {- child.kill();- await Promise.race([exitPromise, sleep(HARNESS_CHILD_KILL_WAIT_MS)]);- }- child.unref();- }-- try {- const deadline = Date.now() + HARNESS_TIMEOUTS.verdictDeadlineMs;- while (Date.now() < deadline) {- const output = readFileSync(outputPath, 'utf8');- if (spawnError !== null) {- throw new Error(`real-PTY harness could not start: ${spawnError.message}\n${output}`);- }-- const completeLines = output.split(/\r?\n/u);- completeLines.pop();- const resultLine = completeLines.find((line) => line.startsWith('HARNESS_RESULT '));- if (resultLine !== undefined) {- if (resultLine !== SUCCESS_RESULT) {- throw new Error(`real-PTY harness reported failure:\n${output}`);- }- if (exitResult !== null && exitResult.code !== 0) {- throw new Error(- `real-PTY harness exited ${exitResult.code ?? exitResult.signal} after success:\n${output}`,- );- }- return output;- }-- if (exitResult !== null) {- throw new Error(- `real-PTY harness exited ${exitResult.code ?? exitResult.signal} without a verdict:\n${output}`,- );- }- await sleep(HARNESS_VERDICT_POLL_INTERVAL_MS);- }-- const output = readFileSync(outputPath, 'utf8');- throw new Error(`real-PTY harness timed out without a verdict:\n${output}`);- } finally {- await terminateChild();- }-}-describe('PTY host — real shell I/O (Node runtime)', () => {test.skipIf(!TERMINAL_PLATFORM)('real interactive shell round-trips commands, strips env markers, survives a kill, and reports a bad shell',diff --git a/packages/desktop/tests/utility/pty-host-startup-trace.test.ts b/packages/desktop/tests/utility/pty-host-startup-trace.test.tsnew file mode 100644index 000000000..71fae5da3--- /dev/null+++ b/packages/desktop/tests/utility/pty-host-startup-trace.test.ts@@ -0,0 +1,421 @@+import { execFileSync } from 'node:child_process';+import { afterEach, expect, test, vi } from 'vitest';+import {+ type PtyHostIncomingMessage,+ type PtyProcessLike,+ type PtySpawnOptions,+ type PtyStartupSpawnContext,+ type PtyStartupTraceOptions,+ setupPtyHost,+} from '../../src/utility/pty-host.ts';+import { buildInputReadyProbe } from '../smoke/_helpers/terminal-smoke-shell.ts';+import {+ createHarnessBudget,+ createPtyHostProbe,+ HARNESS_REPORT_RESERVE_MS,+ HarnessBudgetRefusal,+ harnessTimeouts,+ waitForEvaluatedInput,+} from '../support/pty-readiness.test-helper.ts';+import { createHarnessScenarioRunner } from '../support/pty-startup-trace.test-helper.ts';++vi.mock('node:child_process', async (importOriginal) => ({+ ...(await importOriginal<typeof import('node:child_process')>()),+ execFileSync: vi.fn(),+}));++const PROLOGUE = '\u001b[1t\u001b[c\u001b[?1004h\u001b[?9001h';+const SHELL = 'C:\\Program Files\\PowerShell\\7\\pwsh.exe';++function fixture(traceEnabled: boolean) {+ const events: Record<string, unknown>[] = [];+ let onData = (_data: string) => {};+ const pty: PtyProcessLike = {+ pid: process.pid,+ onData: (callback) => {+ onData = callback;+ },+ onExit: vi.fn(),+ write: vi.fn(),+ resize: vi.fn(),+ kill: vi.fn(),+ pause: vi.fn(),+ resume: vi.fn(),+ };+ const options = {+ spawn: vi.fn(() => pty),+ env: { SystemRoot: 'C:\\Windows', ProgramFiles: 'C:\\Program Files' },+ platform: 'win32' as const,+ shellExists: (path: string) => path === SHELL,+ logger: {+ info: (entry: Record<string, unknown>) => events.push(entry),+ warn: (entry: Record<string, unknown>) => events.push(entry),+ },+ ...(traceEnabled ? { startupTrace: {} } : {}),+ };+ const host = createPtyHostProbe(options);+ host.send({ type: 'create', ptyId: 'private-session', cwd: 'C:\\private', cols: 80, rows: 24 });+ return { host, pty, events, output: (data: string) => onData(data) };+}++afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+});++test('reports startup boundaries before cleanup when a timed-out lookup precedes prologue-only silence', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] });+ vi.mocked(execFileSync).mockImplementation(() => {+ throw Object.assign(new Error('spawnSync where.exe ETIMEDOUT'), { code: 'ETIMEDOUT' });+ });+ const { host, pty, events, output } = fixture(true);+ output(PROLOGUE);+ const probe = buildInputReadyProbe('win32');+ const pending = waitForEvaluatedInput(+ host.streamOf('private-session'),+ (data) => host.send({ type: 'input', ptyId: 'private-session', data }),+ { input: `${probe.command}\r`, marker: probe.marker },+ 'interactive shell ready at project root',+ { budgetMs: harnessTimeouts('win32').budgetMs },+ ).then(+ () => 'unexpected success',+ (error: Error) => error.message,+ );+ await vi.runAllTimersAsync();+ const failure = await pending;+ host.killActive();+ expect(failure).toContain(+ 'shell never produced output before interactive shell ready at project root',+ );+ expect(pty.write).not.toHaveBeenCalled();+ expect(events).toContainEqual(+ expect.objectContaining({ event: 'pty-host-shell-path-probe-timed-out' }),+ );+ const trace = events.filter((entry) => entry.event === 'pty-host-startup');+ expect(trace.map((entry) => entry.stage)).toEqual([+ 'lookup-start',+ 'lookup-complete',+ 'spawn-start',+ 'spawn-return',+ 'first-output',+ 'first-forward',+ 'snapshot',+ ]);+ expect(trace.at(-1)).toEqual(+ expect.objectContaining({+ reason: 'before-cleanup',+ receivedBytes: Buffer.byteLength(PROLOGUE),+ forwardedBytes: Buffer.byteLength(PROLOGUE),+ publicPid: pty.pid,+ terminalExitObserved: false,+ }),+ );+ expect(JSON.stringify(trace)).not.toMatch(/private-session|private|PowerShell|\\u001b/u);+ expect(pty.kill).toHaveBeenCalledOnce();+});++test('does not capture startup diagnostics unless the caller enables them', () => {+ vi.mocked(execFileSync).mockReturnValue(`${SHELL}\r\n`);+ const { host, events, output } = fixture(false);+ output('private terminal output');+ host.killActive();+ expect(events.filter((entry) => entry.event === 'pty-host-startup')).toEqual([]);+});++function lifecycleFixture(+ options: {+ trace?: boolean;+ fallback?: boolean;+ aroundSpawn?: PtyStartupTraceOptions['aroundSpawn'];+ } = {},+) {+ const events: Record<string, unknown>[] = [];+ const sessions: Array<{+ pty: PtyProcessLike;+ output(data: string): void;+ exit(): void;+ }> = [];+ const controlObservations: Array<{ stage: unknown; reason: unknown }> = [];+ let messageHandler = (_event: { data: unknown }) => {};+ const spawn = vi.fn((_file: string, _args: string | string[], spawnOptions: PtySpawnOptions) => {+ if (options.fallback && spawnOptions.useConptyDll) {+ throw new Error('Cannot find conpty.dll at C:\\fixture\\conpty.dll, error code: 2');+ }+ let onData = (_data: string) => {};+ let onExit = (_event: { exitCode: number }) => {};+ const pty: PtyProcessLike = {+ pid: process.pid + sessions.length,+ onData(callback) {+ onData = callback;+ },+ onExit(callback) {+ onExit = callback;+ },+ write: vi.fn(),+ resize: vi.fn(),+ kill: vi.fn(() => {+ controlObservations.push({ stage: events.at(-1)?.stage, reason: events.at(-1)?.reason });+ }),+ pause: vi.fn(),+ resume: vi.fn(),+ };+ sessions.push({ pty, output: (data) => onData(data), exit: () => onExit({ exitCode: 0 }) });+ return pty;+ });+ const deps = {+ parentPort: {+ on(_event: 'message', callback: (event: { data: unknown }) => void) {+ messageHandler = callback;+ },+ postMessage: vi.fn(),+ },+ spawn,+ env: { SystemRoot: 'C:\\Windows', ProgramFiles: 'C:\\Program Files' },+ platform: 'win32' as const,+ shellExists: (path: string) => path === SHELL,+ logger: {+ warn: (entry: Record<string, unknown>) => events.push(entry),+ info: (entry: Record<string, unknown>) => events.push(entry),+ },+ ...(options.trace === false ? {} : { startupTrace: { aroundSpawn: options.aroundSpawn } }),+ };+ const handle = setupPtyHost(deps);+ const send = (data: PtyHostIncomingMessage) => messageHandler({ data });+ const create = (ptyId: string, shell?: string) =>+ send({+ type: 'create',+ ptyId,+ cwd: 'C:\\private',+ cols: 80,+ rows: 24,+ ...(shell ? { shell } : {}),+ });+ const trace = () => events.filter((entry) => entry.event === 'pty-host-startup');+ return { handle, sessions, create, send, trace, spawn, controlObservations };+}++test('startup traces distinguish cached resolution, overrides, and creates across host instances', () => {+ vi.mocked(execFileSync).mockReset().mockReturnValue(`${SHELL}\r\n`);+ const first = lifecycleFixture();+ const second = lifecycleFixture();+ try {+ first.create('first');+ first.create('cached');+ second.create('override', SHELL);+ const resolutions = [...first.trace(), ...second.trace()].filter(+ (entry) => entry.stage === 'lookup-complete',+ );+ expect(resolutions.map((entry) => entry.lookup)).toEqual(['probe', 'cache', 'override']);+ expect(new Set(resolutions.map((entry) => entry.traceId)).size).toBe(resolutions.length);+ expect(vi.mocked(execFileSync)).toHaveBeenCalledOnce();+ } finally {+ first.handle.killActive();+ second.handle.killActive();+ }+});++test('startup traces give fallback spawns distinct attempts within the same create', () => {+ vi.mocked(execFileSync).mockReturnValue(`${SHELL}\r\n`);+ const host = lifecycleFixture({ fallback: true });+ try {+ host.create('fallback');+ const attempts = host.trace().filter((entry) => entry.stage === 'spawn-start');+ expect(attempts.map((entry) => entry.backend)).toEqual(['bundled', 'inbox']);+ expect(new Set(attempts.map((entry) => entry.attempt)).size).toBe(host.spawn.mock.calls.length);+ expect(new Set(attempts.map((entry) => entry.traceId)).size).toBe(host.sessions.length);+ expect(host.trace()).toContainEqual(+ expect.objectContaining({ stage: 'spawn-failed', reason: 'conpty-dll-unavailable' }),+ );+ } finally {+ host.handle.killActive();+ }+});++test('startup traces keep stale output attached to the replaced session', () => {+ vi.mocked(execFileSync).mockReturnValue(`${SHELL}\r\n`);+ const host = lifecycleFixture();+ try {+ host.create('reused');+ const first = host.sessions.at(-1);+ host.create('reused');+ const second = host.sessions.at(-1);+ first?.output('old terminal contents');+ second?.output('new terminal contents');+ const starts = host.trace().filter((entry) => entry.stage === 'lookup-start');+ const receives = host.trace().filter((entry) => entry.stage === 'first-output');+ const forwards = host.trace().filter((entry) => entry.stage === 'first-forward');+ expect(receives.map((entry) => [entry.traceId, entry.currentSession])).toEqual([+ [starts.at(0)?.traceId, false],+ [starts.at(-1)?.traceId, true],+ ]);+ expect(forwards.map((entry) => entry.traceId)).toEqual([starts.at(-1)?.traceId]);+ expect(host.controlObservations).toContainEqual({+ stage: 'snapshot',+ reason: 'before-replacement',+ });+ } finally {+ host.handle.killActive();+ }+});++test.each([+ ['kill', 'before-kill'],+ ['shutdown', 'before-shutdown'],+] as const)('startup traces snapshot before %s can change owned state', (type, reason) => {+ vi.useFakeTimers();+ vi.mocked(execFileSync).mockReturnValue(`${SHELL}\r\n`);+ const host = lifecycleFixture();+ host.create('controlled');+ host.send(type === 'kill' ? { type, ptyId: 'controlled' } : { type });+ expect(host.controlObservations).toEqual([{ stage: 'snapshot', reason }]);+ host.handle.killActive();+});++test('startup traces distinguish an observed terminal exit from no exit notification', () => {+ vi.mocked(execFileSync).mockReturnValue(`${SHELL}\r\n`);+ const host = lifecycleFixture();+ host.create('exiting');+ host.sessions.at(-1)?.exit();+ expect(host.trace()).toContainEqual(+ expect.objectContaining({ stage: 'terminal-exit', exitCode: 0 }),+ );+ expect(host.trace()).toContainEqual(+ expect.objectContaining({ stage: 'snapshot', reason: 'exit', terminalExitObserved: true }),+ );+ host.handle.killActive();+});++test('startup diagnostics sample no clocks when disabled', () => {+ vi.mocked(execFileSync).mockReturnValue(`${SHELL}\r\n`);+ const now = vi.spyOn(performance, 'now');+ const host = lifecycleFixture({ trace: false });+ host.create('ordinary');+ host.sessions.at(-1)?.output('ordinary data');+ host.handle.killActive();+ expect(now).not.toHaveBeenCalled();+});++test('failure reporting can snapshot an owned session without controlling it', () => {+ vi.mocked(execFileSync).mockReturnValue(`${SHELL}\r\n`);+ const { host, pty, events, output } = fixture(true);+ output(PROLOGUE);+ host.snapshotStartup();+ expect(events.at(-1)).toEqual(+ expect.objectContaining({+ stage: 'snapshot',+ reason: 'failure',+ receivedBytes: Buffer.byteLength(PROLOGUE),+ forwardedBytes: Buffer.byteLength(PROLOGUE),+ }),+ );+ expect(pty.kill).not.toHaveBeenCalled();+ expect(pty.write).not.toHaveBeenCalled();+ host.killActive();+});++test('late observations keep the identity of a failed spawn attempt', () => {+ vi.mocked(execFileSync).mockReturnValue(`${SHELL}\r\n`);+ const contexts: PtyStartupSpawnContext[] = [];+ const host = lifecycleFixture({+ fallback: true,+ aroundSpawn(next, context) {+ contexts.push(context);+ return { pty: next() };+ },+ });+ try {+ host.create('late');+ for (const context of contexts) context.emit({ stage: 'worker-error' });+ const attempts = host.trace().filter((entry) => entry.stage === 'spawn-start');+ const late = host.trace().filter((entry) => entry.stage === 'worker-error');+ expect(late.map((entry) => entry.attempt)).toEqual(attempts.map((entry) => entry.attempt));+ expect(host.spawn.mock.calls.length).toBe(contexts.length);+ const sequence = host.trace().map((entry) => entry.sequence);+ expect(new Set(sequence).size).toBe(sequence.length);+ } finally {+ host.handle.killActive();+ }+});++function harnessScenario(title: string) {+ const lines: string[] = [];+ const sessions: Array<ReturnType<typeof fixture>> = [];+ const budget = createHarnessBudget(harnessTimeouts('win32').budgetMs, HARNESS_REPORT_RESERVE_MS);+ const runner = createHarnessScenarioRunner({+ titles: [title],+ grantMs: (before) => budget.grantMs(before),+ isRefusal: (error) => error instanceof HarnessBudgetRefusal,+ print: (line) => lines.push(line),+ });+ return {+ runner,+ lines,+ openSession() {+ const session = fixture(true);+ runner.own({+ snapshot: () => session.host.snapshotStartup(),+ release: () => session.host.killActive(),+ });+ sessions.push(session);+ return session;+ },+ snapshotReasons: () =>+ sessions.map((session) =>+ session.events+ .filter((entry) => entry.event === 'pty-host-startup' && entry.stage === 'snapshot')+ .map((entry) => entry.reason),+ ),+ releases: () => sessions.map((session) => vi.mocked(session.pty.kill).mock.calls.length),+ };+}++test('a failing harness scenario snapshots its live session before releasing it', async () => {+ vi.mocked(execFileSync).mockReturnValue(`${SHELL}\r\n`);+ const scenario = harnessScenario('shell stays silent');+ await scenario.runner.run('shell stays silent', async () => {+ scenario.openSession().output(PROLOGUE);+ throw new Error('shell never produced output');+ });+ expect(scenario.snapshotReasons()).toEqual([['failure', 'before-cleanup']]);+ expect(scenario.releases()).toEqual([1]);+ expect(scenario.lines).toEqual(['FAIL shell stays silent :: shell never produced output']);+});++test('a hard timeout snapshots the live session of the scenario still in flight', async () => {+ vi.mocked(execFileSync).mockReturnValue(`${SHELL}\r\n`);+ const scenario = harnessScenario('shell still starting');+ let proceed = () => {};+ const blocked = new Promise<void>((resolve) => {+ proceed = resolve;+ });+ let started = () => {};+ const inFlight = new Promise<void>((resolve) => {+ started = resolve;+ });+ const running = scenario.runner.run('shell still starting', async () => {+ scenario.openSession().output(PROLOGUE);+ started();+ await blocked;+ });+ await inFlight;+ const verdict = scenario.runner.hardTimeoutVerdict();+ const atTimeout = scenario.snapshotReasons();+ proceed();+ await running;+ expect(verdict).toBe(+ 'HARNESS_RESULT ok=0 fail=1 refused=0 :: hard timeout during shell still starting',+ );+ expect(atTimeout).toEqual([['failure']]);+ expect(scenario.snapshotReasons()).toEqual([['failure', 'before-cleanup']]);+});++test('a passing harness scenario releases its session without a failure snapshot', async () => {+ vi.mocked(execFileSync).mockReturnValue(`${SHELL}\r\n`);+ const scenario = harnessScenario('shell answers');+ await scenario.runner.run('shell answers', async () => {+ scenario.openSession().output(PROLOGUE);+ });+ expect(scenario.snapshotReasons()).toEqual([['before-cleanup']]);+ expect(scenario.releases()).toEqual([1]);+ expect(scenario.lines).toEqual(['PASS shell answers']);+});diff --git a/packages/desktop/tests/utility/pty-host.real-io-harness.ts b/packages/desktop/tests/utility/pty-host.real-io-harness.tsindex 3134c1d79..7ee4bdd5e 100644--- a/packages/desktop/tests/utility/pty-host.real-io-harness.ts+++ b/packages/desktop/tests/utility/pty-host.real-io-harness.ts@@ -23,6 +23,7 @@ import {waitForEvaluatedInput,waitForShellReady,} from '../support/pty-readiness.test-helper.ts';+import { createHarnessScenarioRunner } from '../support/pty-startup-trace.test-helper.ts';import { harnessScenarioTitles } from '../support/real-io-harness-roster.test-helper.ts';const require = createRequire(import.meta.url);@@ -40,47 +41,26 @@ const hostLogger = {info: (entry: Record<string, unknown>) => console.log(`PTY_HOST info ${JSON.stringify(entry)}`),};+const runner = createHarnessScenarioRunner({+ titles: harnessScenarioTitles(process.platform),+ grantMs: (before) => harnessBudget.grantMs(before),+ isRefusal: (error) => error instanceof HarnessBudgetRefusal,+ print: (line) => console.log(line),+});const createHost = (env: Record<string, string | undefined>,shellExists?: (path: string) => boolean,-): ReturnType<typeof createPtyHostProbe> =>- createPtyHostProbe({ spawn, env, shellExists, logger: hostLogger });--type ScenarioOutcome = 'passed' | 'failed' | 'refused';--const results: Array<{ name: string; outcome: ScenarioOutcome; detail?: string }> = [];-const unrun = new Set(harnessScenarioTitles(process.platform));-let inFlight: string | null = null;-async function scenario(name: string, fn: (deadlineAt: number) => Promise<void>): Promise<void> {- if (!unrun.delete(name)) {- results.push({ name, outcome: 'failed', detail: 'not a title the harness roster declares' });- console.log(`FAIL ${name} :: not a title the harness roster declares`);- return;- }- inFlight = name;- try {- const deadlineAt = performance.now() + harnessBudget.grantMs('this scenario started');- await fn(deadlineAt);- results.push({ name, outcome: 'passed' });- console.log(`PASS ${name}`);- } catch (err) {- const outcome = err instanceof HarnessBudgetRefusal ? 'refused' : 'failed';- results.push({ name, outcome, detail: (err as Error).message });- console.log(- `${outcome === 'refused' ? 'REFUSED' : 'FAIL'} ${name} :: ${(err as Error).message}`,- );- } finally {- inFlight = null;- }-}--const tally = (outcome: ScenarioOutcome): number =>- results.filter((result) => result.outcome === outcome).length;--const producedNoResult = (): number => unrun.size + (inFlight === null ? 0 : 1);--const verdictLine = (detail: string): string =>- `HARNESS_RESULT ok=${tally('passed')} fail=${tally('failed') + producedNoResult()} refused=${tally('refused')}${detail}`;+): ReturnType<typeof createPtyHostProbe> => {+ const host = createPtyHostProbe({+ spawn,+ env,+ shellExists,+ logger: hostLogger,+ startupTrace: { native: process.platform === 'win32' },+ });+ runner.own({ snapshot: () => host.snapshotStartup(), release: () => host.killActive() });+ return host;+};const BASE_ENV = { ...process.env };const shellCommands = terminalSmokeShellCommands();@@ -128,87 +108,79 @@ async function main(): Promise<void> {const tmp = realpathSync(mkdtempSync(join(tmpdir(), 'ok-pty-harness-')));- await scenario('real command round-trip at project root', async (deadlineAt) => {+ await runner.run('real command round-trip at project root', async (deadlineAt) => {const cwdToken = randomUUID();writeFileSync(join(tmp, CWD_PROOF_FILE), cwdToken, 'utf8');const host = createHost(BASE_ENV);const io = host.streamOf('io');- try {- host.send({ type: 'create', ptyId: 'io', cwd: tmp, cols: 80, rows: 24 });- await waitForInteractiveShellReady(- host,- 'io',- 'interactive shell ready at project root',- deadlineAt,- );- host.send({- type: 'input',- ptyId: 'io',- data: `${shellCommands.arithmetic('HARNESS', 6, 7, 'DONE')}\r`,- });- await waitForCondition(- io,- () => io.read().includes('HARNESS_42_DONE'),- 'evaluated command output',- { backstopAt: deadlineAt },- );- host.send({- type: 'input',- ptyId: 'io',- data: `${buildCwdFileProofCommand(process.platform, CWD_PROOF_FILE)}\r`,- });- await waitForCondition(- io,- () => io.read().includes(`CWD_PROOF=${cwdToken}`),- 'relative sentinel read at project root',- { backstopAt: deadlineAt },- );- } finally {- host.killActive();- }+ host.send({ type: 'create', ptyId: 'io', cwd: tmp, cols: 80, rows: 24 });+ await waitForInteractiveShellReady(+ host,+ 'io',+ 'interactive shell ready at project root',+ deadlineAt,+ );+ host.send({+ type: 'input',+ ptyId: 'io',+ data: `${shellCommands.arithmetic('HARNESS', 6, 7, 'DONE')}\r`,+ });+ await waitForCondition(+ io,+ () => io.read().includes('HARNESS_42_DONE'),+ 'evaluated command output',+ { backstopAt: deadlineAt },+ );+ host.send({+ type: 'input',+ ptyId: 'io',+ data: `${buildCwdFileProofCommand(process.platform, CWD_PROOF_FILE)}\r`,+ });+ await waitForCondition(+ io,+ () => io.read().includes(`CWD_PROOF=${cwdToken}`),+ 'relative sentinel read at project root',+ { backstopAt: deadlineAt },+ );});- await scenario('strips desktop env markers from the shell', async (deadlineAt) => {+ await runner.run('strips desktop env markers from the shell', async (deadlineAt) => {const host = createHost({...BASE_ENV,OK_ELECTRON_PROTOCOL_HOST: '1',OK_LOCK_KIND: 'interactive',});const env = host.streamOf('env');- try {- host.send({ type: 'create', ptyId: 'env', cwd: tmp, cols: 80, rows: 24 });- await waitForInteractiveShellReady(- host,- 'env',- 'interactive shell ready with desktop markers stripped',- deadlineAt,- );- host.send({- type: 'input',- ptyId: 'env',- data: `${shellCommands.readEnvironment('OK_LOCK_KIND', 'LOCK')}\r`,- });- host.send({- type: 'input',- ptyId: 'env',- data: `${shellCommands.readEnvironment('OK_ELECTRON_PROTOCOL_HOST', 'HOST')}\r`,- });- await waitForCondition(- env,- () => env.read().includes('LOCK=[]') && env.read().includes('HOST=[]'),- 'empty markers in shell',- { backstopAt: deadlineAt },- );- if (env.read().includes('LOCK=[interactive]')) {- throw new Error('OK_LOCK_KIND leaked into the shell');- }- } finally {- host.killActive();+ host.send({ type: 'create', ptyId: 'env', cwd: tmp, cols: 80, rows: 24 });+ await waitForInteractiveShellReady(+ host,+ 'env',+ 'interactive shell ready with desktop markers stripped',+ deadlineAt,+ );+ host.send({+ type: 'input',+ ptyId: 'env',+ data: `${shellCommands.readEnvironment('OK_LOCK_KIND', 'LOCK')}\r`,+ });+ host.send({+ type: 'input',+ ptyId: 'env',+ data: `${shellCommands.readEnvironment('OK_ELECTRON_PROTOCOL_HOST', 'HOST')}\r`,+ });+ await waitForCondition(+ env,+ () => env.read().includes('LOCK=[]') && env.read().includes('HOST=[]'),+ 'empty markers in shell',+ { backstopAt: deadlineAt },+ );+ if (env.read().includes('LOCK=[interactive]')) {+ throw new Error('OK_LOCK_KIND leaked into the shell');}});if (process.platform === 'win32') {- await scenario('PowerShell executes a structured launch command', async (deadlineAt) => {+ await runner.run('PowerShell executes a structured launch command', async (deadlineAt) => {const powershell = join(process.env.SystemRoot ?? 'C:\\Windows','System32',@@ -224,41 +196,37 @@ async function main(): Promise<void> {OK_HARNESS_LAUNCH_TOKEN: launchToken,});const launch = host.streamOf('launch');- try {- host.send({- type: 'create',- ptyId: 'launch',- cwd: tmp,- cols: 80,- rows: 24,- shell: powershell,- launchCommand: {- executable: 'cmd.exe',- args: ['/d', '/c', 'echo', '%OK_HARNESS_LAUNCH_TOKEN%'],- },- });- await waitForCondition(- launch,- () => launch.read().includes(launchToken),- 'PowerShell EncodedCommand output',- harnessWindowsLaunchWait(deadlineAt),- );- await waitForWindowsInputReady(- host,- 'launch',- 'PowerShell remains interactive after EncodedCommand',- deadlineAt,- );- if (host.errorOf('launch') !== null) {- throw new Error(`PowerShell launch failed: ${host.errorOf('launch')}`);- }- } finally {- host.killActive();+ host.send({+ type: 'create',+ ptyId: 'launch',+ cwd: tmp,+ cols: 80,+ rows: 24,+ shell: powershell,+ launchCommand: {+ executable: 'cmd.exe',+ args: ['/d', '/c', 'echo', '%OK_HARNESS_LAUNCH_TOKEN%'],+ },+ });+ await waitForCondition(+ launch,+ () => launch.read().includes(launchToken),+ 'PowerShell EncodedCommand output',+ harnessWindowsLaunchWait(deadlineAt),+ );+ await waitForWindowsInputReady(+ host,+ 'launch',+ 'PowerShell remains interactive after EncodedCommand',+ deadlineAt,+ );+ if (host.errorOf('launch') !== null) {+ throw new Error(`PowerShell launch failed: ${host.errorOf('launch')}`);}});}- await scenario('host survives a PTY death and respawns', async (deadlineAt) => {+ await runner.run('host survives a PTY death and respawns', async (deadlineAt) => {const host = createHost(BASE_ENV);const first = host.streamOf('c1');const second = host.streamOf('c2');@@ -280,10 +248,9 @@ async function main(): Promise<void> {'second shell prompt (host survived)',{ backstopAt: deadlineAt },);- host.killActive();});- await scenario('bad shell surfaces as a spawn failure', async (deadlineAt) => {+ await runner.run('bad shell surfaces as a spawn failure', async (deadlineAt) => {const badShell = join(tmp,process.platform === 'win32' ? 'no-such-shell-xyz.exe' : 'no-such-shell-xyz',@@ -308,24 +275,24 @@ async function main(): Promise<void> {if (exit && exit.exitCode === 0 && exit.signal === null) {throw new Error('expected a non-zero/failed exit for a bad shell');}- host.killActive();});- if (unrun.size > 0) {- console.log(verdictLine(` :: never ran ${[...unrun].join(', ')}`));+ const unrun = runner.unrunTitles();+ if (unrun.length > 0) {+ console.log(runner.verdictLine(` :: never ran ${unrun.join(', ')}`));process.exit(1);}- console.log(verdictLine(''));- process.exit(tally('failed') === 0 && tally('refused') === 0 ? 0 : 1);+ console.log(runner.verdictLine(''));+ process.exit(runner.passed() ? 0 : 1);}const hardTimeout = setTimeout(() => {- console.log(verdictLine(` :: hard timeout during ${inFlight ?? 'startup'}`));+ console.log(runner.hardTimeoutVerdict());process.exit(1);}, HARNESS_BUDGET_MS);hardTimeout.unref();void main().catch((err) => {- console.log(verdictLine(` :: ${(err as Error).message}`));+ console.log(runner.verdictLine(` :: ${(err as Error).message}`));process.exit(1);});diff --git a/packages/desktop/tests/utility/pty-startup-observer.test.ts b/packages/desktop/tests/utility/pty-startup-observer.test.tsnew file mode 100644index 000000000..2345e8565--- /dev/null+++ b/packages/desktop/tests/utility/pty-startup-observer.test.ts@@ -0,0 +1,70 @@+import { getEnvironmentData, setEnvironmentData } from 'node:worker_threads';+import { expect, test, vi } from 'vitest';+import type {+ PtyProcessLike,+ PtyStartupObservation,+ PtyStartupSpawnContext,+} from '../../src/utility/pty-host.ts';+import {+ PTY_STARTUP_WORKER_CONTEXT,+ windowsPtyStartupTrace,+} from '../support/pty-startup-trace.test-helper.ts';++function context(): PtyStartupSpawnContext & { observations: PtyStartupObservation[] } {+ const observations: PtyStartupObservation[] = [];+ return {+ traceId: process.pid,+ attempt: process.pid,+ backend: 'bundled',+ startedAt: performance.timeOrigin + performance.now(),+ emit: (entry) => observations.push(entry),+ observations,+ };+}++const pty: PtyProcessLike = {+ pid: process.pid,+ onData: vi.fn(),+ onExit: vi.fn(),+ write: vi.fn(),+ resize: vi.fn(),+ kill: vi.fn(),+ pause: vi.fn(),+ resume: vi.fn(),+};++test('observer scopes each spawn context and restores the previous context after a throw', () => {+ const previous = getEnvironmentData(PTY_STARTUP_WORKER_CONTEXT);+ const outer = { owner: 'outer-fixture' };+ const observation = context();+ const error = new Error('fixture spawn failure');+ setEnvironmentData(PTY_STARTUP_WORKER_CONTEXT, outer);+ try {+ const next = vi.fn(() => {+ expect(getEnvironmentData(PTY_STARTUP_WORKER_CONTEXT)).toEqual(+ expect.objectContaining({ traceId: observation.traceId, attempt: observation.attempt }),+ );+ throw error;+ });+ expect(() => windowsPtyStartupTrace.aroundSpawn?.(next, observation)).toThrow(error);+ expect(next).toHaveBeenCalledOnce();+ expect(getEnvironmentData(PTY_STARTUP_WORKER_CONTEXT)).toBe(outer);+ } finally {+ setEnvironmentData(PTY_STARTUP_WORKER_CONTEXT, previous);+ }+});++test('an unsupported native object reports missing observation without substituting a process or snapshot', () => {+ const observation = context();+ const next = vi.fn(() => pty);+ const previous = getEnvironmentData(PTY_STARTUP_WORKER_CONTEXT);+ const result = windowsPtyStartupTrace.aroundSpawn?.(next, observation);+ expect(next).toHaveBeenCalledOnce();+ expect(result?.pty).toBe(pty);+ expect(result?.snapshot).toBeUndefined();+ expect(observation.observations).toEqual([+ { stage: 'observer-unavailable', reason: 'unsupported-node-pty-shape' },+ ]);+ expect(getEnvironmentData(PTY_STARTUP_WORKER_CONTEXT)).toBe(previous);+ expect(pty.kill).not.toHaveBeenCalled();+});diff --git a/packages/desktop/tests/utility/pty-startup-worker-trace.test.ts b/packages/desktop/tests/utility/pty-startup-worker-trace.test.tsnew file mode 100644index 000000000..065604b11--- /dev/null+++ b/packages/desktop/tests/utility/pty-startup-worker-trace.test.ts@@ -0,0 +1,487 @@+import { randomUUID } from 'node:crypto';+import { EventEmitter, once } from 'node:events';+import { closeSync, mkdtempSync, openSync, readFileSync, rmSync, writeSync } from 'node:fs';+import { createRequire } from 'node:module';+import { connect, createServer, type Server, type Socket } from 'node:net';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { getEnvironmentData, setEnvironmentData, Worker } from 'node:worker_threads';+import { describe, expect, test, vi } from 'vitest';+import {+ createPtyHostProbe,+ type HarnessSpawn,+ harnessTimeouts,+ runHarness,+} from '../support/pty-readiness.test-helper.ts';+import {+ createPtyStartupWorkerContext,+ PTY_STARTUP_WORKER_CONTEXT,+} from '../support/pty-startup-trace.test-helper.ts';+import { removeTempDirBestEffort } from '../support/temp-dir-cleanup.test-helper.ts';++const requireFromDesktop = createRequire(new URL('../../package.json', import.meta.url));+const workerFile = join(+ dirname(requireFromDesktop.resolve('node-pty')),+ 'worker/conoutSocketWorker.js',+);+const preload = new URL('../support/pty-startup-trace-preload.test-helper.mjs', import.meta.url)+ .href;+const harnessFile = fileURLToPath(new URL('./pty-host.real-io-harness.ts', import.meta.url));+const PERSISTED_RECORDS = 10;+const HARNESS_TIMEOUTS = harnessTimeouts(process.platform);+const NATIVE_BYTES = 0;+const SUBMITTED_BYTES = 1;+const WRITER_ERROR = 8;+const CAPTURE_INSTALLED = 9;+const NATIVE_ERROR = 6;+const FORWARDING_ERROR = 7;++interface WorkerFixture {+ worker: Worker;+ native: Socket;+ forwarded: Socket;+ pipe: string;+ server: Server;+ dir: string;+ close(): Promise<void>;+}++async function openWorkerFixture(+ withPreload: boolean,+ socketErrorSeam = false,+): Promise<WorkerFixture> {+ const dir = mkdtempSync(join(tmpdir(), 'ok-pty-worker-trace-'));+ const pipe =+ process.platform === 'win32'+ ? `\\\\.\\pipe\\ok-pty-worker-trace-${randomUUID()}`+ : join(dir, 'native');+ const server = createServer();+ let worker: Worker | undefined;+ let native: Socket | undefined;+ let forwarded: Socket | undefined;+ try {+ server.listen(pipe);+ await once(server, 'listening');+ worker = new Worker(+ socketErrorSeam+ ? new URL('../support/pty-startup-socket-error.test-helper.mjs', import.meta.url)+ : workerFile,+ {+ workerData: { conoutPipeName: pipe, workerFile },+ execArgv: withPreload ? ['--import', preload] : [],+ },+ );+ const [[accepted], [message]] = await Promise.all([+ (once(server, 'connection') as Promise<[Socket]>).then((result) => {+ native = result[0];+ return result;+ }),+ Promise.race([+ once(worker, 'message'),+ once(worker, 'exit').then(([code]) => {+ throw new Error(`ConPTY worker exited before READY: ${code}`);+ }),+ ]),+ ]);+ native = accepted;+ expect(message).toBe(1);+ forwarded = connect(`${pipe}-worker`);+ await once(forwarded, 'connect');+ return {+ worker,+ native,+ forwarded,+ pipe,+ server,+ dir,+ async close() {+ forwarded.destroy();+ native.destroy();+ await worker.terminate();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ rmSync(dir, { recursive: true, force: true });+ },+ };+ } catch (error) {+ forwarded?.destroy();+ native?.destroy();+ if (worker) await worker.terminate();+ if (server.listening) await new Promise<void>((resolve) => server.close(() => resolve()));+ rmSync(dir, { recursive: true, force: true });+ throw error;+ }+}++async function receiveExact(socket: Socket, expected: Buffer, send: () => void): Promise<void> {+ const received = new Promise<Buffer>((resolve, reject) => {+ const chunks: Buffer[] = [];+ const onData = (chunk: Buffer) => {+ chunks.push(chunk);+ if (Buffer.concat(chunks).length < expected.length) return;+ socket.off('data', onData);+ socket.off('error', reject);+ resolve(Buffer.concat(chunks));+ };+ socket.on('data', onData);+ socket.once('error', reject);+ });+ send();+ expect(await received).toEqual(expected);+}++async function waitForCount(state: BigInt64Array, index: number, count: bigint): Promise<void> {+ while (true) {+ const observed = Atomics.load(state, index);+ if (observed >= count) return;+ const result = await Atomics.waitAsync(+ state,+ index,+ observed,+ HARNESS_TIMEOUTS.verdictDeadlineMs,+ ).value;+ if (result === 'timed-out') throw new Error('ConPTY worker diagnostic count did not advance');+ }+}++async function waitForRecord(output: string, state: BigInt64Array, stage: string): Promise<void> {+ while (true) {+ const observed = Atomics.load(state, PERSISTED_RECORDS);+ const records = readFileSync(output, 'utf8')+ .split('\n')+ .filter((line) => line.startsWith('PTY_HOST info '))+ .map((line) => JSON.parse(line.slice('PTY_HOST info '.length)) as { stage: string });+ if (records.some((record) => record.stage === stage)) return;+ const result = await Atomics.waitAsync(+ state,+ PERSISTED_RECORDS,+ observed,+ HARNESS_TIMEOUTS.verdictDeadlineMs,+ ).value;+ if (result === 'timed-out')+ throw new Error(`ConPTY worker milestone did not persist: ${stage}`);+ }+}++function traceContext(outputFd?: number) {+ return createPtyStartupWorkerContext(+ {+ traceId: 17,+ attempt: 2,+ startedAt: performance.timeOrigin + performance.now(),+ backend: 'bundled',+ emit() {},+ },+ outputFd,+ );+}++async function withWorkerContext<T>(value: unknown, run: () => Promise<T>): Promise<T> {+ const previous = getEnvironmentData(PTY_STARTUP_WORKER_CONTEXT);+ setEnvironmentData(PTY_STARTUP_WORKER_CONTEXT, value);+ try {+ return await run();+ } finally {+ setEnvironmentData(PTY_STARTUP_WORKER_CONTEXT, previous);+ }+}++describe('startup trace on the installed ConPTY output worker', () => {+ test.each([false, true])(+ 'preserves pre-READY native connection failure with preload %s',+ async (withPreload) => {+ const dir = mkdtempSync(join(tmpdir(), 'ok-pty-worker-missing-'));+ const pipe =+ process.platform === 'win32'+ ? `\\\\.\\pipe\\ok-pty-worker-missing-${randomUUID()}`+ : join(dir, 'missing');+ const context = traceContext();+ let worker: Worker | undefined;+ try {+ await withWorkerContext(context, async () => {+ worker = new Worker(workerFile, {+ workerData: { conoutPipeName: pipe },+ execArgv: withPreload ? ['--import', preload] : [],+ });+ const errors: Error[] = [];+ const messages: unknown[] = [];+ worker.on('error', (error) => errors.push(error));+ worker.on('message', (message) => messages.push(message));+ const exitCode = await new Promise<number>((resolve) => worker.once('exit', resolve));+ expect(errors).toHaveLength(1);+ expect(errors[0]).toMatchObject({ code: 'ENOENT' });+ expect(exitCode).toBe(1);+ expect(messages).toEqual([]);+ expect(Atomics.load(new BigInt64Array(context.counters), NATIVE_ERROR)).toBe(+ withPreload ? 1n : 0n,+ );+ });+ } finally {+ if (worker) await worker.terminate();+ rmSync(dir, { recursive: true, force: true });+ }+ },+ );++ test.each([+ { surface: 'native', counter: NATIVE_ERROR, withPreload: false },+ { surface: 'native', counter: NATIVE_ERROR, withPreload: true },+ { surface: 'forwarding', counter: FORWARDING_ERROR, withPreload: false },+ { surface: 'forwarding', counter: FORWARDING_ERROR, withPreload: true },+ ])(+ 'preserves $surface transport failure with preload $withPreload',+ async ({ surface, counter, withPreload }) => {+ const context = traceContext();+ let fixture: WorkerFixture | undefined;+ try {+ await withWorkerContext(context, async () => {+ fixture = await openWorkerFixture(withPreload, true);+ });+ const payload = Buffer.from('output-error-control');+ await receiveExact(fixture.forwarded, payload, () => fixture.native.write(payload));+ const worker = fixture.worker;+ const exited = new Promise<number>((resolve) => worker.once('exit', resolve));+ const outcome = new Promise<unknown>((resolve) => {+ worker.once('error', (error) => resolve({ kind: 'error', message: error.message }));+ worker.once('message', (message) => resolve({ kind: 'message', message }));+ });+ worker.postMessage(surface);+ expect(await outcome).toEqual({ kind: 'error', message: 'owned output socket failed' });+ expect(await exited).toBe(1);+ expect(Atomics.load(new BigInt64Array(context.counters), counter)).toBe(+ withPreload ? 1n : 0n,+ );+ } finally {+ await fixture?.close();+ }+ },+ );++ test('counts raw native bytes and submitted worker bytes across split multibyte input', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'ok-pty-worker-log-'));+ const output = join(dir, 'trace.log');+ const fd = openSync(output, 'w');+ const context = traceContext(fd);+ let fixture: WorkerFixture | undefined;+ try {+ await withWorkerContext(context, async () => {+ fixture = await openWorkerFixture(true);+ });+ const bytes = Buffer.from('AλB語C');+ const state = new BigInt64Array(context.counters);+ expect(Atomics.load(state, CAPTURE_INSTALLED)).toBe(1n);+ const received = receiveExact(fixture.forwarded, bytes, () =>+ fixture.native.write(bytes.subarray(0, 2)),+ );+ await waitForCount(state, NATIVE_BYTES, 2n);+ fixture.native.write(bytes.subarray(2, 5));+ await waitForCount(state, NATIVE_BYTES, 5n);+ fixture.native.write(bytes.subarray(5));+ await received;+ await waitForCount(state, SUBMITTED_BYTES, BigInt(bytes.length));+ await waitForRecord(output, state, 'worker-first-submit');+ expect(Number(Atomics.load(state, NATIVE_BYTES))).toBe(bytes.length);+ expect(Number(Atomics.load(state, SUBMITTED_BYTES))).toBe(bytes.length);+ const malformed = Buffer.from([0xff, 0x58]);+ const reencoded = Buffer.from('�X');+ await receiveExact(fixture.forwarded, reencoded, () => fixture.native.write(malformed));+ await waitForCount(state, NATIVE_BYTES, BigInt(bytes.length + malformed.length));+ await waitForCount(state, SUBMITTED_BYTES, BigInt(bytes.length + reencoded.length));+ expect(Number(Atomics.load(state, NATIVE_BYTES))).toBe(bytes.length + malformed.length);+ expect(Number(Atomics.load(state, SUBMITTED_BYTES))).toBe(bytes.length + reencoded.length);+ expect(Atomics.load(state, CAPTURE_INSTALLED)).toBe(1n);+ expect(Atomics.load(state, WRITER_ERROR)).toBe(0n);+ const records = readFileSync(output, 'utf8');+ expect(records).toContain('"stage":"worker-ready-sent"');+ expect(records).toContain('"stage":"worker-native-first-read"');+ expect(records).toContain('"stage":"worker-first-submit"');+ expect(records).not.toContain('AλB語C');+ expect(records).not.toContain(fixture.pipe);+ const events = records+ .split('\n')+ .filter((line) => line.startsWith('PTY_HOST info '))+ .map(+ (line) =>+ JSON.parse(line.slice('PTY_HOST info '.length)) as {+ traceId: number;+ attempt: number;+ producer: string;+ stage: string;+ sequence: number;+ },+ );+ for (const entry of events) {+ expect(entry.traceId).toBe(context.traceId);+ expect(entry.attempt).toBe(context.attempt);+ expect(entry.producer).toBe('conout-worker');+ }+ expect(new Set(events.map((entry) => entry.stage)).size).toBe(events.length);+ expect(events.map((entry) => entry.sequence)).toEqual(+ events.map((_entry, index) => index + 1),+ );+ } finally {+ await fixture?.close();+ closeSync(fd);+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('keeps transport functional without preload while the diagnostic count stays absent', async () => {+ const context = traceContext();+ let fixture: WorkerFixture | undefined;+ try {+ await withWorkerContext(context, async () => {+ fixture = await openWorkerFixture(false);+ });+ const payload = Buffer.from('worker-control-λ');+ await receiveExact(fixture.forwarded, payload, () => fixture.native.write(payload));+ const state = new BigInt64Array(context.counters);+ expect(Atomics.load(state, CAPTURE_INSTALLED)).toBe(0n);+ expect(Atomics.load(state, NATIVE_BYTES)).toBe(0n);+ expect(Atomics.load(state, SUBMITTED_BYTES)).toBe(0n);+ } finally {+ await fixture?.close();+ }+ });++ test('leaves a worker without trace context uninstrumented', async () => {+ let fixture: WorkerFixture | undefined;+ let identityWorker: Worker | undefined;+ try {+ await withWorkerContext(undefined, async () => {+ fixture = await openWorkerFixture(true);+ });+ const payload = Buffer.from('worker-without-context');+ await receiveExact(fixture.forwarded, payload, () => fixture.native.write(payload));+ await withWorkerContext(undefined, async () => {+ identityWorker = new Worker(+ new URL('../support/pty-startup-trace-state.test-helper.mjs', import.meta.url),+ { workerData: { conoutPipeName: fixture.pipe }, execArgv: [] },+ );+ });+ expect((await once(identityWorker, 'message'))[0]).toEqual({+ connectUnchanged: true,+ serverUnchanged: true,+ });+ } finally {+ if (identityWorker) await identityWorker.terminate();+ await fixture?.close();+ }+ });++ test('persists a worker milestone to a regular file while the main event loop is blocked', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'ok-pty-worker-blocked-'));+ const output = join(dir, 'trace.log');+ const fd = openSync(output, 'w');+ const context = traceContext(fd);+ const state = new BigInt64Array(context.counters);+ let worker: Worker | undefined;+ try {+ await withWorkerContext(context, async () => {+ worker = new Worker(workerFile, {+ workerData: { conoutPipeName: join(dir, 'unreachable-native') },+ execArgv: ['--import', preload],+ });+ worker.once('error', () => undefined);+ });+ const result = Atomics.wait(state, PERSISTED_RECORDS, 0n, HARNESS_TIMEOUTS.verdictDeadlineMs);+ expect(result).not.toBe('timed-out');+ expect(readFileSync(output, 'utf8')).toContain('"stage":"worker-preload-installed"');+ } finally {+ if (worker) await worker.terminate();+ closeSync(fd);+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('marks direct-file failure without changing worker transport', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'ok-pty-worker-readonly-'));+ const output = join(dir, 'trace.log');+ const fd = openSync(output, 'w');+ closeSync(fd);+ const readonlyFd = openSync(output, 'r');+ const context = traceContext(readonlyFd);+ let fixture: WorkerFixture | undefined;+ try {+ await withWorkerContext(context, async () => {+ fixture = await openWorkerFixture(true);+ });+ const payload = Buffer.from('read-only-log-λ');+ await receiveExact(fixture.forwarded, payload, () => fixture.native.write(payload));+ const state = new BigInt64Array(context.counters);+ await waitForCount(state, SUBMITTED_BYTES, BigInt(payload.length));+ expect(Atomics.load(state, CAPTURE_INSTALLED)).toBe(1n);+ expect(Atomics.load(state, WRITER_ERROR)).toBe(1n);+ expect(readFileSync(output, 'utf8')).toBe('');+ } finally {+ await fixture?.close();+ closeSync(readonlyFd);+ rmSync(dir, { recursive: true, force: true });+ }+ });+});++describe('startup trace wrapper', () => {+ test('launches the harness with its worker preload and retains diagnostic records on failure', async () => {+ const outputDir = mkdtempSync(join(tmpdir(), 'ok-pty-trace-wrapper-'));+ const emitter = new EventEmitter();+ const child = Object.assign(emitter, {+ kill: vi.fn(() => emitter.emit('exit', 0, null)),+ unref: vi.fn(),+ });+ const spawnChild = vi.fn<HarnessSpawn>((_file, _args, options) => {+ const fd = Array.isArray(options.stdio) ? options.stdio.at(1) : undefined;+ if (typeof fd !== 'number')+ throw new Error('fixture requires the actual output file descriptor');+ const host = createPtyHostProbe({+ spawn: () => {+ throw new Error('fixture shell did not start');+ },+ platform: 'darwin',+ env: { SHELL: '/fixture-shell' },+ shellExists: () => true,+ startupTrace: {},+ logger: {+ warn: (entry) => writeSync(fd, `PTY_HOST warn ${JSON.stringify(entry)}\n`),+ info: (entry) => writeSync(fd, `PTY_HOST info ${JSON.stringify(entry)}\n`),+ },+ });+ host.send({ type: 'create', ptyId: 'wrapper-fixture', cwd: outputDir, cols: 80, rows: 24 });+ writeSync(+ fd,+ `FAIL fixture :: ${host.errorOf('wrapper-fixture')}\nHARNESS_RESULT ok=0 fail=1 refused=0\n`,+ );+ host.killActive();+ return child;+ });+ try {+ const failure = await runHarness(outputDir, {}, spawnChild).then(+ () => 'unexpected success',+ (error: Error) => error.message,+ );+ expect(failure).toContain('real-PTY harness reported failure:');+ expect(failure).toContain('FAIL fixture :: fixture shell did not start');+ const trace = failure+ .split('\n')+ .filter((line) => line.startsWith('PTY_HOST info '))+ .map((line) => JSON.parse(line.slice('PTY_HOST info '.length)))+ .filter((entry) => entry.event === 'pty-host-startup');+ expect(trace.map((entry) => entry.stage)).toEqual([+ 'lookup-start',+ 'lookup-complete',+ 'spawn-start',+ 'spawn-failed',+ ]);+ expect(JSON.stringify(trace)).not.toContain('wrapper-fixture');+ expect(JSON.stringify(trace)).not.toContain(outputDir);+ expect(spawnChild.mock.calls.at(0)?.slice(0, 2)).toEqual([+ process.execPath,+ ['--import', preload, harnessFile],+ ]);+ expect(child.kill).toHaveBeenCalledOnce();+ expect(child.unref).toHaveBeenCalledOnce();+ } finally {+ removeTempDirBestEffort(outputDir);+ }+ });+});