Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Name the pty ending when the packaged Windows echo smoke fails (#4934)
Nick Gomez90ef743c07f4
diff --git a/knip.config.ts b/knip.config.tsindex 8b615429f..6a38348d8 100644--- a/knip.config.ts+++ b/knip.config.ts@@ -143,15 +143,11 @@ export default {'packages/server': {entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],project: 'src/**',- ignoreDependencies: [- '@types/shell-quote',- ],+ ignoreDependencies: ['@types/shell-quote'],},'packages/cli': {entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],- ignoreDependencies: [- 'yjs',- ],+ ignoreDependencies: ['yjs'],},'packages/desktop': {entry: [diff --git a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts b/packages/app/tests/integration/bug3-source-mode-writeback.test.tsindex a28cc2b18..8a60e5826 100644--- a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts+++ b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts@@ -1,4 +1,3 @@-import { readFileSync } from 'node:fs';import { join } from 'node:path';import { setTimeout as wait } from 'node:timers/promises';diff --git a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts b/packages/app/tests/integration/indented-jsx-byte-sacred.test.tsindex 4fc2c11f9..6fcdc23f2 100644--- a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts+++ b/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts@@ -1,4 +1,3 @@-import { setTimeout as wait } from 'node:timers/promises';import { normalizeBridge } from '@inkeep/open-knowledge-core';import { updateYFragment } from '@tiptap/y-tiptap';diff --git a/packages/app/tests/integration/interior-edit-freshness.test.ts b/packages/app/tests/integration/interior-edit-freshness.test.tsindex 9f2f6feb6..40b5cdfd6 100644--- a/packages/app/tests/integration/interior-edit-freshness.test.ts+++ b/packages/app/tests/integration/interior-edit-freshness.test.ts@@ -1,4 +1,3 @@-import { setTimeout as wait } from 'node:timers/promises';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';import { afterAll, beforeAll, describe, expect, test } from 'vitest';diff --git a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts b/packages/app/tests/integration/keystroke-cadence-danger-space.test.tsindex 2a085742b..93666af70 100644--- a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts+++ b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts@@ -1,4 +1,3 @@-import { setTimeout as wait } from 'node:timers/promises';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';import { afterAll, beforeAll, describe, expect, test } from 'vitest';diff --git a/packages/app/tests/integration/producer-guard-wiring.test.ts b/packages/app/tests/integration/producer-guard-wiring.test.tsindex 878d5196b..867598d34 100644--- a/packages/app/tests/integration/producer-guard-wiring.test.ts+++ b/packages/app/tests/integration/producer-guard-wiring.test.ts@@ -1,4 +1,3 @@-import { setTimeout as wait } from 'node:timers/promises';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';import { afterAll, beforeAll, describe, expect, test } from 'vitest';diff --git a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.tsindex 4ada3cf26..0970ac12f 100644--- a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts+++ b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts@@ -1,4 +1,3 @@-import { randomUUID } from 'node:crypto';import { afterEach, describe, expect, test } from 'vitest';import { agentWriteMd, createTestServer, type TestServer } from './test-harness';diff --git a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts b/packages/app/tests/integration/qa-045-restore-after-gc.test.tsindex cbe2b705f..b632185e1 100644--- a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts+++ b/packages/app/tests/integration/qa-045-restore-after-gc.test.ts@@ -1,4 +1,3 @@-import { execFileSync } from 'node:child_process';import { randomUUID } from 'node:crypto';import { join } from 'node:path';diff --git a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.tsindex 89bc9b4d9..c530ce4ba 100644--- a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts+++ b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts@@ -1,4 +1,3 @@-import { randomUUID } from 'node:crypto';import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest';import type * as Y from 'yjs';diff --git a/packages/app/tests/integration/undo-after-rollback.test.ts b/packages/app/tests/integration/undo-after-rollback.test.tsindex a78aeb0e4..d3767adc9 100644--- a/packages/app/tests/integration/undo-after-rollback.test.ts+++ b/packages/app/tests/integration/undo-after-rollback.test.ts@@ -1,4 +1,3 @@-import { ROLLBACK_ORIGIN } from '@inkeep/open-knowledge-server';import { afterAll, beforeAll, describe, expect, test } from 'vitest';import * as Y from 'yjs';diff --git a/packages/app/tests/integration/undo-recycle-reset.test.ts b/packages/app/tests/integration/undo-recycle-reset.test.tsindex e7cc69c3f..b076f955c 100644--- a/packages/app/tests/integration/undo-recycle-reset.test.ts+++ b/packages/app/tests/integration/undo-recycle-reset.test.ts@@ -1,4 +1,3 @@-import { writeFileSync } from 'node:fs';import { join } from 'node:path';import { setTimeout as wait } from 'node:timers/promises';diff --git a/packages/app/tests/integration/undo-rederive-survival.test.ts b/packages/app/tests/integration/undo-rederive-survival.test.tsindex 9ddcd0730..7935e35f8 100644--- a/packages/app/tests/integration/undo-rederive-survival.test.ts+++ b/packages/app/tests/integration/undo-rederive-survival.test.ts@@ -1,4 +1,3 @@-import { prependFrontmatter } from '@inkeep/open-knowledge-core';import { Plugin, PluginKey } from '@tiptap/pm/state';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.tsindex 2a597ec3d..f4cc8a286 100644--- a/packages/core/src/bridge/compose.ts+++ b/packages/core/src/bridge/compose.ts@@ -1,4 +1,3 @@-import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.tsindex 01ef76a9f..8fb428b90 100644--- a/packages/core/src/bridge/doc-boundary-space.ts+++ b/packages/core/src/bridge/doc-boundary-space.ts@@ -1,4 +1,3 @@-import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.tsindex fb0ba5a7c..fc267cbea 100644--- a/packages/core/src/markdown/comment-promoter.ts+++ b/packages/core/src/markdown/comment-promoter.ts@@ -1,4 +1,3 @@-import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.tsindex fa3cfcd86..bfd7e3109 100644--- a/packages/core/src/markdown/merged-walker.ts+++ b/packages/core/src/markdown/merged-walker.ts@@ -1,4 +1,3 @@-import type { Nodes, Parent, Root } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.tsindex 8be632ba4..4d3250d3a 100644--- a/packages/core/src/markdown/safe-url.ts+++ b/packages/core/src/markdown/safe-url.ts@@ -1,4 +1,3 @@-export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');diff --git a/packages/desktop/scripts/smoke-terminal-package-cdp.py b/packages/desktop/scripts/smoke-terminal-package-cdp.pyindex 52f52fed8..c2a14dafd 100755--- a/packages/desktop/scripts/smoke-terminal-package-cdp.py+++ b/packages/desktop/scripts/smoke-terminal-package-cdp.py@@ -235,10 +235,12 @@ def evaluate_pty_echo(socket_url: str) -> Dict[str, object]:let output = '';let ptyId = null;let settled = false;- let unsubscribe = () => {{}};let createdAt = null;let firstByteAt = null;let markerAt = null;+ const endings = [];+ const notices = [];+ const releases = [];const sinceStart = (at) => (at === null ? null : Math.round(at - startedAt));const timings = () => ({{createdMs: sinceStart(createdAt),@@ -249,10 +251,10 @@ def evaluate_pty_echo(socket_url: str) -> Dict[str, object]:if (settled) return;settled = true;clearTimeout(timeout);- unsubscribe();+ for (const release of releases) release();if (ptyId !== null) await bridge.terminal.kill(ptyId).catch(() => {{}});if (error) reject(error);- else resolve({{ output, platform: bridge.platform, timings: timings() }});+ else resolve({{ output, platform: bridge.platform, timings: timings(), endings, notices }});}};const consume = (data, at) => {{if (firstByteAt === null) firstByteAt = at;@@ -280,15 +282,26 @@ def evaluate_pty_echo(socket_url: str) -> Dict[str, object]:() =>void finish(new Error(- `PTY echo timed out; output=${{JSON.stringify(output)}}; timings=${{JSON.stringify(timings())}}`,+ `PTY echo timed out; output=${{JSON.stringify(output)}}; timings=${{JSON.stringify(timings())}}; endings=${{JSON.stringify(endings)}}; notices=${{JSON.stringify(notices)}}`,),),{renderer_echo_timeout_ms()},);- unsubscribe = bridge.terminal.onData((message) => {{- if (message.ptyId !== ptyId) return;- consume(message.data, performance.now());- }});+ try {{+ releases.push(bridge.terminal.onData((message) => {{+ if (message.ptyId !== ptyId) return;+ consume(message.data, performance.now());+ }}));+ releases.push(bridge.terminal.onExit((message) => {{+ endings.push({{ ...message, atMs: sinceStart(performance.now()) }});+ }}));+ releases.push(bridge.terminal.onNotice((message) => {{+ notices.push({{ ...message, atMs: sinceStart(performance.now()) }});+ }}));+ }} catch (error) {{+ await finish(error);+ return;+ }}const isWindows = bridge.platform === 'win32';const created = await bridge.terminal.create({{cols: 80,@@ -355,7 +368,10 @@ def main() -> int:file=sys.stderr,)return 1- print(f"PTY echo marker observed: {MARKER}; timings={json.dumps(result.get('timings'))}")+ print(+ f"PTY echo marker observed: {MARKER}; timings={json.dumps(result.get('timings'))}; "+ f"endings={json.dumps(result.get('endings'))}; notices={json.dumps(result.get('notices'))}"+ )return 0diff --git a/packages/desktop/scripts/smoke-windows-terminal-package.mjs b/packages/desktop/scripts/smoke-windows-terminal-package.mjsindex 9513a4ef3..5459320d4 100644--- a/packages/desktop/scripts/smoke-windows-terminal-package.mjs+++ b/packages/desktop/scripts/smoke-windows-terminal-package.mjs@@ -11,13 +11,14 @@ import {rmSync,writeFileSync,} from 'node:fs';-import { tmpdir } from 'node:os';+import { homedir, tmpdir } from 'node:os';import { dirname, join, resolve } from 'node:path';import { fileURLToPath, pathToFileURL } from 'node:url';import {SPAWN_STARTUP_DEADLINE_MS,SPAWN_WAIT_EXTENSION_FACTOR,} from '../src/shared/boot-narration.ts';+import { readBootLog } from '../tests/smoke/_helpers/launch-readiness.ts';export const PACKAGED_BOOT_ENVELOPE_MS = 10_000;export const PACKAGED_PTY_ECHO_BUDGET_MS = 30_000;@@ -90,6 +91,10 @@ export function windowsPtyDriverEnv(env = process.env) {};}+export function windowsPackageAppEnv(env = process.env) {+ return { ...env, OK_DESKTOP_E2E_SMOKE: '1', OK_LOG_LEVEL: 'info' };+}+export function seedWindowsPtySmokeProject(rootDir, shellPath) {const projectDir = join(rootDir, 'project');const userDataDir = join(rootDir, 'user-data');@@ -115,6 +120,40 @@ function printAppLog(logPath) {if (tail.trim() !== '') console.error(`Packaged app log (tail):\n${tail}`);}+const TERMINAL_LOG_SUBSYSTEMS = new Set(['terminal', 'pty-host']);+const TERMINAL_LOG_TAIL_LINES = 200;++function isTerminalRecordSince(line, launchedAt) {+ let record;+ try {+ record = JSON.parse(line);+ } catch {+ return false;+ }+ return TERMINAL_LOG_SUBSYSTEMS.has(record?.subsystem) && Date.parse(record.time) >= launchedAt;+}++export function readTerminalSubsystemLog(launchedAt, home = homedir()) {+ const log = readBootLog(home);+ if (log.unreadableReason !== undefined) {+ return `Could not list the app log directory at ${log.dir} (${log.unreadableReason}), so what the terminal subsystem wrote is unavailable.`;+ }+ if (!log.exists) {+ return `No desktop log in ${log.dir}, so the packaged app never opened the log its terminal subsystem writes to.`;+ }+ const since = new Date(launchedAt).toISOString();+ const missing =+ log.unreadableFiles.length === 0+ ? ''+ : `\nCould not read ${log.unreadableFiles.join(', ')} in ${log.dir}, so any terminal record written there since ${since} is missing.`;+ const kept = log.lines.filter((line) => isTerminalRecordSince(line, launchedAt));+ if (kept.length === 0) {+ return `No terminal or pty-host record written since ${since} in any desktop log under ${log.dir}, so the packaged app logged nothing about the subsystem this smoke drives.${missing}`;+ }+ const tail = kept.slice(-TERMINAL_LOG_TAIL_LINES);+ return `Packaged app terminal log (${tail.length} of ${kept.length} records written since ${since} in ${log.dir}):\n${tail.join('\n')}${missing}`;+}+export function runWindowsPackageTerminalSmoke({packageDir = defaultPackageDir,platform = process.platform,@@ -135,12 +174,13 @@ export function runWindowsPackageTerminalSmoke({const logPath = join(smokeRoot, 'openknowledge.log');const { projectDir, userDataDir } = seedWindowsPtySmokeProject(smokeRoot, shellPath);const logFd = openSync(logPath, 'w');+ const launchedAt = Date.now();let app = null;try {app = spawn(executable, windowsPackageLaunchArgs(projectDir, userDataDir), {cwd: resolvedPackageDir,- env: { ...env, OK_DESKTOP_E2E_SMOKE: '1' },+ env: windowsPackageAppEnv(env),stdio: ['ignore', logFd, logFd],windowsHide: true,});@@ -162,6 +202,7 @@ export function runWindowsPackageTerminalSmoke({} catch (error) {closeSync(logFd);printAppLog(logPath);+ console.error(readTerminalSubsystemLog(launchedAt));throw error;} finally {if (app?.pid) {diff --git a/packages/desktop/scripts/smoke-windows-terminal-package.test.mjs b/packages/desktop/scripts/smoke-windows-terminal-package.test.mjsindex f4b6dd3cb..d836a5cf1 100644--- a/packages/desktop/scripts/smoke-windows-terminal-package.test.mjs+++ b/packages/desktop/scripts/smoke-windows-terminal-package.test.mjs@@ -1,9 +1,21 @@import { execFileSync } from 'node:child_process';-import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';-import { tmpdir } from 'node:os';+import { once } from 'node:events';+import {+ constants,+ copyFileSync,+ existsSync,+ mkdirSync,+ mkdtempSync,+ readdirSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from 'node:fs';+import { homedir, tmpdir } from 'node:os';import { dirname, join } from 'node:path';import { fileURLToPath, pathToFileURL } from 'node:url';-import { afterEach, describe, expect, test } from 'vitest';+import pino from 'pino';+import { afterEach, describe, expect, test, vi } from 'vitest';import {SPAWN_STARTUP_DEADLINE_MS,SPAWN_WAIT_EXTENSION_FACTOR,@@ -20,6 +32,7 @@ import {packagedStartupBoundMs,runWindowsPackageTerminalSmoke,seedWindowsPtySmokeProject,+ windowsPackageAppEnv,windowsPackageLaunchArgs,windowsPtyDriverEnv,} from './smoke-windows-terminal-package.mjs';@@ -166,29 +179,55 @@ function ptyEchoSnippet() {return run.output;}+const STUB_PTY_ID = '5f1c2a70-3b6e-4d2f-9a11-7c0e5d8b4321';+const OTHER_PTY_ID = '0c4a9e18-77d5-4a63-8f20-1b93e6c5a7d4';+const STUB_EXIT_CODE = 3;+function stubRenderer({ duringStart = [] } = {}) {- const listeners = [];- const emit = (data) => {- for (const listener of listeners) listener({ ptyId: 7, data });+ const channels = { data: [], exit: [], notice: [] };+ const subscribed = { data: 0, exit: 0, notice: 0 };+ let subscribedAtCreate = null;+ const subscribe = (channel) => (listener) => {+ channels[channel].push(listener);+ subscribed[channel] += 1;+ return () => {+ const at = channels[channel].indexOf(listener);+ if (at !== -1) channels[channel].splice(at, 1);+ };+ };+ const deliver = (channel, payload) => {+ for (const listener of channels[channel].slice()) listener(payload);+ };+ const dispatch = (step) => {+ if (typeof step === 'string') return deliver('data', { ptyId: STUB_PTY_ID, data: step });+ if (step.exit !== undefined) return deliver('exit', step.exit);+ return deliver('notice', step.notice);};return {+ subscriptionAudit: () => ({+ subscribed: { ...subscribed },+ subscribedAtCreate,+ active: {+ data: channels.data.length,+ exit: channels.exit.length,+ notice: channels.notice.length,+ },+ }),okDesktop: {config: { ptyAvailable: true },platform: 'win32',terminal: {- onData(listener) {- listeners.push(listener);- return () => {- listeners.length = 0;- };- },+ onData: subscribe('data'),+ onExit: subscribe('exit'),+ onNotice: subscribe('notice'),async create() {- return { ok: true, ptyId: 7 };+ subscribedAtCreate = { ...subscribed };+ return { ok: true, ptyId: STUB_PTY_ID };},async start() {- for (const chunk of duringStart) {+ for (const step of duringStart) {await new Promise((resolve) => setTimeout(resolve, 5));- emit(chunk);+ dispatch(step);}return { ok: true };},@@ -202,9 +241,100 @@ function runPtyEchoSnippet(window) {return new Function('window', `return (\n${ptyEchoSnippet()}\n);`)(window);}+function rejectionOf(pending) {+ return pending.then(+ (value) => {+ throw new Error(+ `the renderer expression resolved instead of timing out: ${JSON.stringify(value)}`,+ );+ },+ (reason) => reason,+ );+}++function timeoutFields(message) {+ const parsed =+ /^PTY echo timed out; output=("(?:[^"\\]|\\.)*"); timings=(\{.*?\}); endings=(\[.*\]); notices=(\[.*\])$/.exec(+ message,+ );+ if (parsed === null) {+ throw new Error(+ `the PTY echo timeout error named no ending: it must carry output, timings, endings and notices in that order, and it read ${message}`,+ );+ }+ return {+ output: JSON.parse(parsed[1]),+ timings: JSON.parse(parsed[2]),+ endings: JSON.parse(parsed[3]),+ notices: JSON.parse(parsed[4]),+ };+}++async function timedOutWith(duringStart) {+ const reason = await rejectionOf(runPtyEchoSnippet(stubRenderer({ duringStart })));+ return timeoutFields(reason.message);+}++async function terminalSubsystemLogReader() {+ const module = await import(pathToFileURL(harnessPath).href);+ expect(+ typeof module.readTerminalSubsystemLog,+ 'the packaged Windows smoke must export a reader for the log the terminal subsystem actually writes, so a failing run can print it',+ ).toBe('function');+ return module.readTerminalSubsystemLog;+}++async function terminalSubsystemLogReaderOverNewestFirstListing() {+ vi.resetModules();+ vi.doMock('node:fs', async (importOriginal) => {+ const fs = await importOriginal();+ return {+ ...fs,+ readdirSync: (...args) =>+ fs+ .readdirSync(...args)+ .sort()+ .reverse(),+ };+ });+ try {+ return await terminalSubsystemLogReader();+ } finally {+ vi.doUnmock('node:fs');+ vi.resetModules();+ }+}++const NEWER_LOG = 'desktop.2026-09-24.log';+const OLDER_LOG = 'desktop.2026-09-23.log';+const UNREADABLE_LOG = 'desktop.2026-09-22.log';+const LAUNCHED_AT = Date.UTC(2026, 8, 23, 23, 59);+const BEFORE_LAUNCH = '2026-09-23T23:58:00.000Z';+const YESTERDAY_AFTER_LAUNCH = '2026-09-23T23:59:30.000Z';+const AFTER_LAUNCH = '2026-09-24T00:00:30.000Z';++function logsDirOf(home) {+ return join(home, '.ok', 'logs');+}++function writeLogFile(logsDir, name, lines) {+ writeFileSync(join(logsDir, name), `${lines.join('\n')}\n`);+}++function homeWithLogs(lines, previousDayLines = null) {+ const home = mkdtempSync(join(tmpdir(), 'ok-win-pty-home-'));+ fixtures.push(home);+ const logsDir = logsDirOf(home);+ mkdirSync(logsDir, { recursive: true });+ if (previousDayLines !== null) writeLogFile(logsDir, OLDER_LOG, previousDayLines);+ writeLogFile(logsDir, NEWER_LOG, lines);+ return home;+}+const CONPTY_INIT = '\u001b[1t\u001b[c';const MARKER_LINE = 'OK_PACKAGED_PTY_ECHO\r\n';const RENDERER_TIMER_MS = 500;+const OVERSIZED_TERMINAL_LOG_LINES = 400;describe('packaged Windows terminal smoke driver', () => {test('seeds deterministic project-local terminal config for the packaged app', () => {@@ -271,6 +401,41 @@ describe('packaged Windows terminal smoke driver', () => {expect(options.env).toEqual(windowsPtyDriverEnv({ SENTINEL: 'preserved' }));});+ test('spawns the packaged app at a log level that keeps the records its failure path reads back', async () => {+ const home = mkdtempSync(join(tmpdir(), 'ok-win-pty-logger-home-'));+ fixtures.push(home);+ const spawned = windowsPackageAppEnv({+ NODE_ENV: 'test',+ LOG_LEVEL: 'error',+ OK_LOG_LEVEL: 'error',+ HOME: home,+ USERPROFILE: home,+ });++ vi.resetModules();+ for (const [key, value] of Object.entries(spawned)) vi.stubEnv(key, value);+ try {+ const { getRootDesktopLogger } = await import('../src/main/desktop-logger.ts');+ const logger = getRootDesktopLogger();+ const destination = logger[pino.symbols.streamSym];+ const closed = once(destination, 'close');+ destination.end();+ await closed;++ expect(+ existsSync(logsDirOf(home)),+ 'the logger resolves its directory from the home this cell stubbed, so a run that did not open it there wrote its records somewhere else and settles nothing about the level',+ ).toBe(true);+ expect(+ { warn: logger.isLevelEnabled('warn'), info: logger.isLevelEnabled('info') },+ `the packaged app inherits whatever environment the runner hands the smoke, the terminal and pty-host subsystems log only at warn and info, and this one resolved to ${logger.level}, which empties the corpus the failure path reads back and leaves it reporting that the app logged nothing about the subsystem this smoke drives`,+ ).toEqual({ warn: true, info: true });+ } finally {+ vi.unstubAllEnvs();+ vi.resetModules();+ }+ });+test('stops re-arming the read window when its own deadline is spent', () => {const stubRoot = stubRootWithModule(CHATTY_PEER_STUB);const startedAt = Date.now();@@ -487,10 +652,504 @@ describe('packaged Windows terminal smoke driver', () => {expect(firstByteMs).toBeLessThan(markerMs);});- test('reports the same measurements on the line it prints when nothing echoes', async () => {- await expect(runPtyEchoSnippet(stubRenderer())).rejects.toThrow(+ test('reports the same measurements on the line it prints when nothing echoes, and says no ending arrived', async () => {+ const pending = runPtyEchoSnippet(stubRenderer());+ await expect(pending).rejects.toThrow(/PTY echo timed out; output=""; timings=\{"createdMs":\d+,"firstByteMs":null,"markerMs":null\}/,);++ const { endings, notices } = timeoutFields((await rejectionOf(pending)).message);+ expect(+ { endings, notices },+ 'an empty endings list is the datum that separates a shell that is alive and silent from every death, so it must be reported rather than omitted',+ ).toEqual({ endings: [], notices: [] });+ });++ test('subscribes to every ending channel before it creates the pty, and releases all three when it settles', async () => {+ const renderer = stubRenderer({ duringStart: [CONPTY_INIT, MARKER_LINE] });++ await runPtyEchoSnippet(renderer);++ expect(renderer.subscriptionAudit()).toEqual({+ subscribed: { data: 1, exit: 1, notice: 1 },+ subscribedAtCreate: { data: 1, exit: 1, notice: 1 },+ active: { data: 0, exit: 0, notice: 0 },+ });+ });++ test('names the preload member it could not subscribe to, instead of leaving the driver waiting on the socket', async () => {+ const renderer = stubRenderer();+ delete renderer.okDesktop.terminal.onExit;+ const STILL_PENDING = Symbol('still pending');++ const settled = await Promise.race([+ rejectionOf(runPtyEchoSnippet(renderer)),+ new Promise((resolve) => setTimeout(() => resolve(STILL_PENDING), RENDERER_TIMER_MS * 4)),+ ]);++ expect(+ settled,+ 'a preload that does not expose a channel must settle the expression with its own cause; staying pending spends the whole CDP budget and prints a reply timeout carrying no cause at all',+ ).not.toBe(STILL_PENDING);+ expect(settled.message).toMatch(/onExit/);+ expect(+ {+ subscribed: renderer.subscriptionAudit().subscribed,+ active: renderer.subscriptionAudit().active,+ },+ 'the channel it did subscribe to before the throw has to come back off; taking all three in one call loses the first release when the second throws, and that listener outlives the expression that installed it',+ ).toEqual({+ subscribed: { data: 1, exit: 0, notice: 0 },+ active: { data: 0, exit: 0, notice: 0 },+ });+ });++ test('names a shell that never attached on the line it prints', async () => {+ const { endings, notices } = await timedOutWith([+ { exit: { ptyId: STUB_PTY_ID, neverStarted: true } },+ ]);++ expect({ endings, notices }).toEqual({+ endings: [{ ptyId: STUB_PTY_ID, neverStarted: true, atMs: expect.any(Number) }],+ notices: [],+ });+ });++ test('names an attached shell that exited, with the code it exited on', async () => {+ const { endings } = await timedOutWith([+ CONPTY_INIT,+ { exit: { ptyId: STUB_PTY_ID, exitCode: STUB_EXIT_CODE, signal: null } },+ ]);++ expect(endings).toEqual([+ { ptyId: STUB_PTY_ID, exitCode: STUB_EXIT_CODE, signal: null, atMs: expect.any(Number) },+ ]);+ });++ test('separates a dead pty host from a shell that never attached and from a shell that exited', async () => {+ const { endings } = await timedOutWith([+ { exit: { ptyId: STUB_PTY_ID, neverStarted: true, hostExited: true } },+ ]);++ expect(endings).toEqual([+ { ptyId: STUB_PTY_ID, neverStarted: true, hostExited: true, atMs: expect.any(Number) },+ ]);+ });++ test('names a shell notice and the reason it carried', async () => {+ const { endings, notices } = await timedOutWith([+ { notice: { ptyId: STUB_PTY_ID, notice: 'invalid-shell-override', reason: 'not-found' } },+ ]);++ expect({ endings, notices }).toEqual({+ endings: [],+ notices: [+ {+ ptyId: STUB_PTY_ID,+ notice: 'invalid-shell-override',+ reason: 'not-found',+ atMs: expect.any(Number),+ },+ ],+ });+ });++ test('keeps an ending whose ptyId does not match the pty it created', async () => {+ const { endings } = await timedOutWith([+ { exit: { ptyId: OTHER_PTY_ID, exitCode: STUB_EXIT_CODE, signal: null } },+ ]);++ expect(+ endings,+ 'dropping an ending is the defect under repair, so an ending for another pty is reported with its own ptyId rather than filtered away',+ ).toEqual([+ { ptyId: OTHER_PTY_ID, exitCode: STUB_EXIT_CODE, signal: null, atMs: expect.any(Number) },+ ]);+ });++ test('reports what it saw before the marker on the run that echoed, and records nothing after it settles', async () => {+ const result = await runPtyEchoSnippet(+ stubRenderer({+ duringStart: [+ { notice: { ptyId: STUB_PTY_ID, notice: 'shell-resolved', shellFamily: 'cmd' } },+ CONPTY_INIT,+ MARKER_LINE,+ { exit: { ptyId: STUB_PTY_ID, exitCode: 0, signal: null } },+ ],+ }),+ );++ expect({ endings: result.endings, notices: result.notices }).toEqual({+ endings: [],+ notices: [+ {+ ptyId: STUB_PTY_ID,+ notice: 'shell-resolved',+ shellFamily: 'cmd',+ atMs: expect.any(Number),+ },+ ],+ });+ });++ test('prints what the observer recorded beside the timings on the run that passed', () => {+ const { code, output } = runPython(+ [+ '-c',+ [+ 'import importlib.util, sys, types',+ "sys.modules['websocket'] = types.ModuleType('websocket')",+ `spec = importlib.util.spec_from_file_location('d', ${JSON.stringify(driverPath)})`,+ 'm = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)',+ "m.find_editor_websocket = lambda: 'ws://stub'",+ 'm.evaluate_pty_echo = lambda socket_url: {',+ " 'platform': 'win32',",+ " 'timings': {'createdMs': 1, 'firstByteMs': 2, 'markerMs': 3},",+ " 'endings': [],",+ " 'notices': [{'ptyId': 'p', 'notice': 'shell-resolved', 'shellFamily': 'cmd', 'atMs': 2}],",+ '}',+ 'raise SystemExit(m.main())',+ ].join('\n'),+ ],+ {+ OK_SMOKE_EXPECT_PLATFORM: 'win32',+ OK_SMOKE_ECHO_DEADLINE_MS: String(PACKAGED_PTY_ECHO_BUDGET_MS),+ },+ );++ expect(code).toBe(0);+ expect(+ output,+ 'a green run is the cheapest proof that the ending channels are live, which it can only give by printing what they delivered',+ ).toContain(+ 'timings={"createdMs": 1, "firstByteMs": 2, "markerMs": 3}; endings=[]; ' ++ 'notices=[{"ptyId": "p", "notice": "shell-resolved", "shellFamily": "cmd", "atMs": 2}]',+ );+ });++ test('surfaces the terminal and pty-host lines the app wrote to its own log', async () => {+ const read = await terminalSubsystemLogReader();+ const unrelated = JSON.stringify({+ time: AFTER_LAUNCH,+ level: 30,+ subsystem: 'app',+ event: 'terminal-load-failed',+ });+ const spawnError = JSON.stringify({+ time: AFTER_LAUNCH,+ level: 40,+ subsystem: 'terminal',+ event: 'terminal-manager-spawn-error',+ shellNeverAttached: true,+ exitCode: -1,+ elapsedMs: 42,+ killRequested: false,+ });+ const hostLine = JSON.stringify({+ time: AFTER_LAUNCH,+ level: 40,+ subsystem: 'pty-host',+ event: 'pty-host-unexpected-message',+ });+ const eventless = JSON.stringify({+ time: AFTER_LAUNCH,+ level: 40,+ subsystem: 'terminal',+ cli: 'claude',+ msg: 'cli-preflight: unknown cli discriminant',+ });++ const surfaced = read(LAUNCHED_AT, homeWithLogs([unrelated, spawnError, hostLine, eventless]));++ expect(surfaced).toContain(spawnError);+ expect(surfaced).toContain(hostLine);+ expect(+ surfaced,+ 'the terminal subsystem names an event on most of its records but not all of them, so a reader that selects on the event name instead of the subsystem drops the warnings that carry no event and the triager loses them',+ ).toContain(eventless);+ expect(surfaced).not.toContain('terminal-load-failed');+ });++ test('says it looked and where when the logs directory is not there', async () => {+ const read = await terminalSubsystemLogReader();+ const absent = join(tmpdir(), `ok-win-pty-home-absent-${process.pid}`);+ expect(existsSync(absent)).toBe(false);++ const surfaced = read(LAUNCHED_AT, absent);++ expect(surfaced.trim()).not.toBe('');+ expect(surfaced).toContain(logsDirOf(absent));+ });++ test('says it looked and where when the logs it found carry no terminal line', async () => {+ const read = await terminalSubsystemLogReader();+ const home = homeWithLogs([+ JSON.stringify({+ time: AFTER_LAUNCH,+ level: 30,+ subsystem: 'app',+ event: 'theme-source-set',+ }),+ ]);+ const absent = join(tmpdir(), `ok-win-pty-home-absent-${process.pid}`);++ const surfaced = read(LAUNCHED_AT, home);++ expect(surfaced.trim()).not.toBe('');+ expect(surfaced).toContain(logsDirOf(home));+ expect(surfaced).not.toContain('theme-source-set');+ expect(+ surfaced.replaceAll(home, '<home>'),+ 'a directory that holds no terminal line is a different observation from a directory that is not there, so the two cannot print the same sentence',+ ).not.toBe(read(LAUNCHED_AT, absent).replaceAll(absent, '<home>'));+ });++ test('bounds what it surfaces to the newest lines the terminal subsystem wrote', async () => {+ const read = await terminalSubsystemLogReader();+ const line = (index) =>+ JSON.stringify({+ time: AFTER_LAUNCH,+ level: 40,+ subsystem: 'terminal',+ event: 'terminal-manager-host-exited',+ index,+ });+ const written = Array.from({ length: OVERSIZED_TERMINAL_LOG_LINES }, (_, index) => line(index));++ const surfaced = read(LAUNCHED_AT, homeWithLogs(written));++ expect(surfaced).toContain(line(OVERSIZED_TERMINAL_LOG_LINES - 1));+ expect(surfaced).not.toContain(line(0));+ });++ test('skips a line it cannot parse and still surfaces the terminal lines around it', async () => {+ const read = await terminalSubsystemLogReader();+ const tornEvent = 'terminal-manager-write-interrupted';+ const before = JSON.stringify({+ time: AFTER_LAUNCH,+ level: 40,+ subsystem: 'terminal',+ event: 'terminal-manager-spawn-error',+ shellNeverAttached: true,+ });+ const after = JSON.stringify({+ time: AFTER_LAUNCH,+ level: 40,+ subsystem: 'pty-host',+ event: 'pty-host-exited',+ code: 1,+ });+ const complete = JSON.stringify({+ time: AFTER_LAUNCH,+ level: 40,+ subsystem: 'terminal',+ event: tornEvent,+ elapsedMs: 42,+ });+ const torn = complete.slice(0, complete.lastIndexOf(',"elapsedMs"'));++ const surfaced = read(LAUNCHED_AT, homeWithLogs([before, torn, after]));++ expect(surfaced).toContain(before);+ expect(surfaced).toContain(after);+ expect(+ surfaced,+ 'a half-written record carries no subsystem the reader can select on, and printing the fragment puts a parse artefact where the triager is looking for the lines that explain the run',+ ).not.toContain(tornEvent);+ });++ test('surfaces every log file the directory holds, oldest first', async () => {+ const read = await terminalSubsystemLogReaderOverNewestFirstListing();+ const yesterday = JSON.stringify({+ time: YESTERDAY_AFTER_LAUNCH,+ level: 40,+ subsystem: 'terminal',+ event: 'terminal-manager-host-exited',+ day: 'yesterday',+ });+ const today = JSON.stringify({+ time: AFTER_LAUNCH,+ level: 40,+ subsystem: 'terminal',+ event: 'terminal-manager-host-exited',+ day: 'today',+ });++ const surfaced = read(LAUNCHED_AT, homeWithLogs([today], [yesterday]));++ expect(surfaced).toContain(yesterday);+ expect(surfaced).toContain(today);+ expect(+ surfaced.indexOf(yesterday),+ 'the app names its log file once, for the day it started, so a run that crosses midnight leaves two of them; splicing the older day in after the newer one reads to a triager as a clock running backwards',+ ).toBeLessThan(surfaced.indexOf(today));+ });++ test('bounds the newest lines across every log file, not within each one', async () => {+ const read = await terminalSubsystemLogReaderOverNewestFirstListing();+ const line = (index) =>+ JSON.stringify({+ time: AFTER_LAUNCH,+ level: 40,+ subsystem: 'terminal',+ event: 'terminal-manager-host-exited',+ index,+ });+ const yesterday = JSON.stringify({+ time: YESTERDAY_AFTER_LAUNCH,+ level: 40,+ subsystem: 'terminal',+ event: 'terminal-manager-host-exited',+ day: 'yesterday',+ });+ const written = Array.from({ length: OVERSIZED_TERMINAL_LOG_LINES }, (_, index) => line(index));++ const surfaced = read(LAUNCHED_AT, homeWithLogs(written, [yesterday]));++ expect(surfaced).toContain(line(OVERSIZED_TERMINAL_LOG_LINES - 1));+ expect(+ surfaced,+ 'a bound spent once per file keeps yesterday alive at the cost of the lines this run wrote, which is the opposite of the trade a triager reading a failed run needs',+ ).not.toContain(yesterday);+ });++ test('says what it looked at and where when the logs path cannot be listed', async () => {+ const read = await terminalSubsystemLogReader();+ const home = mkdtempSync(join(tmpdir(), 'ok-win-pty-home-'));+ fixtures.push(home);+ mkdirSync(join(home, '.ok'));+ const notADirectory = logsDirOf(home);+ writeFileSync(notADirectory, 'a path that exists, is readable, and is not a directory\n');+ expect(+ existsSync(notADirectory),+ 'the path has to exist, or the reader answers from its absence branch and this cell never reaches the listing it is here to drive',+ ).toBe(true);++ const surfaced = read(LAUNCHED_AT, home);++ expect(surfaced.trim()).not.toBe('');+ expect(+ surfaced,+ 'the reader runs inside the supervisor catch that is about to print why the driver failed, so a filesystem error let loose here replaces that diagnostic with its own',+ ).toContain(notADirectory);+ });++ test('surfaces the terminal records in the logs it can read when another log cannot be read', async () => {+ const read = await terminalSubsystemLogReader();+ const record = JSON.stringify({+ time: AFTER_LAUNCH,+ level: 40,+ subsystem: 'terminal',+ event: 'terminal-manager-spawn-error',+ shellNeverAttached: true,+ });+ const home = homeWithLogs([record]);+ mkdirSync(join(logsDirOf(home), UNREADABLE_LOG));++ const surfaced = read(LAUNCHED_AT, home);++ expect(surfaced).toContain(record);+ expect(+ surfaced,+ 'a log the reader could not open may hold the record that explains the run, so the triager has to be told which one is missing',+ ).toContain(UNREADABLE_LOG);+ });++ test('names the log it could not read when the logs it could read carry no terminal record', async () => {+ const read = await terminalSubsystemLogReader();+ const home = homeWithLogs([+ JSON.stringify({+ time: AFTER_LAUNCH,+ level: 30,+ subsystem: 'app',+ event: 'theme-source-set',+ }),+ ]);+ mkdirSync(join(logsDirOf(home), UNREADABLE_LOG));++ const surfaced = read(LAUNCHED_AT, home);++ expect(+ surfaced,+ 'with nothing found in the logs it could read, the log it could not open is the only place the record that explains the run can still be, so leaving it unnamed reads as a terminal subsystem that stayed quiet',+ ).toContain(UNREADABLE_LOG);+ });++ test('prints the terminal records this launch wrote, and none from before it, when the driver fails', () => {+ const earlierSession = JSON.stringify({+ time: BEFORE_LAUNCH,+ level: 40,+ subsystem: 'terminal',+ event: 'terminal-manager-spawn-error',+ shellNeverAttached: true,+ });+ const thisLaunch = JSON.stringify({+ time: AFTER_LAUNCH,+ level: 40,+ subsystem: 'pty-host',+ event: 'pty-host-exited',+ code: 1,+ });+ const home = homeWithLogs([earlierSession, thisLaunch]);+ const packageDir = join(home, 'win-unpacked');+ mkdirSync(packageDir);+ copyFileSync(+ process.execPath,+ join(packageDir, 'OpenKnowledge.exe'),+ constants.COPYFILE_FICLONE,+ );++ vi.stubEnv('HOME', home);+ vi.stubEnv('USERPROFILE', home);+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(LAUNCHED_AT);+ const printed = vi.spyOn(console, 'error').mockImplementation(() => {});+ try {+ expect(() =>+ runWindowsPackageTerminalSmoke({+ packageDir,+ platform: 'win32',+ env: { ...process.env, ComSpec: 'C:\\Windows\\System32\\cmd.exe' },+ python: join(home, 'no-python-here'),+ }),+ ).toThrow(/could not run packaged PTY CDP driver/);+ const stderr = printed.mock.calls.map((call) => call.join(' ')).join('\n');++ expect(stderr).toContain(thisLaunch);+ expect(+ stderr,+ 'the app shares one log file per day across every session on the host, so a record from before this launch printed beside its own reads to a triager as something this run did',+ ).not.toContain(earlierSession);+ } finally {+ printed.mockRestore();+ vi.useRealTimers();+ vi.unstubAllEnvs();+ }+ });++ test('reads the logs the app writes beneath the home directory when it is called without one', async () => {+ const read = await terminalSubsystemLogReader();+ const hostLine = JSON.stringify({+ time: AFTER_LAUNCH,+ level: 40,+ subsystem: 'pty-host',+ event: 'pty-host-exited',+ code: 1,+ });+ const fakeHome = homeWithLogs([hostLine]);++ vi.stubEnv('HOME', fakeHome);+ vi.stubEnv('USERPROFILE', fakeHome);+ try {+ expect(+ homedir(),+ 'the home directory has to resolve to the fixture before the reader is called, or calling it without one reads whatever this machine has in its own ~/.ok/logs',+ ).toBe(fakeHome);++ expect(read(LAUNCHED_AT)).toContain(hostLine);+ } finally {+ vi.unstubAllEnvs();+ }});test('names every phase budget in seconds when the kill fires', () => {