Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Stop a Windows quit crash from hiding restored terminal tabs (#4996)
Nick Gomez1f7787f99374
diff --git a/.changeset/windows-server-shutdown-watcher-crash.md b/.changeset/windows-server-shutdown-watcher-crash.mdnew file mode 100644index 000000000..d7ee4f22e--- /dev/null+++ b/.changeset/windows-server-shutdown-watcher-crash.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++On Windows, stopping a project server no longer risks a native crash in its file watcher during shutdown.diff --git a/packages/desktop/src/main/minidump.test-helper.ts b/packages/desktop/src/main/minidump.test-helper.tsindex fb6a88d78..17f945a28 100644--- a/packages/desktop/src/main/minidump.test-helper.ts+++ b/packages/desktop/src/main/minidump.test-helper.ts@@ -20,7 +20,30 @@ const ANNOTATION_OBJECT_VALUE_RVA_OFFSET = 8;const ANNOTATION_TYPE_STRING = 1;const EXCEPTION_STREAM_TYPE = 6;const EXCEPTION_STREAM_BYTES = 168;+const EXCEPTION_THREAD_ID_OFFSET = 0;const EXCEPTION_CODE_OFFSET = 8;+const EXCEPTION_FLAGS_OFFSET = 12;+const EXCEPTION_ADDRESS_OFFSET = 24;+const MODULE_BASE_OFFSET = 0;+const MODULE_SIZE_OFFSET = 8;+const MISC_INFO_STREAM_TYPE = 15;+const MISC_INFO_BYTES = 24;+const MISC_INFO_FLAGS_OFFSET = 4;+const MISC_INFO_PROCESS_ID_OFFSET = 8;+const MISC_INFO_PROCESS_CREATE_TIME_OFFSET = 12;+const MISC_INFO_PROCESS_ID_FLAG = 0x1;+const MISC_INFO_PROCESS_TIMES_FLAG = 0x2;+const HEADER_TIME_DATE_STAMP_OFFSET = 20;++interface MinidumpModuleImage {+ base: bigint;+ size: number;+}++interface MinidumpMiscInfo {+ processId?: number;+ processCreateTime?: number;+}export interface MinidumpPatch {signature?: string;@@ -52,6 +75,12 @@ export interface MinidumpPatch {annotationObjectType?: number;annotationObjectValueRva?: number;annotationObjectValueByteLength?: number;+ moduleImages?: readonly MinidumpModuleImage[];+ exceptionThreadId?: number;+ exceptionFlags?: number;+ exceptionAddress?: bigint;+ miscInfo?: MinidumpMiscInfo;+ timeDateStamp?: number;}export function buildMinidump(modulePaths: string[], patch: MinidumpPatch = {}): Buffer {@@ -61,7 +90,9 @@ export function buildMinidump(modulePaths: string[], patch: MinidumpPatch = {}):const objectModules = patch.annotationObjects ?? null;const hasCrashpadStream = annotationEntries !== null || objectModules !== null;const hasException = patch.exceptionCode !== undefined;- const directoryEntries = decoyStreams + 1 + (hasCrashpadStream ? 1 : 0) + (hasException ? 1 : 0);+ const hasMiscInfo = patch.miscInfo !== undefined;+ const directoryEntries =+ decoyStreams + 1 + (hasCrashpadStream ? 1 : 0) + (hasException ? 1 : 0) + (hasMiscInfo ? 1 : 0);const directoryRva = HEADER_BYTES;const moduleListRva = directoryRva + directoryEntries * DIRECTORY_ENTRY_BYTES;const moduleListBytes = 4 + modulePaths.length * MODULE_RECORD_BYTES;@@ -230,17 +261,39 @@ export function buildMinidump(modulePaths: string[], patch: MinidumpPatch = {}):const exceptionRva = cursor;if (hasException) {const exception = Buffer.alloc(EXCEPTION_STREAM_BYTES);- exception.writeUInt32LE(1, 0);+ exception.writeUInt32LE(patch.exceptionThreadId ?? 1, EXCEPTION_THREAD_ID_OFFSET);exception.writeUInt32LE(patch.exceptionCode ?? 0, EXCEPTION_CODE_OFFSET);+ exception.writeUInt32LE(patch.exceptionFlags ?? 0, EXCEPTION_FLAGS_OFFSET);+ exception.writeBigUInt64LE(patch.exceptionAddress ?? 0n, EXCEPTION_ADDRESS_OFFSET);exceptionBlocks.push(exception);cursor += EXCEPTION_STREAM_BYTES;}+ const miscInfoBlocks: Buffer[] = [];+ const miscInfoRva = cursor;+ if (patch.miscInfo !== undefined) {+ const { processId, processCreateTime } = patch.miscInfo;+ const misc = Buffer.alloc(MISC_INFO_BYTES);+ misc.writeUInt32LE(MISC_INFO_BYTES, 0);+ misc.writeUInt32LE(+ (processId === undefined ? 0 : MISC_INFO_PROCESS_ID_FLAG) |+ (processCreateTime === undefined ? 0 : MISC_INFO_PROCESS_TIMES_FLAG),+ MISC_INFO_FLAGS_OFFSET,+ );+ misc.writeUInt32LE(processId ?? 0, MISC_INFO_PROCESS_ID_OFFSET);+ misc.writeUInt32LE(processCreateTime ?? 0, MISC_INFO_PROCESS_CREATE_TIME_OFFSET);+ miscInfoBlocks.push(misc);+ cursor += MISC_INFO_BYTES;+ }+const header = Buffer.alloc(HEADER_BYTES);header.write(patch.signature ?? 'MDMP', 0, 'ascii');header.writeUInt32LE(0xa793, 4);header.writeUInt32LE(patch.streamCount ?? directoryEntries, 8);header.writeUInt32LE(patch.streamDirectoryRva ?? directoryRva, 12);+ if (patch.timeDateStamp !== undefined) {+ header.writeUInt32LE(patch.timeDateStamp, HEADER_TIME_DATE_STAMP_OFFSET);+ }const directory = Buffer.alloc(directoryEntries * DIRECTORY_ENTRY_BYTES);for (let i = 0; i < decoyStreams; i += 1) {@@ -263,6 +316,12 @@ export function buildMinidump(modulePaths: string[], patch: MinidumpPatch = {}):directory.writeUInt32LE(exceptionRva, nextEntry + 8);nextEntry += DIRECTORY_ENTRY_BYTES;}+ if (hasMiscInfo) {+ directory.writeUInt32LE(MISC_INFO_STREAM_TYPE, nextEntry);+ directory.writeUInt32LE(MISC_INFO_BYTES, nextEntry + 4);+ directory.writeUInt32LE(miscInfoRva, nextEntry + 8);+ nextEntry += DIRECTORY_ENTRY_BYTES;+ }const moduleList = Buffer.alloc(moduleListBytes);moduleList.writeUInt32LE(patch.moduleCount ?? modulePaths.length, 0);@@ -270,6 +329,11 @@ export function buildMinidump(modulePaths: string[], patch: MinidumpPatch = {}):const at = 4 + index * MODULE_RECORD_BYTES + MODULE_NAME_RVA_OFFSET;moduleList.writeUInt32LE(index === 0 ? (patch.nameRva ?? rva) : rva, at);});+ patch.moduleImages?.forEach((image, index) => {+ const at = 4 + index * MODULE_RECORD_BYTES;+ moduleList.writeBigUInt64LE(image.base, at + MODULE_BASE_OFFSET);+ moduleList.writeUInt32LE(image.size, at + MODULE_SIZE_OFFSET);+ });const dump = Buffer.concat([header,@@ -278,6 +342,7 @@ export function buildMinidump(modulePaths: string[], patch: MinidumpPatch = {}):...nameBlocks,...crashpadBlocks,...exceptionBlocks,+ ...miscInfoBlocks,]);return patch.truncateTo === undefined ? dump : dump.subarray(0, patch.truncateTo);}diff --git a/packages/desktop/tests/smoke/_helpers/crash-dumps.test.ts b/packages/desktop/tests/smoke/_helpers/crash-dumps.test.tsnew file mode 100644index 000000000..3f0f4594c--- /dev/null+++ b/packages/desktop/tests/smoke/_helpers/crash-dumps.test.ts@@ -0,0 +1,714 @@+import { spawnSync } from 'node:child_process';+import {+ mkdirSync,+ mkdtempSync,+ readdirSync,+ rmSync,+ symlinkSync,+ utimesSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, describe, expect, test } from 'vitest';+import { buildMinidump, type MinidumpPatch } from '../../../src/main/minidump.test-helper.ts';+import {+ type AppProcess,+ type CrashDumpTestInfo,+ type CrashDumpVerdict,+ type CrashDumpWatch,+ collectCrashDumps,+ crashDumpsSince,+ crashDumpVerdict,+ crashDumpWatchFor,+ failIfEarlierAttemptFoundCrashDump,+ type ProcessTableRead,+ processRoleOf,+ type QuitObservation,+ readCrashDumpFacts,+ runningAppProcesses,+} from './crash-dumps';++const QUIT_REQUESTED_AT_MS = Date.parse('2026-09-22T15:30:19.277Z');+const ACCESS_VIOLATION = 0xc000_0005;+const DARWIN_SIMULATED_DUMP = 0x4350_7378;+const EXCEPTION_STREAM_BYTES = 168;+const NTDLL = { base: 0x7ffa_1000_0000n, size: 0x20_0000 };+const ELECTRON_IMAGE = { base: 0x7ff6_0000_0000n, size: 0x1000_0000 };+const PNPM_CONPTY_ADDON =+ 'D:\\a\\agents-private\\node_modules\\.pnpm\\[email protected]\\node_modules\\node-pty\\prebuilds\\win32-x64\\conpty.node';+const PNPM_CONPTY_DLL =+ 'D:\\a\\agents-private\\node_modules\\.pnpm\\[email protected]\\node_modules\\node-pty\\prebuilds\\win32-x64\\conpty\\conpty.dll';+const PARCEL_WATCHER_ADDON =+ 'D:\\a\\agents-private\\node_modules\\.pnpm\\@[email protected]\\node_modules\\@parcel\\watcher-win32-x64\\watcher.node';+const TERMINAL_HOST: AppProcess = {+ pid: 5678,+ type: 'Utility',+ serviceName: 'OpenKnowledge Terminal Host 1',+ name: 'OpenKnowledge Terminal Host 1',+ creationTime: QUIT_REQUESTED_AT_MS - 5_300,+};+const PROJECT_SERVER: AppProcess = {+ pid: 4321,+ type: 'Utility',+ serviceName: 'OpenKnowledge Project Server 1',+ name: 'OpenKnowledge Project Server 1',+ creationTime: QUIT_REQUESTED_AT_MS - 18_000,+};+const OBSERVATION: QuitObservation = {+ processes: [TERMINAL_HOST, PROJECT_SERVER],+ quitRequestedAtMs: QUIT_REQUESTED_AT_MS,+};++const tmpDirs: string[] = [];++afterEach(() => {+ for (const dir of tmpDirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++interface CrashpadFixture {+ crashDumps: string;+ mainModule: string;+ watch(platform?: NodeJS.Platform): CrashDumpWatch;+ writeDump(relativePath: string, bytes: Buffer, mtimeMs: number): string;+}++function crashpadFixture(executable: (bundleRoot: string) => string): CrashpadFixture {+ const root = mkdtempSync(join(tmpdir(), 'ok-crash-dumps-'));+ tmpDirs.push(root);+ const crashDumps = join(root, 'electron-userdata', 'Crashpad');+ mkdirSync(crashDumps, { recursive: true });+ const mainModule = executable(join(root, 'electron-dist'));+ return {+ crashDumps,+ mainModule,+ watch: (platform = 'win32') => crashDumpWatchFor(crashDumps, mainModule, platform),+ writeDump(relativePath, bytes, mtimeMs) {+ const path = join(crashDumps, relativePath);+ mkdirSync(join(path, '..'), { recursive: true });+ writeFileSync(path, bytes);+ utimesSync(path, new Date(mtimeMs), new Date(mtimeMs));+ return path;+ },+ };+}++function windowsFixture(): CrashpadFixture {+ return crashpadFixture((bundleRoot) => join(bundleRoot, 'electron.exe'));+}++function utilityDump(mainModule: string, extraModules: string[], patch: MinidumpPatch): Buffer {+ return buildMinidump([mainModule, ...extraModules], {+ annotationObjects: [{ process_type: 'utility' }],+ ...patch,+ });+}++function verdictFor(watch: CrashDumpWatch): CrashDumpVerdict {+ return crashDumpVerdict(crashDumpsSince(watch), OBSERVATION, watch.platform);+}++describe('readCrashDumpFacts', () => {+ test('lists every loaded module with its image range, not only the main module', () => {+ const fixture = windowsFixture();+ const path = fixture.writeDump(+ 'reports/facts.dmp',+ buildMinidump(+ ['C:\\app\\electron.exe', 'C:\\Windows\\System32\\ntdll.dll', PNPM_CONPTY_ADDON],+ {+ moduleImages: [ELECTRON_IMAGE, NTDLL, { base: 0x7ff9_2000_0000n, size: 0x4_0000 }],+ },+ ),+ QUIT_REQUESTED_AT_MS,+ );++ expect(readCrashDumpFacts(path).modules).toEqual([+ { path: 'C:\\app\\electron.exe', base: ELECTRON_IMAGE.base, size: ELECTRON_IMAGE.size },+ { path: 'C:\\Windows\\System32\\ntdll.dll', base: NTDLL.base, size: NTDLL.size },+ { path: PNPM_CONPTY_ADDON, base: 0x7ff9_2000_0000n, size: 0x4_0000 },+ ]);+ });++ test('reads the exception record, the process id and creation time, and the write time', () => {+ const fixture = windowsFixture();+ const path = fixture.writeDump(+ 'reports/exception.dmp',+ buildMinidump(['C:\\app\\electron.exe'], {+ exceptionCode: ACCESS_VIOLATION,+ exceptionFlags: 1,+ exceptionAddress: NTDLL.base + 0x1234n,+ exceptionThreadId: 4242,+ miscInfo: { processId: 5678, processCreateTime: 1_790_091_014 },+ timeDateStamp: 1_790_091_019,+ }),+ QUIT_REQUESTED_AT_MS,+ );++ const facts = readCrashDumpFacts(path);+ expect(facts.exception).toEqual({+ code: ACCESS_VIOLATION,+ flags: 1,+ address: NTDLL.base + 0x1234n,+ threadId: 4242,+ });+ expect(facts.processId).toBe(5678);+ expect(facts.processCreatedAtSec).toBe(1_790_091_014);+ expect(facts.writtenAtSec).toBe(1_790_091_019);+ expect(facts.unreadable).toBeNull();+ });++ test('a process id MISC_INFO does not mark as valid is not reported', () => {+ const fixture = windowsFixture();+ const path = fixture.writeDump(+ 'reports/misc.dmp',+ buildMinidump(['C:\\app\\electron.exe'], { miscInfo: { processCreateTime: 1_790_091_014 } }),+ QUIT_REQUESTED_AT_MS,+ );++ const facts = readCrashDumpFacts(path);+ expect(facts.processCreatedAtSec).toBe(1_790_091_014);+ expect(facts.processId).toBeNull();+ });++ test('reads the simple dictionary and the string annotation objects of every module', () => {+ const fixture = windowsFixture();+ const path = fixture.writeDump(+ 'reports/annotations.dmp',+ buildMinidump(['C:\\app\\electron.exe'], {+ annotations: { _productName: 'OpenKnowledge', _version: '0.77.9' },+ annotationObjects: [+ { ignored_binary: 'x', first: 'kept' },+ { process_type: 'utility', 'switch-1': '--type=utility' },+ ],+ annotationObjectType: 2,+ }),+ QUIT_REQUESTED_AT_MS,+ );++ expect(readCrashDumpFacts(path).annotations).toEqual([+ { key: '_productName', value: 'OpenKnowledge', source: 'simple' },+ { key: '_version', value: '0.77.9', source: 'simple' },+ { key: 'first', value: 'kept', source: 'module' },+ { key: 'process_type', value: 'utility', source: 'module' },+ { key: 'switch-1', value: '--type=utility', source: 'module' },+ ]);+ });++ test.each<[string, (fixture: CrashpadFixture) => string]>([+ ['a missing file', (fixture) => join(fixture.crashDumps, 'reports', 'gone.dmp')],+ [+ 'an empty file',+ (fixture) => fixture.writeDump('reports/empty.dmp', Buffer.alloc(0), QUIT_REQUESTED_AT_MS),+ ],+ [+ 'a file without the minidump signature',+ (fixture) =>+ fixture.writeDump(+ 'reports/text.dmp',+ buildMinidump(['C:\\app\\electron.exe'], { signature: 'XXXX' }),+ QUIT_REQUESTED_AT_MS,+ ),+ ],+ ])('%s is reported as unreadable rather than throwing', (_label, pathOf) => {+ const facts = readCrashDumpFacts(pathOf(windowsFixture()));+ expect(facts.unreadable).not.toBeNull();+ expect(facts.modules).toEqual([]);+ });++ test('a dump cut off inside its exception record keeps the modules and drops the record', () => {+ const fixture = windowsFixture();+ const whole = buildMinidump(['C:\\app\\electron.exe', 'C:\\Windows\\System32\\ntdll.dll'], {+ exceptionCode: ACCESS_VIOLATION,+ });+ const path = fixture.writeDump(+ 'reports/cut.dmp',+ whole.subarray(0, whole.length - EXCEPTION_STREAM_BYTES + 4),+ QUIT_REQUESTED_AT_MS,+ );++ const facts = readCrashDumpFacts(path);+ expect(facts.modules.map((module) => module.path)).toEqual([+ 'C:\\app\\electron.exe',+ 'C:\\Windows\\System32\\ntdll.dll',+ ]);+ expect(facts.exception).toBeNull();+ });+});++describe('processRoleOf', () => {+ test.each([+ ['the pnpm development layout', PNPM_CONPTY_ADDON],+ [+ 'the packaged Windows layout',+ 'C:\\Users\\me\\AppData\\Local\\Programs\\OpenKnowledge\\resources\\app.asar.unpacked\\node_modules\\node-pty\\prebuilds\\win32-x64\\conpty.node',+ ],+ [+ 'a macOS build of the addon',+ '/Applications/OpenKnowledge.app/Contents/Resources/app.asar.unpacked/node_modules/node-pty/prebuilds/darwin-arm64/pty.node',+ ],+ ])('a process with node-pty’s terminal addon from %s is the pty-host', (_layout, addon) => {+ const fixture = windowsFixture();+ const path = fixture.writeDump(+ 'reports/role.dmp',+ buildMinidump(['C:\\app\\electron.exe', addon]),+ QUIT_REQUESTED_AT_MS,+ );+ expect(processRoleOf(readCrashDumpFacts(path))).toMatch(/^pty-host/);+ });++ test('the console-list agent node-pty forks on kill is told apart from the pty-host', () => {+ const fixture = windowsFixture();+ const path = fixture.writeDump(+ 'reports/agent.dmp',+ buildMinidump([+ 'C:\\app\\electron.exe',+ PNPM_CONPTY_ADDON.replace('conpty.node', 'conpty_console_list.node'),+ ]),+ QUIT_REQUESTED_AT_MS,+ );+ expect(processRoleOf(readCrashDumpFacts(path))).toBe('node-pty console-list agent');+ });++ test('a process with @parcel/watcher and no node-pty addon is the project server', () => {+ const fixture = windowsFixture();+ const path = fixture.writeDump(+ 'reports/server.dmp',+ buildMinidump(['C:\\app\\electron.exe', PARCEL_WATCHER_ADDON]),+ QUIT_REQUESTED_AT_MS,+ );+ expect(processRoleOf(readCrashDumpFacts(path))).toMatch(/^project server/);+ });++ test('a module merely named like the addon outside node-pty identifies nothing', () => {+ const fixture = windowsFixture();+ const path = fixture.writeDump(+ 'reports/lookalike.dmp',+ buildMinidump(['C:\\app\\electron.exe', 'C:\\Tools\\conpty.node']),+ QUIT_REQUESTED_AT_MS,+ );+ expect(processRoleOf(readCrashDumpFacts(path))).toBe('no identifying addon loaded');+ });+});++describe('crashDumpVerdict names the process a clean quit crashed', () => {+ test('the pty-host is named by its pid, its node-pty addon, its exception and faulting module', () => {+ const fixture = windowsFixture();+ const watch = fixture.watch();+ fixture.writeDump(+ 'reports/8c1f.dmp',+ utilityDump(+ fixture.mainModule,+ ['C:\\Windows\\System32\\ntdll.dll', PNPM_CONPTY_ADDON, PNPM_CONPTY_DLL],+ {+ moduleImages: [+ ELECTRON_IMAGE,+ NTDLL,+ { base: 0x7ff9_2000_0000n, size: 0x4_0000 },+ { base: 0x7ff9_3000_0000n, size: 0x10_0000 },+ ],+ exceptionCode: ACCESS_VIOLATION,+ exceptionAddress: NTDLL.base + 0x9abcn,+ miscInfo: { processId: TERMINAL_HOST.pid },+ },+ ),+ QUIT_REQUESTED_AT_MS + 463,+ );++ const verdict = verdictFor(watch);+ expect(verdict.crashes).toHaveLength(1);+ expect(verdict.headline).toBe(+ 'the quit left 1 crash dump(s) from the app; first: ' ++ 'pid 5678 Utility "OpenKnowledge Terminal Host 1"; pty-host (node-pty terminal addon loaded); ' ++ 'exception 0xC0000005 EXCEPTION_ACCESS_VIOLATION at 0x7FFA10009ABC in ntdll.dll; ' ++ 'written 463 ms after quit was requested',+ );+ expect(verdict.lines[0]).toContain('process_type=utility');+ expect(verdict.lines[0]).toContain('native addons: node-pty/conpty.node, node-pty/conpty.dll');+ expect(verdict.lines[0]).toContain('main module electron.exe');+ });++ test('the project server is named by its addon even when the pid was not in the snapshot', () => {+ const fixture = windowsFixture();+ const watch = fixture.watch();+ fixture.writeDump(+ 'reports/2d40.dmp',+ utilityDump(fixture.mainModule, [PARCEL_WATCHER_ADDON], {+ exceptionCode: 0xc000_0409,+ miscInfo: { processId: 999 },+ }),+ QUIT_REQUESTED_AT_MS - 1_500,+ );++ const { headline } = verdictFor(watch);+ expect(headline).toContain('pid 999 (not among the app processes listed before quit)');+ expect(headline).toContain('project server (@parcel/watcher addon loaded)');+ expect(headline).toContain('0xC0000409 STATUS_STACK_BUFFER_OVERRUN');+ expect(headline).toContain('written 1500 ms before quit was requested');+ });++ test('an exception address one past a module image is not attributed to that module', () => {+ const fixture = windowsFixture();+ const watch = fixture.watch();+ fixture.writeDump(+ 'reports/edge.dmp',+ utilityDump(fixture.mainModule, ['C:\\Windows\\System32\\ntdll.dll'], {+ moduleImages: [ELECTRON_IMAGE, NTDLL],+ exceptionCode: ACCESS_VIOLATION,+ exceptionAddress: NTDLL.base + BigInt(NTDLL.size),+ }),+ QUIT_REQUESTED_AT_MS,+ );++ expect(verdictFor(watch).headline).toContain('outside every listed module');+ });+});++describe('crashDumpsSince decides which dumps count against the quit', () => {+ test('a new owned dump counts; the baseline and a foreign dump do not', () => {+ const fixture = windowsFixture();+ fixture.writeDump(+ 'reports/old.dmp',+ utilityDump(fixture.mainModule, [], {}),+ QUIT_REQUESTED_AT_MS - 60_000,+ );+ const watch = fixture.watch();+ const owned = fixture.writeDump(+ 'reports/new.dmp',+ utilityDump(fixture.mainModule, [], {}),+ QUIT_REQUESTED_AT_MS + 10,+ );+ const foreign = fixture.writeDump(+ 'reports/foreign.dmp',+ buildMinidump(['C:\\Program Files\\PowerShell\\7\\pwsh.exe']),+ QUIT_REQUESTED_AT_MS + 20,+ );++ const findings = crashDumpsSince(watch);+ expect(findings.map((finding) => [finding.path, finding.countsAsCrash])).toEqual([+ [owned, true],+ [foreign, false],+ ]);+ });++ test('a dump whose main module cannot be read still counts as a crash from the app', () => {+ const fixture = windowsFixture();+ const watch = fixture.watch();+ const unreadable = fixture.writeDump(+ 'reports/unknown.dmp',+ buildMinidump([fixture.mainModule], { nameByteLength: 3 }),+ QUIT_REQUESTED_AT_MS,+ );++ expect(crashDumpsSince(watch).map((finding) => [finding.path, finding.ownership])).toEqual([+ [unreadable, 'unknown'],+ ]);+ expect(verdictFor(watch).crashes).toHaveLength(1);+ });++ test('a baseline dump rewritten after the watch began counts again', () => {+ const fixture = windowsFixture();+ const path = fixture.writeDump(+ 'reports/rewritten.dmp',+ utilityDump(fixture.mainModule, [], {}),+ QUIT_REQUESTED_AT_MS - 60_000,+ );+ const watch = fixture.watch();+ utimesSync(path, new Date(QUIT_REQUESTED_AT_MS + 5), new Date(QUIT_REQUESTED_AT_MS + 5));++ expect(crashDumpsSince(watch).map((finding) => finding.path)).toEqual([path]);+ });++ test('a macOS dump written without crashing does not count; one from a crash does', () => {+ const fixture = crashpadFixture((bundleRoot) =>+ join(bundleRoot, 'OpenKnowledge.app', 'Contents', 'MacOS', 'OpenKnowledge'),+ );+ const watch = fixture.watch('darwin');+ fixture.writeDump(+ 'completed/simulated.dmp',+ buildMinidump([fixture.mainModule], { exceptionCode: DARWIN_SIMULATED_DUMP }),+ QUIT_REQUESTED_AT_MS,+ );+ const crashed = fixture.writeDump(+ 'pending/crashed.dmp',+ buildMinidump([fixture.mainModule], { exceptionCode: 1 }),+ QUIT_REQUESTED_AT_MS + 1,+ );++ expect(verdictFor(watch).crashes.map((finding) => finding.path)).toEqual([crashed]);+ });++ test('a crash directory that never appeared yields no findings and a clean verdict', () => {+ const fixture = windowsFixture();+ const watch = crashDumpWatchFor(+ join(fixture.crashDumps, 'never-created'),+ fixture.mainModule,+ 'win32',+ );++ const verdict = verdictFor(watch);+ expect(verdict.findings).toEqual([]);+ expect(verdict.lines).toEqual([]);+ expect(verdict.headline).toBe('the quit left no crash dump from the app');+ });++ test('a crash directory that cannot be read after the watch began fails the scan instead of yielding a clean verdict', () => {+ const fixture = windowsFixture();+ const watch = fixture.watch();+ rmSync(fixture.crashDumps, { recursive: true });+ writeFileSync(fixture.crashDumps, '');++ expect(() => verdictFor(watch)).toThrow(/ENOTDIR/);+ });++ test.skipIf(process.platform === 'win32')(+ 'a dump whose metadata cannot be read after the watch began fails the scan instead of being dropped',+ () => {+ const fixture = windowsFixture();+ const watch = fixture.watch();+ const reports = join(fixture.crashDumps, 'reports');+ mkdirSync(reports);+ symlinkSync(join(reports, 'loop.dmp'), join(reports, 'loop.dmp'));++ expect(() => verdictFor(watch)).toThrow(/ELOOP/);+ },+ );+});++describe('collectCrashDumps', () => {+ interface Attached {+ name: string;+ path?: string;+ body?: string | Buffer;+ contentType?: string;+ }++ function verdictOutputDir(): string {+ const dir = mkdtempSync(join(tmpdir(), 'ok-crash-verdicts-'));+ tmpDirs.push(dir);+ return dir;+ }++ function recorder(+ testId = 'collect-crash-dumps',+ outputDir = verdictOutputDir(),+ ): CrashDumpTestInfo & { attached: Attached[] } {+ const attached: Attached[] = [];+ return {+ attached,+ testId,+ project: { outputDir },+ attach: async (name, options = {}) => {+ attached.push({ name, ...options });+ },+ };+ }++ test('keeps each crash dump file from the app and the facts of every new dump as evidence', async () => {+ const fixture = windowsFixture();+ const watch = fixture.watch();+ const owned = fixture.writeDump(+ 'reports/kept.dmp',+ utilityDump(fixture.mainModule, [PNPM_CONPTY_ADDON], {+ miscInfo: { processId: TERMINAL_HOST.pid },+ }),+ QUIT_REQUESTED_AT_MS + 7,+ );+ fixture.writeDump(+ 'reports/foreign.dmp',+ buildMinidump(['C:\\Program Files\\PowerShell\\7\\pwsh.exe']),+ QUIT_REQUESTED_AT_MS + 8,+ );+ const sink = recorder();++ const verdict = await collectCrashDumps(watch, OBSERVATION, sink);++ expect(verdict.crashes.map((finding) => finding.path)).toEqual([owned]);+ expect(sink.attached.map((entry) => [entry.name, entry.path ?? null])).toEqual([+ ['crash-dump-facts', null],+ ['crash-dump-1', owned],+ ]);+ const facts = JSON.parse(String(sink.attached[0]?.body));+ expect(+ facts.dumps.map((dump: { file: string; role: string; processId: number | null }) => [+ dump.file,+ dump.role,+ dump.processId,+ ]),+ ).toEqual([+ ['kept.dmp', 'pty-host (node-pty terminal addon loaded)', TERMINAL_HOST.pid],+ ['foreign.dmp', 'no identifying addon loaded', null],+ ]);+ expect(facts.processesBeforeQuit).toEqual([TERMINAL_HOST, PROJECT_SERVER]);+ });++ test('attaches nothing when the quit wrote no dump', async () => {+ const fixture = windowsFixture();+ const sink = recorder();++ const verdict = await collectCrashDumps(fixture.watch(), OBSERVATION, sink);++ expect(verdict.findings).toEqual([]);+ expect(sink.attached).toEqual([]);+ });++ describe('a crash dump found on one attempt of a test', () => {+ function writeAppCrashDump(fixture: CrashpadFixture): void {+ fixture.writeDump(+ 'reports/app-crash.dmp',+ utilityDump(fixture.mainModule, [PARCEL_WATCHER_ADDON], {+ miscInfo: { processId: PROJECT_SERVER.pid },+ }),+ QUIT_REQUESTED_AT_MS + 344,+ );+ }++ test('fails every later attempt of that test with the recorded finding', async () => {+ const fixture = windowsFixture();+ const watch = fixture.watch();+ writeAppCrashDump(fixture);+ const outputDir = verdictOutputDir();++ const verdict = await collectCrashDumps(+ watch,+ OBSERVATION,+ recorder('restart-test', outputDir),+ );++ expect(verdict.crashes).toHaveLength(1);+ for (const laterAttempt of [1, 2]) {+ expect(+ () => failIfEarlierAttemptFoundCrashDump(recorder('restart-test', outputDir)),+ `attempt ${laterAttempt}`,+ ).toThrow(verdict.headline);+ }+ });++ test('still fails later attempts when its record cannot be read', async () => {+ const fixture = windowsFixture();+ const watch = fixture.watch();+ writeAppCrashDump(fixture);+ const outputDir = verdictOutputDir();+ await collectCrashDumps(watch, OBSERVATION, recorder('restart-test', outputDir));+ const records = readdirSync(outputDir, { recursive: true, withFileTypes: true }).filter(+ (entry) => entry.isFile(),+ );+ expect(records).not.toEqual([]);+ for (const record of records) {+ const recordPath = join(record.parentPath, record.name);+ rmSync(recordPath);+ mkdirSync(recordPath);+ }++ expect(() => failIfEarlierAttemptFoundCrashDump(recorder('restart-test', outputDir))).toThrow(+ /EISDIR/,+ );+ });++ test('leaves later attempts free to pass when the attempt found no dump', async () => {+ const fixture = windowsFixture();+ const outputDir = verdictOutputDir();++ await collectCrashDumps(fixture.watch(), OBSERVATION, recorder('restart-test', outputDir));++ expect(() =>+ failIfEarlierAttemptFoundCrashDump(recorder('restart-test', outputDir)),+ ).not.toThrow();+ });++ test('never reaches another test that shares the output directory', async () => {+ const fixture = windowsFixture();+ const watch = fixture.watch();+ writeAppCrashDump(fixture);+ const outputDir = verdictOutputDir();++ await collectCrashDumps(watch, OBSERVATION, recorder('clean-quit-1', outputDir));++ expect(() =>+ failIfEarlierAttemptFoundCrashDump(recorder('clean-quit-2', outputDir)),+ ).not.toThrow();+ expect(() =>+ failIfEarlierAttemptFoundCrashDump(recorder('clean-quit-1', outputDir)),+ ).toThrow();+ });++ test('does not stick when the only dump is foreign', async () => {+ const fixture = windowsFixture();+ const watch = fixture.watch();+ fixture.writeDump(+ 'reports/foreign.dmp',+ buildMinidump(['C:\\Program Files\\PowerShell\\7\\pwsh.exe']),+ QUIT_REQUESTED_AT_MS + 8,+ );+ const outputDir = verdictOutputDir();++ const verdict = await collectCrashDumps(+ watch,+ OBSERVATION,+ recorder('restart-test', outputDir),+ );++ expect(verdict.findings).toHaveLength(1);+ expect(verdict.crashes).toEqual([]);+ expect(() =>+ failIfEarlierAttemptFoundCrashDump(recorder('restart-test', outputDir)),+ ).not.toThrow();+ });+ });+});++describe('runningAppProcesses', () => {+ const table = (read: ProcessTableRead) => (): ProcessTableRead => read;++ test('reads the Windows process table and keeps only the app processes still listed', () => {+ const tasklist = [+ '"System Idle Process","0","Services","0","8 K"',+ `"electron.exe","${TERMINAL_HOST.pid}","Console","1","41,220 K"`,+ '"pwsh.exe","9999","Console","1","80,100 K"',+ ].join('\r\n');++ expect(+ runningAppProcesses([TERMINAL_HOST, PROJECT_SERVER], {+ platform: 'win32',+ read: table({ status: 0, stdout: tasklist }),+ }),+ ).toEqual([TERMINAL_HOST]);+ });++ test('ps finding none of the pids means every app process has exited', () => {+ expect(+ runningAppProcesses([TERMINAL_HOST, PROJECT_SERVER], {+ platform: 'linux',+ read: table({ status: 1, stdout: '' }),+ }),+ ).toEqual([]);+ });++ test('a process table that cannot be read leaves every app process counted as running', () => {+ expect(+ runningAppProcesses([TERMINAL_HOST, PROJECT_SERVER], {+ platform: 'win32',+ read: table({ status: null, stdout: '' }),+ }),+ ).toEqual([TERMINAL_HOST, PROJECT_SERVER]);+ });++ test('a Windows process table that exits 0 with no row it can parse leaves every app process counted as running', () => {+ for (const stdout of ['', 'INFO: No tasks are running which match the specified criteria.']) {+ expect(+ runningAppProcesses([TERMINAL_HOST, PROJECT_SERVER], {+ platform: 'win32',+ read: table({ status: 0, stdout }),+ }),+ ).toEqual([TERMINAL_HOST, PROJECT_SERVER]);+ }+ });++ test('the real process table lists this process and not a child that already exited', () => {+ const exited = spawnSync(process.execPath, ['-e', ''], { encoding: 'utf8' });+ expect(exited.status).toBe(0);+ const self: AppProcess = { ...TERMINAL_HOST, pid: process.pid };+ const gone: AppProcess = { ...PROJECT_SERVER, pid: exited.pid };++ expect(runningAppProcesses([self, gone])).toEqual([self]);+ });+});diff --git a/packages/desktop/tests/smoke/_helpers/crash-dumps.ts b/packages/desktop/tests/smoke/_helpers/crash-dumps.tsnew file mode 100644index 000000000..d64b166dd--- /dev/null+++ b/packages/desktop/tests/smoke/_helpers/crash-dumps.ts@@ -0,0 +1,734 @@+import { spawnSync } from 'node:child_process';+import {+ type Dirent,+ mkdirSync,+ readdirSync,+ readFileSync,+ statSync,+ writeFileSync,+} from 'node:fs';+import { join } from 'node:path';+import type { ElectronApplication, TestInfo } from '@playwright/test';+import { appBundleRootFromExecutable } from '../../../src/main/bundle-paths.ts';+import {+ classifyMinidumpCrashKind,+ classifyMinidumpOwnership,+ type MinidumpCrashKind,+ type MinidumpOwnership,+} from '../../../src/main/minidump-ownership.ts';++const MINIDUMP_SIGNATURE = 0x504d_444d;+const HEADER_BYTES = 32;+const HEADER_STREAM_COUNT_OFFSET = 8;+const HEADER_DIRECTORY_RVA_OFFSET = 12;+const HEADER_TIME_DATE_STAMP_OFFSET = 20;+const DIRECTORY_ENTRY_BYTES = 12;+const DIRECTORY_ENTRY_SIZE_OFFSET = 4;+const DIRECTORY_ENTRY_RVA_OFFSET = 8;+const MODULE_LIST_STREAM_TYPE = 4;+const EXCEPTION_STREAM_TYPE = 6;+const MISC_INFO_STREAM_TYPE = 15;+const CRASHPAD_INFO_STREAM_TYPE = 0x4350_0001;+const MODULE_RECORD_BYTES = 108;+const MODULE_BASE_OFFSET = 0;+const MODULE_SIZE_OFFSET = 8;+const MODULE_NAME_RVA_OFFSET = 20;+const EXCEPTION_THREAD_ID_OFFSET = 0;+const EXCEPTION_CODE_OFFSET = 8;+const EXCEPTION_FLAGS_OFFSET = 12;+const EXCEPTION_ADDRESS_OFFSET = 24;+const MISC_INFO_MIN_BYTES = 24;+const MISC_INFO_FLAGS_OFFSET = 4;+const MISC_INFO_PROCESS_ID_OFFSET = 8;+const MISC_INFO_PROCESS_CREATE_TIME_OFFSET = 12;+const MISC_INFO_PROCESS_ID_FLAG = 0x1;+const MISC_INFO_PROCESS_TIMES_FLAG = 0x2;+const CRASHPAD_INFO_SIMPLE_ANNOTATIONS_SIZE_OFFSET = 36;+const CRASHPAD_INFO_SIMPLE_ANNOTATIONS_RVA_OFFSET = 40;+const CRASHPAD_INFO_MODULE_LIST_SIZE_OFFSET = 44;+const CRASHPAD_INFO_MODULE_LIST_RVA_OFFSET = 48;+const SIMPLE_ANNOTATION_ENTRY_BYTES = 8;+const MODULE_LINK_BYTES = 12;+const MODULE_LINK_RVA_OFFSET = 8;+const MODULE_CRASHPAD_INFO_BYTES = 28;+const MODULE_ANNOTATION_OBJECTS_SIZE_OFFSET = 20;+const MODULE_ANNOTATION_OBJECTS_RVA_OFFSET = 24;+const ANNOTATION_OBJECT_BYTES = 12;+const ANNOTATION_OBJECT_TYPE_OFFSET = 4;+const ANNOTATION_OBJECT_VALUE_RVA_OFFSET = 8;+const ANNOTATION_TYPE_STRING = 1;++const MAX_DUMP_BYTES = 512 * 1024 * 1024;+const MAX_STREAMS = 4096;+const MAX_MODULES = 4096;+const MAX_MODULE_NAME_BYTES = 8192;+const MAX_ANNOTATIONS = 1024;+const MAX_ANNOTATION_BYTES = 1024;+const DUMP_SCAN_DEPTH = 4;+const DESCRIBED_ANNOTATIONS = 40;+const DESCRIBED_ANNOTATION_VALUE_CHARS = 60;+const PROCESS_TABLE_READ_TIMEOUT_MS = 10_000;++const WINDOWS_EXCEPTION_NAMES: ReadonlyMap<number, string> = new Map([+ [0x8000_0003, 'EXCEPTION_BREAKPOINT'],+ [0xc000_0005, 'EXCEPTION_ACCESS_VIOLATION'],+ [0xc000_001d, 'EXCEPTION_ILLEGAL_INSTRUCTION'],+ [0xc000_00fd, 'EXCEPTION_STACK_OVERFLOW'],+ [0xc000_0374, 'STATUS_HEAP_CORRUPTION'],+ [0xc000_0409, 'STATUS_STACK_BUFFER_OVERRUN'],+ [0xe06d_7363, 'MSVC C++ exception'],+]);++const NODE_PTY_HOST_ADDONS = new Set(['conpty.node', 'pty.node']);+const NODE_PTY_CONSOLE_LIST_ADDON = 'conpty_console_list.node';++export interface LoadedModule {+ path: string;+ base: bigint;+ size: number;+}++export interface CrashDumpException {+ code: number;+ flags: number;+ address: bigint;+ threadId: number;+}++export interface CrashDumpAnnotation {+ key: string;+ value: string;+ source: 'simple' | 'module';+}++export interface CrashDumpFacts {+ modules: readonly LoadedModule[];+ exception: CrashDumpException | null;+ processId: number | null;+ processCreatedAtSec: number | null;+ writtenAtSec: number | null;+ annotations: readonly CrashDumpAnnotation[];+ unreadable: string | null;+}++export interface CrashDumpWatch {+ dir: string;+ appBundleRoot: string;+ platform: NodeJS.Platform;+ baseline: ReadonlyMap<string, number>;+}++export interface AppProcess {+ pid: number;+ type: string;+ serviceName: string | null;+ name: string | null;+ creationTime: number | null;+}++export interface QuitObservation {+ processes: readonly AppProcess[];+ quitRequestedAtMs: number;+}++export interface CrashDumpFinding {+ path: string;+ mtimeMs: number;+ ownership: MinidumpOwnership;+ crashKind: MinidumpCrashKind | null;+ facts: CrashDumpFacts;+ countsAsCrash: boolean;+}++export interface CrashDumpVerdict {+ findings: readonly CrashDumpFinding[];+ crashes: readonly CrashDumpFinding[];+ headline: string;+ lines: readonly string[];+}++export interface ProcessTableRead {+ status: number | null;+ stdout: string;+}++export type ProcessTableReader = (file: string, args: readonly string[]) => ProcessTableRead;++export type CrashDumpAttemptInfo = Pick<TestInfo, 'testId'> & {+ project: Pick<TestInfo['project'], 'outputDir'>;+};++export type CrashDumpTestInfo = Pick<TestInfo, 'attach'> & CrashDumpAttemptInfo;++function crashDumpVerdictDir(testInfo: CrashDumpAttemptInfo): string {+ return join(testInfo.project.outputDir, 'crash-dump-verdicts');+}++function crashDumpVerdictFile(testInfo: CrashDumpAttemptInfo): string {+ return join(crashDumpVerdictDir(testInfo), `${testInfo.testId}.txt`);+}++function recordCrashDumpVerdict(testInfo: CrashDumpAttemptInfo, verdict: CrashDumpVerdict): void {+ mkdirSync(crashDumpVerdictDir(testInfo), { recursive: true });+ writeFileSync(crashDumpVerdictFile(testInfo), [verdict.headline, ...verdict.lines].join('\n'));+}++export function failIfEarlierAttemptFoundCrashDump(testInfo: CrashDumpAttemptInfo): void {+ let recorded: string;+ try {+ recorded = readFileSync(crashDumpVerdictFile(testInfo), 'utf8');+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;+ throw error;+ }+ throw new Error(+ `an earlier attempt of this test found a crash dump from the app, so no retry of it can pass: ${recorded}`,+ );+}++class DumpBytes {+ readonly #bytes: Buffer;++ constructor(bytes: Buffer) {+ this.#bytes = bytes;+ }++ u16(at: number): number | null {+ return at >= 0 && at + 2 <= this.#bytes.length ? this.#bytes.readUInt16LE(at) : null;+ }++ u32(at: number): number | null {+ return at >= 0 && at + 4 <= this.#bytes.length ? this.#bytes.readUInt32LE(at) : null;+ }++ u64(at: number): bigint | null {+ return at >= 0 && at + 8 <= this.#bytes.length ? this.#bytes.readBigUInt64LE(at) : null;+ }++ slice(at: number, length: number): Buffer | null {+ return at >= 0 && length >= 0 && at + length <= this.#bytes.length+ ? this.#bytes.subarray(at, at + length)+ : null;+ }++ utf16String(rva: number): string | null {+ const byteLength = this.u32(rva);+ if (byteLength === null || byteLength === 0 || byteLength % 2 !== 0) return null;+ if (byteLength > MAX_MODULE_NAME_BYTES) return null;+ return this.slice(rva + 4, byteLength)?.toString('utf16le') ?? null;+ }++ utf8String(rva: number): string | null {+ if (rva === 0) return null;+ const byteLength = this.u32(rva);+ if (byteLength === null || byteLength > MAX_ANNOTATION_BYTES) return null;+ return this.slice(rva + 4, byteLength)?.toString('utf8') ?? null;+ }+}++function emptyFacts(unreadable: string): CrashDumpFacts {+ return {+ modules: [],+ exception: null,+ processId: null,+ processCreatedAtSec: null,+ writtenAtSec: null,+ annotations: [],+ unreadable,+ };+}++function readModules(dump: DumpBytes, rva: number | undefined): LoadedModule[] {+ if (rva === undefined) return [];+ const count = dump.u32(rva);+ if (count === null) return [];+ const modules: LoadedModule[] = [];+ for (let index = 0; index < Math.min(count, MAX_MODULES); index += 1) {+ const at = rva + 4 + index * MODULE_RECORD_BYTES;+ const base = dump.u64(at + MODULE_BASE_OFFSET);+ const size = dump.u32(at + MODULE_SIZE_OFFSET);+ const nameRva = dump.u32(at + MODULE_NAME_RVA_OFFSET);+ if (base === null || size === null || nameRva === null) break;+ const path = dump.utf16String(nameRva);+ if (path !== null) modules.push({ path, base, size });+ }+ return modules;+}++function readException(dump: DumpBytes, rva: number | undefined): CrashDumpException | null {+ if (rva === undefined) return null;+ const threadId = dump.u32(rva + EXCEPTION_THREAD_ID_OFFSET);+ const code = dump.u32(rva + EXCEPTION_CODE_OFFSET);+ const flags = dump.u32(rva + EXCEPTION_FLAGS_OFFSET);+ const address = dump.u64(rva + EXCEPTION_ADDRESS_OFFSET);+ if (threadId === null || code === null || flags === null || address === null) return null;+ return { code, flags, address, threadId };+}++function readMiscInfo(+ dump: DumpBytes,+ rva: number | undefined,+): { processId: number | null; processCreatedAtSec: number | null } {+ const none = { processId: null, processCreatedAtSec: null };+ if (rva === undefined) return none;+ const size = dump.u32(rva);+ const flags = dump.u32(rva + MISC_INFO_FLAGS_OFFSET);+ if (size === null || size < MISC_INFO_MIN_BYTES || flags === null) return none;+ const processId = dump.u32(rva + MISC_INFO_PROCESS_ID_OFFSET);+ const createdAt = dump.u32(rva + MISC_INFO_PROCESS_CREATE_TIME_OFFSET);+ return {+ processId: (flags & MISC_INFO_PROCESS_ID_FLAG) !== 0 ? processId : null,+ processCreatedAtSec: (flags & MISC_INFO_PROCESS_TIMES_FLAG) !== 0 ? createdAt : null,+ };+}++function readSimpleAnnotations(dump: DumpBytes, infoRva: number): CrashDumpAnnotation[] {+ const size = dump.u32(infoRva + CRASHPAD_INFO_SIMPLE_ANNOTATIONS_SIZE_OFFSET);+ const rva = dump.u32(infoRva + CRASHPAD_INFO_SIMPLE_ANNOTATIONS_RVA_OFFSET);+ if (size === null || rva === null || rva === 0) return [];+ const count = dump.u32(rva);+ if (count === null || count > MAX_ANNOTATIONS) return [];+ if (size < 4 + count * SIMPLE_ANNOTATION_ENTRY_BYTES) return [];+ const annotations: CrashDumpAnnotation[] = [];+ for (let index = 0; index < count; index += 1) {+ const at = rva + 4 + index * SIMPLE_ANNOTATION_ENTRY_BYTES;+ const keyRva = dump.u32(at);+ const valueRva = dump.u32(at + 4);+ if (keyRva === null || valueRva === null) break;+ const key = dump.utf8String(keyRva);+ const value = dump.utf8String(valueRva);+ if (key !== null && value !== null) annotations.push({ key, value, source: 'simple' });+ }+ return annotations;+}++function readModuleAnnotationObjects(dump: DumpBytes, infoRva: number): CrashDumpAnnotation[] {+ const size = dump.u32(infoRva + CRASHPAD_INFO_MODULE_LIST_SIZE_OFFSET);+ const rva = dump.u32(infoRva + CRASHPAD_INFO_MODULE_LIST_RVA_OFFSET);+ if (size === null || rva === null || rva === 0) return [];+ const linkCount = dump.u32(rva);+ if (linkCount === null || linkCount > MAX_MODULES) return [];+ if (size < 4 + linkCount * MODULE_LINK_BYTES) return [];+ const annotations: CrashDumpAnnotation[] = [];+ let budget = MAX_ANNOTATIONS;+ for (let link = 0; link < linkCount && budget > 0; link += 1) {+ const moduleInfoRva = dump.u32(rva + 4 + link * MODULE_LINK_BYTES + MODULE_LINK_RVA_OFFSET);+ if (moduleInfoRva === null || dump.slice(moduleInfoRva, MODULE_CRASHPAD_INFO_BYTES) === null) {+ continue;+ }+ const listSize = dump.u32(moduleInfoRva + MODULE_ANNOTATION_OBJECTS_SIZE_OFFSET);+ const listRva = dump.u32(moduleInfoRva + MODULE_ANNOTATION_OBJECTS_RVA_OFFSET);+ if (listSize === null || listRva === null || listRva === 0) continue;+ const objectCount = dump.u32(listRva);+ if (objectCount === null || objectCount > MAX_ANNOTATIONS) continue;+ if (listSize < 4 + objectCount * ANNOTATION_OBJECT_BYTES) continue;+ for (let index = 0; index < objectCount && budget > 0; index += 1) {+ budget -= 1;+ const at = listRva + 4 + index * ANNOTATION_OBJECT_BYTES;+ if (dump.u16(at + ANNOTATION_OBJECT_TYPE_OFFSET) !== ANNOTATION_TYPE_STRING) continue;+ const nameRva = dump.u32(at);+ const valueRva = dump.u32(at + ANNOTATION_OBJECT_VALUE_RVA_OFFSET);+ if (nameRva === null || valueRva === null) continue;+ const key = dump.utf8String(nameRva);+ const value = dump.utf8String(valueRva);+ if (key !== null && value !== null) annotations.push({ key, value, source: 'module' });+ }+ }+ return annotations;+}++export function readCrashDumpFacts(dumpPath: string): CrashDumpFacts {+ let bytes: Buffer;+ try {+ if (statSync(dumpPath).size > MAX_DUMP_BYTES) return emptyFacts('larger than the reader bound');+ bytes = readFileSync(dumpPath);+ } catch (error) {+ return emptyFacts(`unreadable file: ${error instanceof Error ? error.message : String(error)}`);+ }+ const dump = new DumpBytes(bytes);+ if (bytes.length < HEADER_BYTES || dump.u32(0) !== MINIDUMP_SIGNATURE) {+ return emptyFacts('no minidump signature');+ }+ const streamCount = dump.u32(HEADER_STREAM_COUNT_OFFSET) ?? 0;+ const directoryRva = dump.u32(HEADER_DIRECTORY_RVA_OFFSET) ?? 0;+ if (streamCount === 0 || streamCount > MAX_STREAMS) return emptyFacts('no stream directory');+ const streams = new Map<number, { rva: number; size: number }>();+ for (let index = 0; index < streamCount; index += 1) {+ const at = directoryRva + index * DIRECTORY_ENTRY_BYTES;+ const type = dump.u32(at);+ const size = dump.u32(at + DIRECTORY_ENTRY_SIZE_OFFSET);+ const rva = dump.u32(at + DIRECTORY_ENTRY_RVA_OFFSET);+ if (type === null || size === null || rva === null) break;+ if (!streams.has(type)) streams.set(type, { rva, size });+ }+ const crashpadInfoRva = streams.get(CRASHPAD_INFO_STREAM_TYPE)?.rva;+ const misc = readMiscInfo(dump, streams.get(MISC_INFO_STREAM_TYPE)?.rva);+ return {+ modules: readModules(dump, streams.get(MODULE_LIST_STREAM_TYPE)?.rva),+ exception: readException(dump, streams.get(EXCEPTION_STREAM_TYPE)?.rva),+ processId: misc.processId,+ processCreatedAtSec: misc.processCreatedAtSec,+ writtenAtSec: dump.u32(HEADER_TIME_DATE_STAMP_OFFSET) || null,+ annotations:+ crashpadInfoRva === undefined+ ? []+ : [+ ...readSimpleAnnotations(dump, crashpadInfoRva),+ ...readModuleAnnotationObjects(dump, crashpadInfoRva),+ ],+ unreadable: null,+ };+}++function pathSegments(path: string): string[] {+ return path.split(/[\\/]+/).filter((segment) => segment !== '');+}++function fileNameOf(path: string): string {+ return pathSegments(path).at(-1) ?? path;+}++export function packageOfModule(path: string): string | null {+ const segments = pathSegments(path);+ const nodeModules = segments.lastIndexOf('node_modules');+ if (nodeModules === -1) return null;+ const name = segments[nodeModules + 1];+ if (name === undefined) return null;+ if (!name.startsWith('@')) return name;+ const scoped = segments[nodeModules + 2];+ return scoped === undefined ? null : `${name}/${scoped}`;+}++export function nativeAddonsOf(facts: CrashDumpFacts): string[] {+ const addons: string[] = [];+ for (const module of facts.modules) {+ const file = fileNameOf(module.path);+ const owner = packageOfModule(module.path);+ const isAddon = file.toLowerCase().endsWith('.node');+ const isPackagedLibrary = owner !== null && file.toLowerCase().endsWith('.dll');+ if (!isAddon && !isPackagedLibrary) continue;+ addons.push(owner === null ? file : `${owner}/${file}`);+ }+ return addons;+}++export function processRoleOf(facts: CrashDumpFacts): string {+ const loaded = facts.modules.map((module) => ({+ file: fileNameOf(module.path).toLowerCase(),+ owner: packageOfModule(module.path),+ }));+ const fromNodePty = loaded.filter((module) => module.owner === 'node-pty');+ if (fromNodePty.some((module) => NODE_PTY_HOST_ADDONS.has(module.file))) {+ return 'pty-host (node-pty terminal addon loaded)';+ }+ if (fromNodePty.some((module) => module.file === NODE_PTY_CONSOLE_LIST_ADDON)) {+ return 'node-pty console-list agent';+ }+ if (loaded.some((module) => module.owner?.startsWith('@parcel/watcher') === true)) {+ return 'project server (@parcel/watcher addon loaded)';+ }+ return 'no identifying addon loaded';+}++export function faultingModuleOf(facts: CrashDumpFacts): LoadedModule | null {+ const address = facts.exception?.address;+ if (address === undefined) return null;+ return (+ facts.modules.find(+ (module) => address >= module.base && address < module.base + BigInt(module.size),+ ) ?? null+ );+}++function hex(value: number | bigint, width = 8): string {+ return `0x${value.toString(16).toUpperCase().padStart(width, '0')}`;+}++export function exceptionNameOf(code: number, platform: NodeJS.Platform): string | null {+ return platform === 'win32' ? (WINDOWS_EXCEPTION_NAMES.get(code) ?? null) : null;+}++function printable(value: string, limit: number): string {+ const cleaned = value.replace(/[^\x20-\x7e]/g, '?');+ return cleaned.length > limit ? `${cleaned.slice(0, limit)}...` : cleaned;+}++function processIdentity(finding: CrashDumpFinding, observation: QuitObservation): string {+ const pid = finding.facts.processId;+ if (pid === null) return 'pid unknown (no process id in the dump)';+ const known = observation.processes.find((entry) => entry.pid === pid);+ if (known === undefined) return `pid ${pid} (not among the app processes listed before quit)`;+ const label = known.serviceName ?? known.name;+ return label === null ? `pid ${pid} ${known.type}` : `pid ${pid} ${known.type} "${label}"`;+}++function exceptionSummary(finding: CrashDumpFinding, platform: NodeJS.Platform): string {+ const exception = finding.facts.exception;+ if (exception === null) return 'no exception record';+ const name = exceptionNameOf(exception.code, platform);+ const faulting = faultingModuleOf(finding.facts);+ return [+ `exception ${hex(exception.code)}${name === null ? '' : ` ${name}`}`,+ `at ${hex(exception.address, 12)}`,+ faulting === null ? 'outside every listed module' : `in ${fileNameOf(faulting.path)}`,+ ].join(' ');+}++function timingSummary(finding: CrashDumpFinding, observation: QuitObservation): string {+ const deltaMs = Math.round(finding.mtimeMs - observation.quitRequestedAtMs);+ return deltaMs >= 0+ ? `written ${deltaMs} ms after quit was requested`+ : `written ${-deltaMs} ms before quit was requested`;+}++function identify(+ finding: CrashDumpFinding,+ observation: QuitObservation,+ platform: NodeJS.Platform,+): string {+ return [+ processIdentity(finding, observation),+ processRoleOf(finding.facts),+ exceptionSummary(finding, platform),+ timingSummary(finding, observation),+ ].join('; ');+}++export function describeCrashDump(+ finding: CrashDumpFinding,+ observation: QuitObservation,+ platform: NodeJS.Platform,+): string {+ const facts = finding.facts;+ const processType = facts.annotations.find((entry) => entry.key === 'process_type')?.value;+ const mainModule = facts.modules[0];+ const addons = nativeAddonsOf(facts);+ const annotations = facts.annotations+ .slice(0, DESCRIBED_ANNOTATIONS)+ .map(+ (entry) =>+ `${printable(entry.key, DESCRIBED_ANNOTATION_VALUE_CHARS)}=${printable(entry.value, DESCRIBED_ANNOTATION_VALUE_CHARS)}`,+ );+ return [+ fileNameOf(finding.path),+ identify(finding, observation, platform),+ `process_type=${processType === undefined ? '(absent)' : printable(processType, DESCRIBED_ANNOTATION_VALUE_CHARS)}`,+ `native addons: ${addons.length === 0 ? '(none)' : addons.join(', ')}`,+ `main module ${mainModule === undefined ? '(none)' : fileNameOf(mainModule.path)}`,+ `ownership ${finding.ownership}, crash kind ${finding.crashKind ?? 'unread'}`,+ `${facts.modules.length} modules`,+ ...(facts.unreadable === null ? [] : [`unreadable: ${facts.unreadable}`]),+ `annotations: ${annotations.length === 0 ? '(none)' : annotations.join(', ')}`,+ ].join('; ');+}++function listCrashDumpFiles(dir: string, depth: number, out: Map<string, number>): void {+ let entries: Dirent[];+ try {+ entries = readdirSync(dir, { withFileTypes: true });+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;+ throw error;+ }+ for (const entry of entries) {+ const entryPath = join(dir, entry.name);+ if (entry.isDirectory()) {+ if (depth > 0) listCrashDumpFiles(entryPath, depth - 1, out);+ continue;+ }+ if (!entry.name.toLowerCase().endsWith('.dmp')) continue;+ try {+ out.set(entryPath, statSync(entryPath).mtimeMs);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }+ }+}++function crashDumpFiles(dir: string): Map<string, number> {+ const out = new Map<string, number>();+ listCrashDumpFiles(dir, DUMP_SCAN_DEPTH, out);+ return out;+}++export function crashDumpWatchFor(+ dir: string,+ executablePath: string,+ platform: NodeJS.Platform = process.platform,+): CrashDumpWatch {+ return {+ dir,+ appBundleRoot: appBundleRootFromExecutable(executablePath, platform),+ platform,+ baseline: crashDumpFiles(dir),+ };+}++export async function watchCrashDumps(app: ElectronApplication): Promise<CrashDumpWatch> {+ const paths = await app.evaluate(({ app: electronApp }) => ({+ crashDumps: electronApp.getPath('crashDumps'),+ executable: electronApp.getPath('exe'),+ }));+ return crashDumpWatchFor(paths.crashDumps, paths.executable);+}++export async function observeQuit(app: ElectronApplication): Promise<QuitObservation> {+ const processes = await app.evaluate(({ app: electronApp }) =>+ electronApp.getAppMetrics().map((metric) => ({+ pid: metric.pid,+ type: metric.type,+ serviceName: metric.serviceName ?? null,+ name: metric.name ?? null,+ creationTime: metric.creationTime,+ })),+ );+ return { processes, quitRequestedAtMs: Date.now() };+}++export function crashDumpsSince(watch: CrashDumpWatch): CrashDumpFinding[] {+ const findings: CrashDumpFinding[] = [];+ for (const [path, mtimeMs] of crashDumpFiles(watch.dir)) {+ const before = watch.baseline.get(path);+ if (before !== undefined && before >= mtimeMs) continue;+ const ownership = classifyMinidumpOwnership(path, watch.appBundleRoot);+ const crashKind = ownership === 'ours' ? classifyMinidumpCrashKind(path, watch.platform) : null;+ findings.push({+ path,+ mtimeMs,+ ownership,+ crashKind,+ facts: readCrashDumpFacts(path),+ countsAsCrash: ownership !== 'foreign' && crashKind !== 'non-crash',+ });+ }+ return findings.sort((a, b) => a.mtimeMs - b.mtimeMs);+}++export function crashDumpVerdict(+ findings: readonly CrashDumpFinding[],+ observation: QuitObservation,+ platform: NodeJS.Platform = process.platform,+): CrashDumpVerdict {+ const crashes = findings.filter((finding) => finding.countsAsCrash);+ const [first] = crashes;+ const headline =+ first === undefined+ ? 'the quit left no crash dump from the app'+ : `the quit left ${crashes.length} crash dump(s) from the app; first: ${identify(first, observation, platform)}`;+ return {+ findings,+ crashes,+ headline,+ lines: crashes.map((finding) => describeCrashDump(finding, observation, platform)),+ };+}++function factsForAttachment(finding: CrashDumpFinding): Record<string, unknown> {+ const { facts } = finding;+ return {+ file: fileNameOf(finding.path),+ mtime: new Date(finding.mtimeMs).toISOString(),+ ownership: finding.ownership,+ crashKind: finding.crashKind,+ countsAsCrash: finding.countsAsCrash,+ processId: facts.processId,+ processCreatedAtSec: facts.processCreatedAtSec,+ writtenAtSec: facts.writtenAtSec,+ role: processRoleOf(facts),+ exception:+ facts.exception === null+ ? null+ : {+ code: hex(facts.exception.code),+ flags: hex(facts.exception.flags),+ address: hex(facts.exception.address, 12),+ threadId: facts.exception.threadId,+ faultingModule: faultingModuleOf(facts)?.path ?? null,+ },+ annotations: facts.annotations,+ modules: facts.modules.map((module) => ({+ path: module.path,+ base: hex(module.base, 12),+ size: module.size,+ })),+ unreadable: facts.unreadable,+ };+}++export async function collectCrashDumps(+ watch: CrashDumpWatch,+ observation: QuitObservation,+ testInfo: CrashDumpTestInfo,+): Promise<CrashDumpVerdict> {+ const verdict = crashDumpVerdict(crashDumpsSince(watch), observation, watch.platform);+ if (verdict.crashes.length > 0) recordCrashDumpVerdict(testInfo, verdict);+ if (verdict.findings.length === 0) return verdict;+ await testInfo.attach('crash-dump-facts', {+ body: JSON.stringify(+ {+ headline: verdict.headline,+ processesBeforeQuit: observation.processes,+ quitRequestedAt: new Date(observation.quitRequestedAtMs).toISOString(),+ dumps: verdict.findings.map(factsForAttachment),+ },+ null,+ 2,+ ),+ contentType: 'application/json',+ });+ for (const [index, finding] of verdict.crashes.entries()) {+ await testInfo.attach(`crash-dump-${index + 1}`, {+ path: finding.path,+ contentType: 'application/octet-stream',+ });+ }+ return verdict;+}++function readProcessTable(file: string, args: readonly string[]): ProcessTableRead {+ const result = spawnSync(file, [...args], {+ encoding: 'utf8',+ timeout: PROCESS_TABLE_READ_TIMEOUT_MS,+ windowsHide: true,+ });+ return { status: result.status, stdout: result.stdout ?? '' };+}++function listedWindowsPids(stdout: string): Set<number> {+ const listed = new Set<number>();+ for (const line of stdout.split(/\r?\n/)) {+ const match = /^"[^"]*","(\d+)"/.exec(line.trim());+ if (match?.[1] !== undefined) listed.add(Number(match[1]));+ }+ return listed;+}++function listedPosixPids(stdout: string): Set<number> {+ return new Set(+ stdout+ .split(/\s+/)+ .filter((token) => /^\d+$/.test(token))+ .map(Number),+ );+}++export function runningAppProcesses(+ processes: readonly AppProcess[],+ options: { platform?: NodeJS.Platform; read?: ProcessTableReader } = {},+): AppProcess[] {+ const candidates = processes.filter((entry) => Number.isInteger(entry.pid) && entry.pid > 0);+ if (candidates.length === 0) return [];+ const platform = options.platform ?? process.platform;+ const read = options.read ?? readProcessTable;+ if (platform === 'win32') {+ const table = read('tasklist', ['/FO', 'CSV', '/NH']);+ if (table.status !== 0) return candidates;+ const listed = listedWindowsPids(table.stdout);+ if (listed.size === 0) return candidates;+ return candidates.filter((entry) => listed.has(entry.pid));+ }+ const table = read('ps', ['-o', 'pid=', '-p', candidates.map((entry) => entry.pid).join(',')]);+ if (table.status !== 0 && table.status !== 1) return candidates;+ const listed = listedPosixPids(table.stdout);+ return candidates.filter((entry) => listed.has(entry.pid));+}diff --git a/packages/desktop/tests/smoke/terminal-collection-size.json b/packages/desktop/tests/smoke/terminal-collection-size.jsonindex c45fb8519..42df4d453 100644--- a/packages/desktop/tests/smoke/terminal-collection-size.json+++ b/packages/desktop/tests/smoke/terminal-collection-size.json@@ -1,4 +1,4 @@{- "$comment": "Total tests collected by `playwright test tests/smoke/terminal-*.e2e.ts`, skipped ones included. Inkeep runs that collection sharded across parallel Windows CI cells and sums each shard's Playwright JSON stats against this number, so a shard that never ran cannot leave part of the collection unexecuted while every cell reads green. That guard and the workflow driving it live in Inkeep's internal monorepo, so whether a stale number fails anything depends on which checkout you are reading: it does there, and in the public mirror the guard is absent and nothing reads this file. Add or remove a terminal smoke test and this number moves with it either way; the guard prints the observed total when the two disagree.",- "terminalSmokeTestCount": 43+ "$comment": "Total tests collected by `playwright test tests/smoke/terminal-*.e2e.ts` on Windows, skipped ones included. Inkeep runs that collection sharded across parallel Windows CI cells and sums each shard's Playwright JSON stats against this number, so a shard that never ran cannot leave part of the collection unexecuted while every cell reads green. That guard and the workflow driving it live in Inkeep's internal monorepo, so whether a stale number fails anything depends on which checkout you are reading: it does there, and in the public mirror the guard is absent and nothing reads this file. Add or remove a terminal smoke test and this number moves with it either way; the guard prints the observed total when the two disagree.",+ "terminalSmokeTestCount": 93}diff --git a/packages/desktop/tests/smoke/terminal-process-restart.e2e.ts b/packages/desktop/tests/smoke/terminal-process-restart.e2e.tsindex 21e371b78..631cb4af3 100644--- a/packages/desktop/tests/smoke/terminal-process-restart.e2e.ts+++ b/packages/desktop/tests/smoke/terminal-process-restart.e2e.ts@@ -4,6 +4,15 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import type { ElectronApplication, Page } from '@playwright/test';import { _electron as electron } from '@playwright/test';+import {+ type CrashDumpVerdict,+ type CrashDumpWatch,+ collectCrashDumps,+ failIfEarlierAttemptFoundCrashDump,+ observeQuit,+ runningAppProcesses,+ watchCrashDumps,+} from './_helpers/crash-dumps';import { desktopLaunchOptions, resolveDesktopTarget } from './_helpers/launch-desktop';import { waitForWindowByMode } from './_helpers/launch-readiness';import { sumOfDeclaredBoundsMs } from './_helpers/parse-timeouts';@@ -35,6 +44,8 @@ import {const TARGET = resolveDesktopTarget();const ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';const PRIMARY_MODIFIER = process.platform === 'darwin' ? 'Meta' : 'Control';+const QUIT_SAMPLES = process.platform === 'win32' ? 50 : 1;+const SECOND_TAB_LABEL = process.platform === 'win32' ? 'process second' : 'Terminal 2';interface RestartSeed {tmpHome: string;@@ -146,6 +157,34 @@ async function openBareTab(page: Page): Promise<void> {});}+async function expectArrangedTabs(page: Page): Promise<void> {+ await expect(terminalTabs(page)).toHaveText([SECOND_TAB_LABEL, 'process first']);+ await expect(page.getByRole('tab', { name: SECOND_TAB_LABEL })).toHaveAttribute(+ 'aria-selected',+ 'true',+ );+}++async function arrangeTabsInRightColumn(+ page: Page,+ firstTabId: string,+ secondTabId: string,+): Promise<void> {+ await renameTerminalTab(page, terminalTabById(page, firstTabId), 'process first');+ if (process.platform === 'win32') {+ await renameTerminalTab(page, terminalTabById(page, secondTabId), SECOND_TAB_LABEL);+ }+ await terminalTabById(page, secondTabId).click();+ await expect(terminalTabById(page, secondTabId)).toHaveAttribute('aria-selected', 'true');+ await page.locator('section[aria-label="Terminal"]:visible .xterm').click();+ await page.keyboard.press(`${PRIMARY_MODIFIER}+Shift+ArrowLeft`);+ await expectTerminalTabOrder(page, [secondTabId, firstTabId]);+ await expect(terminalTabById(page, secondTabId)).toHaveAttribute('aria-selected', 'true');+ await dispatchRendererMenuAction(page, 'move-terminal');+ await expect(page.locator('#terminal-column')).toBeVisible({ timeout: 10_000 });+ await expectArrangedTabs(page);+}+async function applyPersistedRightTerminalWidth(page: Page, width: number): Promise<number> {await page.evaluate((nextWidth) => {localStorage.setItem('ok-terminal-right-width-v1', String(nextWidth));@@ -178,6 +217,24 @@ async function quitAndWait(app: ElectronApplication, child: ChildProcess): Promiexpect(child.exitCode ?? child.signalCode).not.toBeNull();}+async function quitAndCollectCrashDumps(+ app: ElectronApplication,+ child: ChildProcess,+ dumps: CrashDumpWatch,+): Promise<CrashDumpVerdict> {+ const quit = await observeQuit(app);+ await quitAndWait(app, child);+ await expect+ .configure({ soft: true })+ .poll(() => runningAppProcesses(quit.processes), {+ message:+ 'every process the app ran before quit has exited, so the crash-dump scan is complete',+ timeout: 15_000,+ })+ .toEqual([]);+ return collectCrashDumps(dumps, quit, test.info());+}+test.describe('terminal process restart', () => {test.skip(!ENABLED, 'Set OK_DESKTOP_E2E_SMOKE=1');test.skip(!PTY_PLATFORM_SUPPORTED, PTY_PLATFORM_SKIP_REASON);@@ -187,10 +244,12 @@ test.describe('terminal process restart', () => {captureStderrFor,}) => {test.setTimeout(sumOfDeclaredBoundsMs(test.info()));+ failIfEarlierAttemptFoundCrashDump(test.info());const seed = seedRestartProfile();const firstApp = await launchRestartProfile(seed);captureStderrFor(firstApp, { home: seed.tmpHome });const firstProcess = firstApp.process();+ const firstDumps = await watchCrashDumps(firstApp);const firstPage = await findEditorWindow(firstApp);await setWindowSize(firstApp, firstPage, 1900, 900);await openTerminal(firstPage);@@ -199,31 +258,11 @@ test.describe('terminal process restart', () => {await openBareTab(firstPage);const [, secondTabId] = await terminalTabIds(firstPage);if (secondTabId === undefined) throw new Error('second terminal tab was not created');- await renameTerminalTab(firstPage, terminalTabById(firstPage, firstTabId), 'process first');- const secondLabel = process.platform === 'win32' ? 'process second' : 'Terminal 2';- if (process.platform === 'win32') {- await renameTerminalTab(firstPage, terminalTabById(firstPage, secondTabId), secondLabel);- }- await terminalTabById(firstPage, secondTabId).click();- await expect(terminalTabById(firstPage, secondTabId)).toHaveAttribute('aria-selected', 'true');- await firstPage.locator('section[aria-label="Terminal"]:visible .xterm').click();- await firstPage.keyboard.press(`${PRIMARY_MODIFIER}+Shift+ArrowLeft`);- await expectTerminalTabOrder(firstPage, [secondTabId, firstTabId]);- await expect(terminalTabById(firstPage, secondTabId)).toHaveAttribute('aria-selected', 'true');- await dispatchRendererMenuAction(firstPage, 'move-terminal');- await expect(firstPage.locator('#terminal-column')).toBeVisible({ timeout: 10_000 });- await expect(terminalTabs(firstPage)).toHaveText([secondLabel, 'process first']);- await expect(firstPage.getByRole('tab', { name: secondLabel })).toHaveAttribute(- 'aria-selected',- 'true',- );+ await arrangeTabsInRightColumn(firstPage, firstTabId, secondTabId);const retainedWidth = await applyPersistedRightTerminalWidth(firstPage, 860);- await expect(terminalTabs(firstPage)).toHaveText([secondLabel, 'process first']);- await expect(firstPage.getByRole('tab', { name: secondLabel })).toHaveAttribute(- 'aria-selected',- 'true',- );- await quitAndWait(firstApp, firstProcess);+ await expectArrangedTabs(firstPage);+ const firstQuitDumps = await quitAndCollectCrashDumps(firstApp, firstProcess, firstDumps);+ expect.soft(firstQuitDumps.lines, firstQuitDumps.headline).toEqual([]);const secondApp = await launchRestartProfile(seed);captureStderrFor(secondApp, {@@ -234,13 +273,13 @@ test.describe('terminal process restart', () => {await setWindowSize(secondApp, secondPage, 1900, 900);await expect(secondPage.locator('#terminal-column')).toBeVisible({ timeout: 25_000 });await expect(secondPage.locator('#terminal-dock-panel')).toHaveCount(0);- await expect(terminalTabs(secondPage)).toHaveText([secondLabel, 'process first'], {+ await expect(terminalTabs(secondPage)).toHaveText([SECOND_TAB_LABEL, 'process first'], {timeout: 25_000,});const restoredTail = settleBudget('restored active tab and right Terminal width', {timeout: RAIL_LAYOUT_SETTLE_TIMEOUT_MS,});- await expect(secondPage.getByRole('tab', { name: secondLabel })).toHaveAttribute(+ await expect(secondPage.getByRole('tab', { name: SECOND_TAB_LABEL })).toHaveAttribute('aria-selected','true',{ timeout: restoredTail.remainingMs() },@@ -251,4 +290,32 @@ test.describe('terminal process restart', () => {{ reading: 'width', of: '#terminal-column', budget: restoredTail },);});++ for (let sample = 1; sample <= QUIT_SAMPLES; sample += 1) {+ test(`clean quit ${sample} of ${QUIT_SAMPLES} with two live terminals leaves no crash dump for the next launch`, async ({+ captureStderrFor,+ }) => {+ test.setTimeout(sumOfDeclaredBoundsMs(test.info()));+ failIfEarlierAttemptFoundCrashDump(test.info());+ const seed = seedRestartProfile();+ const app = await launchRestartProfile(seed);+ captureStderrFor(app, { home: seed.tmpHome, cleanupDirs: [seed.tmpHome, seed.projectDir] });+ const appProcess = app.process();+ const dumps = await watchCrashDumps(app);+ // WARN: mirrors the first process of the restart test above+ const page = await findEditorWindow(app);+ await setWindowSize(app, page, 1900, 900);+ await openTerminal(page);+ const [firstTabId] = await terminalTabIds(page);+ if (firstTabId === undefined) throw new Error('first terminal tab was not created');+ await openBareTab(page);+ const [, secondTabId] = await terminalTabIds(page);+ if (secondTabId === undefined) throw new Error('second terminal tab was not created');+ await arrangeTabsInRightColumn(page, firstTabId, secondTabId);+ await applyPersistedRightTerminalWidth(page, 860);+ await expectArrangedTabs(page);+ const quit = await quitAndCollectCrashDumps(app, appProcess, dumps);+ expect(quit.lines, quit.headline).toEqual([]);+ });+ }});diff --git a/packages/server/src/file-watcher-parcel-release.test.ts b/packages/server/src/file-watcher-parcel-release.test.tsnew file mode 100644index 000000000..0bc800351--- /dev/null+++ b/packages/server/src/file-watcher-parcel-release.test.ts@@ -0,0 +1,128 @@+import { mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { type DiskEvent, startWatcher, type WatcherHandle } from './file-watcher.ts';+import {+ forgetNativeSubscriptions,+ type NativeSubscriptionDouble,+ nativeSubscriptionOn,+} from './parcel-watcher-double.test-helper.ts';++vi.mock('@parcel/watcher', async () => {+ const { parcelWatcherModule } = await import('./parcel-watcher-double.test-helper.ts');+ return parcelWatcherModule;+});++const POSIX_PLATFORMS = ['linux', 'darwin'] as const satisfies readonly NodeJS.Platform[];+const PLATFORMS = ['win32', ...POSIX_PLATFORMS] as const satisfies readonly NodeJS.Platform[];+const LIVENESS = { timeout: 10_000 };++let contentDir: string;++beforeEach(() => {+ forgetNativeSubscriptions();+ contentDir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-parcel-release-')));+});++afterEach(() => {+ rmSync(contentDir, { recursive: true, force: true });+});++interface WatchedContent {+ readonly watcher: WatcherHandle;+ readonly subscription: NativeSubscriptionDouble;+ readonly dispatched: string[];+ readonly rawBatches: (readonly string[])[];+}++function dispatchLabel(event: DiskEvent): string {+ return event.kind === 'create' ? `create ${event.docName}` : event.kind;+}++async function watchContent(platform: NodeJS.Platform): Promise<WatchedContent> {+ const dispatched: string[] = [];+ const rawBatches: (readonly string[])[] = [];+ const watcher = await startWatcher(+ contentDir,+ async (event) => {+ dispatched.push(dispatchLabel(event));+ },+ undefined,+ {+ forceBackend: 'parcel',+ platform,+ onRawBatch: (paths) => {+ rawBatches.push(paths);+ },+ },+ );+ return { watcher, subscription: nativeSubscriptionOn(contentDir), dispatched, rawBatches };+}++function writeDoc(name: string): string {+ const path = join(contentDir, name);+ writeFileSync(path, `# ${name}\n`, 'utf-8');+ return path;+}++async function deliverLiveCreate(watched: WatchedContent): Promise<string> {+ const before = writeDoc('before.md');+ await watched.subscription.deliver([{ type: 'create', path: before }]);+ await vi.waitFor(() => expect(watched.dispatched).toEqual(['create before']), LIVENESS);+ return before;+}++describe('releasing the file watcher on the parcel backend', () => {+ test('on win32, releasing the file watcher never asks the addon to unsubscribe natively', async () => {+ const { watcher, subscription } = await watchContent('win32');++ await watcher.unsubscribe();++ expect(subscription.nativeReleases(), 'native unsubscribe calls').toBe(0);+ });++ test.each(PLATFORMS)(+ 'on %s, a create the addon delivers after the file watcher is released reaches no consumer',+ async (platform) => {+ const watched = await watchContent(platform);+ const before = await deliverLiveCreate(watched);++ await watched.watcher.unsubscribe();+ await watched.subscription.deliver([{ type: 'create', path: writeDoc('after.md') }]);++ expect({ rawBatches: watched.rawBatches, dispatched: watched.dispatched }).toEqual({+ rawBatches: [[before]],+ dispatched: ['create before'],+ });+ },+ );++ test.each(POSIX_PLATFORMS)(+ 'on %s, a create the addon delivers while the native unsubscribe is in flight reaches no consumer',+ async (platform) => {+ const watched = await watchContent(platform);+ const before = await deliverLiveCreate(watched);++ watched.subscription.deliverWhileReleasing([{ type: 'create', path: writeDoc('during.md') }]);+ await watched.watcher.unsubscribe();++ expect(watched.subscription.nativeReleases(), 'native unsubscribe calls').toBe(1);+ expect({ rawBatches: watched.rawBatches, dispatched: watched.dispatched }).toEqual({+ rawBatches: [[before]],+ dispatched: ['create before'],+ });+ },+ );++ test.each(POSIX_PLATFORMS)(+ 'characterization: on %s, releasing the file watcher unsubscribes the addon exactly once',+ async (platform) => {+ const { watcher, subscription } = await watchContent(platform);++ await watcher.unsubscribe();++ expect(subscription.nativeReleases(), 'native unsubscribe calls').toBe(1);+ },+ );+});diff --git a/packages/server/src/file-watcher.ts b/packages/server/src/file-watcher.tsindex 16db67578..2e32235c3 100644--- a/packages/server/src/file-watcher.ts+++ b/packages/server/src/file-watcher.ts@@ -30,6 +30,7 @@ import {extractPageTitle,extractPageType,} from './page-identity.ts';+import { subscribeParcel } from './parcel-subscription.ts';import { toPosix } from './path-utils.ts';import { containsConflictMarkers } from './reconciliation.ts';import { getMeter, withSpan } from './telemetry.ts';@@ -1450,6 +1451,7 @@ async function startParcelWatcher(onDiskEvent: (event: DiskEvent) => Promise<void>,aliasMap: Map<string, string>,onAfterMutation: () => void,+ platform: NodeJS.Platform,onRawBatch?: (absPaths: readonly string[]) => void,discoveredStructuralDirs?: ReadonlySet<string>,): Promise<AsyncSubscription | null> {@@ -1474,7 +1476,8 @@ async function startParcelWatcher(}: undefined;- const subscription = await parcel.subscribe(+ const subscription = await subscribeParcel(+ parcel,contentDir,async (err, events) => {if (err) {@@ -1498,6 +1501,7 @@ async function startParcelWatcher(}},subscribeOpts,+ platform,);return subscription;@@ -1684,6 +1688,7 @@ export async function startWatcher(let subscription: AsyncSubscription;let backend: WatcherBackend;const forceChokidar = process.env.OK_FILE_WATCHER_BACKEND === 'chokidar';+ const platform = opts.platform ?? process.platform;try {const parcelSub =forceChokidar || opts.forceBackend === 'chokidar'@@ -1696,6 +1701,7 @@ export async function startWatcher(onDiskEvent,aliasMap,bumpFileIndexGeneration,+ platform,onRawBatch,structuralIgnoreDirs,);@@ -1714,7 +1720,7 @@ export async function startWatcher(onDiskEvent,aliasMap,bumpFileIndexGeneration,- opts.platform ?? process.platform,+ platform,onRawBatch,);backend = 'chokidar';diff --git a/packages/server/src/head-watcher-parcel-release.test.ts b/packages/server/src/head-watcher-parcel-release.test.tsnew file mode 100644index 000000000..0fc080ef0--- /dev/null+++ b/packages/server/src/head-watcher-parcel-release.test.ts@@ -0,0 +1,117 @@+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { type HeadWatcherHandle, startHeadWatcher } from './head-watcher.ts';+import {+ forgetNativeSubscriptions,+ type NativeSubscriptionDouble,+ nativeSubscriptionOn,+} from './parcel-watcher-double.test-helper.ts';++vi.mock('@parcel/watcher', async () => {+ const { parcelWatcherModule } = await import('./parcel-watcher-double.test-helper.ts');+ return parcelWatcherModule;+});++const POSIX_PLATFORMS = ['linux', 'darwin'] as const satisfies readonly NodeJS.Platform[];+const PLATFORMS = ['win32', ...POSIX_PLATFORMS] as const satisfies readonly NodeJS.Platform[];+const LIVENESS = { timeout: 10_000 };++type HeadWatcherOptions = NonNullable<Parameters<typeof startHeadWatcher>[3]>;+type ParcelHeadWatcherOptions = HeadWatcherOptions & { readonly platform: NodeJS.Platform };++function parcelBackendOn(platform: NodeJS.Platform): ParcelHeadWatcherOptions {+ return { forceBackend: 'parcel', platform };+}++let projectRoot: string;+let gitDir: string;++beforeEach(() => {+ forgetNativeSubscriptions();+ projectRoot = realpathSync(mkdtempSync(join(tmpdir(), 'ok-parcel-head-release-')));+ gitDir = join(projectRoot, '.git');+ mkdirSync(gitDir);+ writeFileSync(join(gitDir, 'HEAD'), 'ref: refs/heads/main\n', 'utf-8');+});++afterEach(() => {+ rmSync(projectRoot, { recursive: true, force: true });+});++interface WatchedHead {+ readonly handle: HeadWatcherHandle;+ readonly subscription: NativeSubscriptionDouble;+ readonly batchTriggers: string[];+}++async function watchHead(platform: NodeJS.Platform): Promise<WatchedHead> {+ const batchTriggers: string[] = [];+ const handle = await startHeadWatcher(+ projectRoot,+ ({ trigger }) => {+ batchTriggers.push(trigger);+ },+ () => {},+ parcelBackendOn(platform),+ );+ return { handle, subscription: nativeSubscriptionOn(gitDir), batchTriggers };+}++function headUpdateEvent(): { type: 'update'; path: string } {+ return { type: 'update', path: join(gitDir, 'HEAD') };+}++async function beginLiveBatch(watched: WatchedHead): Promise<void> {+ await watched.subscription.deliver([headUpdateEvent()]);+ await vi.waitFor(() => expect(watched.batchTriggers).toEqual(['HEAD']), LIVENESS);+}++describe('releasing the HEAD watcher on the parcel backend', () => {+ test('on win32, releasing the HEAD watcher never asks the addon to unsubscribe natively', async () => {+ const { handle, subscription } = await watchHead('win32');++ await handle.unsubscribe();++ expect(subscription.nativeReleases(), 'native unsubscribe calls').toBe(0);+ });++ test.each(PLATFORMS)(+ 'on %s, a HEAD change the addon delivers after the HEAD watcher is released begins no batch',+ async (platform) => {+ const watched = await watchHead(platform);+ await beginLiveBatch(watched);++ await watched.handle.unsubscribe();+ await watched.subscription.deliver([headUpdateEvent()]);++ expect(watched.batchTriggers).toEqual(['HEAD']);+ },+ );++ test.each(POSIX_PLATFORMS)(+ 'on %s, a HEAD change the addon delivers while the native unsubscribe is in flight begins no batch',+ async (platform) => {+ const watched = await watchHead(platform);+ await beginLiveBatch(watched);++ watched.subscription.deliverWhileReleasing([headUpdateEvent()]);+ await watched.handle.unsubscribe();++ expect(watched.subscription.nativeReleases(), 'native unsubscribe calls').toBe(1);+ expect(watched.batchTriggers).toEqual(['HEAD']);+ },+ );++ test.each(POSIX_PLATFORMS)(+ 'characterization: on %s, releasing the HEAD watcher unsubscribes the addon exactly once',+ async (platform) => {+ const { handle, subscription } = await watchHead(platform);++ await handle.unsubscribe();++ expect(subscription.nativeReleases(), 'native unsubscribe calls').toBe(1);+ },+ );+});diff --git a/packages/server/src/head-watcher.ts b/packages/server/src/head-watcher.tsindex 2d15547e3..a2e5ecc0c 100644--- a/packages/server/src/head-watcher.ts+++ b/packages/server/src/head-watcher.ts@@ -3,6 +3,7 @@ import {type GitRepository,} from '@inkeep/open-knowledge-core/git-repository';import { getLogger } from './logger.ts';+import { subscribeParcel } from './parcel-subscription.ts';const log = getLogger('head-watcher');@@ -69,6 +70,7 @@ export function watchedGitFile(rawPath: string): string | null {async function tryStartParcelHeadWatcher(gitDir: string,dispatch: HeadEventDispatch,+ platform: NodeJS.Platform,): Promise<(() => Promise<void>) | null> {let parcel: typeof import('@parcel/watcher');try {@@ -81,13 +83,19 @@ async function tryStartParcelHeadWatcher(return null;}try {- const subscription = await parcel.subscribe(gitDir, (err, events) => {- if (err) {- log.warn({ err }, '[head-watcher] parcel subscription error');- return;- }- for (const event of events) dispatch(event.path);- });+ const subscription = await subscribeParcel(+ parcel,+ gitDir,+ (err, events) => {+ if (err) {+ log.warn({ err }, '[head-watcher] parcel subscription error');+ return;+ }+ for (const event of events) dispatch(event.path);+ },+ undefined,+ platform,+ );return () => subscription.unsubscribe();} catch (err) {log.debug(@@ -121,6 +129,7 @@ export async function startHeadWatcher(onBatchEnd: OnBatchEnd,opts: {forceBackend?: 'parcel' | 'chokidar';+ platform?: NodeJS.Platform;subscribeForTest?: (gitDir: string,dispatch: HeadEventDispatch,@@ -247,7 +256,11 @@ export async function startHeadWatcher(resolvedUnsub = await opts.subscribeForTest(gitDir, dispatch);backend = 'test';} else if (opts.forceBackend !== 'chokidar') {- resolvedUnsub = await tryStartParcelHeadWatcher(gitDir, dispatch);+ resolvedUnsub = await tryStartParcelHeadWatcher(+ gitDir,+ dispatch,+ opts.platform ?? process.platform,+ );if (resolvedUnsub) backend = 'parcel';}if (!resolvedUnsub) {diff --git a/packages/server/src/parcel-subscription.test.ts b/packages/server/src/parcel-subscription.test.tsnew file mode 100644index 000000000..99f3680ae--- /dev/null+++ b/packages/server/src/parcel-subscription.test.ts@@ -0,0 +1,115 @@+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { AsyncSubscription, Event } from '@parcel/watcher';+import { beforeEach, describe, expect, test } from 'vitest';+import { subscribeParcel } from './parcel-subscription.ts';+import {+ forgetNativeSubscriptions,+ type NativeSubscriptionDouble,+ nativeSubscriptionOn,+ parcelWatcherModule,+} from './parcel-watcher-double.test-helper.ts';++const POSIX_PLATFORMS = ['linux', 'darwin'] as const satisfies readonly NodeJS.Platform[];+const PLATFORMS = ['win32', ...POSIX_PLATFORMS] as const satisfies readonly NodeJS.Platform[];+const NATIVE_RELEASES_PER_RELEASE = [+ ['win32', 0],+ ['linux', 1],+ ['darwin', 1],+] as const satisfies readonly (readonly [NodeJS.Platform, number])[];+const WATCHED_DIR = join(tmpdir(), 'ok-parcel-subscription');++beforeEach(() => {+ forgetNativeSubscriptions();+});++interface Subscribed {+ readonly subscription: AsyncSubscription;+ readonly native: NativeSubscriptionDouble;+ readonly delivered: Event[][];+}++async function subscribeOn(platform?: NodeJS.Platform): Promise<Subscribed> {+ const delivered: Event[][] = [];+ const subscription = await subscribeParcel(+ parcelWatcherModule,+ WATCHED_DIR,+ (_err, events) => {+ delivered.push(events);+ },+ undefined,+ platform,+ );+ return { subscription, native: nativeSubscriptionOn(WATCHED_DIR), delivered };+}++function created(name: string): Event {+ return { type: 'create', path: join(WATCHED_DIR, name) };+}++async function deliverLive(subscribed: Subscribed): Promise<void> {+ await subscribed.native.deliver([created('before.md')]);+ expect(subscribed.delivered, 'live delivery').toEqual([[created('before.md')]]);+}++describe('releasing a subscription taken through subscribeParcel', () => {+ test.each(NATIVE_RELEASES_PER_RELEASE)(+ 'on %s, a release asks the addon to unsubscribe natively %i time(s)',+ async (platform, nativeReleases) => {+ const { subscription, native } = await subscribeOn(platform);++ await subscription.unsubscribe();++ expect(native.nativeReleases(), 'native unsubscribe calls').toBe(nativeReleases);+ },+ );++ test.each(PLATFORMS)(+ 'on %s, a batch the addon delivers after the release reaches no consumer',+ async (platform) => {+ const subscribed = await subscribeOn(platform);+ await deliverLive(subscribed);++ await subscribed.subscription.unsubscribe();+ await subscribed.native.deliver([created('after.md')]);++ expect(subscribed.delivered).toEqual([[created('before.md')]]);+ },+ );++ test.each(POSIX_PLATFORMS)(+ 'on %s, a batch the addon delivers while the native unsubscribe is in flight reaches no consumer',+ async (platform) => {+ const subscribed = await subscribeOn(platform);+ await deliverLive(subscribed);++ subscribed.native.deliverWhileReleasing([created('during.md')]);+ await subscribed.subscription.unsubscribe();++ expect(subscribed.native.nativeReleases(), 'native unsubscribe calls').toBe(1);+ expect(subscribed.delivered).toEqual([[created('before.md')]]);+ },+ );++ test.each(POSIX_PLATFORMS)(+ 'on %s, a second release asks the addon for nothing more',+ async (platform) => {+ const { subscription, native } = await subscribeOn(platform);++ await subscription.unsubscribe();+ await subscription.unsubscribe();++ expect(native.nativeReleases(), 'native unsubscribe calls').toBe(1);+ },+ );++ test('without a platform, the host platform decides whether a release unsubscribes natively', async () => {+ const { subscription, native } = await subscribeOn();++ await subscription.unsubscribe();++ expect(native.nativeReleases(), 'native unsubscribe calls').toBe(+ process.platform === 'win32' ? 0 : 1,+ );+ });+});diff --git a/packages/server/src/parcel-subscription.ts b/packages/server/src/parcel-subscription.tsnew file mode 100644index 000000000..680526e8e--- /dev/null+++ b/packages/server/src/parcel-subscription.ts@@ -0,0 +1,25 @@+import type { AsyncSubscription, Options, SubscribeCallback } from '@parcel/watcher';++export async function subscribeParcel(+ parcel: Pick<typeof import('@parcel/watcher'), 'subscribe'>,+ dir: string,+ onEvents: SubscribeCallback,+ options?: Options,+ platform: NodeJS.Platform = process.platform,+): Promise<AsyncSubscription> {+ let deliver: SubscribeCallback | null = onEvents;+ const subscription = await parcel.subscribe(+ dir,+ (err, events) => deliver?.(err, events),+ options,+ );+ return {+ async unsubscribe() {+ if (deliver === null) return;+ deliver = null;+ // UPSTREAM(parcel-bundler/watcher#262): the win32 native unsubscribe frees the subscription while its read's completion is still queued+ if (platform === 'win32') return;+ await subscription.unsubscribe();+ },+ };+}diff --git a/packages/server/src/parcel-watcher-double.test-helper.ts b/packages/server/src/parcel-watcher-double.test-helper.tsnew file mode 100644index 000000000..346d95312--- /dev/null+++ b/packages/server/src/parcel-watcher-double.test-helper.ts@@ -0,0 +1,76 @@+import { resolve } from 'node:path';+import type { AsyncSubscription, Event, Options, SubscribeCallback } from '@parcel/watcher';++export interface NativeSubscriptionDouble {+ readonly dir: string;+ nativeReleases(): number;+ deliver(events: Event[]): Promise<void>;+ deliverWhileReleasing(events: Event[]): void;+}++interface Registration extends NativeSubscriptionDouble {+ readonly callback: SubscribeCallback;+ release(): Promise<void>;+}++const registrations: Registration[] = [];++function register(dir: string, callback: SubscribeCallback): Registration {+ let releases = 0;+ const queuedForRelease: Event[][] = [];+ const deliver = async (events: Event[]): Promise<void> => {+ await callback(null, events);+ await new Promise<void>((settle) => setImmediate(settle));+ };+ return {+ dir,+ callback,+ nativeReleases: () => releases,+ deliver,+ deliverWhileReleasing: (events) => {+ queuedForRelease.push(events);+ },+ release: async () => {+ releases += 1;+ for (const events of queuedForRelease.splice(0)) await deliver(events);+ },+ };+}++const parcelWatcherDouble = {+ subscribe(+ dir: string,+ callback: SubscribeCallback,+ _options?: Options,+ ): Promise<AsyncSubscription> {+ const registration = register(resolve(dir), callback);+ registrations.push(registration);+ return Promise.resolve({ unsubscribe: () => registration.release() });+ },+ unsubscribe(dir: string, callback: SubscribeCallback, _options?: Options): Promise<void> {+ const registration = registrations.find(+ (candidate) => candidate.dir === resolve(dir) && candidate.callback === callback,+ );+ return registration === undefined ? Promise.resolve() : registration.release();+ },+};++export const parcelWatcherModule = { default: parcelWatcherDouble, ...parcelWatcherDouble };++export function forgetNativeSubscriptions(): void {+ registrations.length = 0;+}++export function nativeSubscriptionDirs(): string[] {+ return registrations.map((registration) => registration.dir);+}++export function nativeSubscriptionOn(dir: string): NativeSubscriptionDouble {+ const matching = registrations.filter((registration) => registration.dir === dir);+ if (matching.length !== 1) {+ throw new Error(+ `expected exactly one native subscription on ${dir}; the addon was asked to watch [${nativeSubscriptionDirs().join(', ')}]`,+ );+ }+ return matching[0];+}diff --git a/packages/server/src/server-shutdown-parcel-release.test.ts b/packages/server/src/server-shutdown-parcel-release.test.tsnew file mode 100644index 000000000..488deb1cb--- /dev/null+++ b/packages/server/src/server-shutdown-parcel-release.test.ts@@ -0,0 +1,101 @@+import { execFileSync } from 'node:child_process';+import { mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, sep } from 'node:path';+import { afterEach, beforeEach, expect, test, vi } from 'vitest';+import type { BootedServer } from './boot.ts';+import { bootCompositionRig } from './composition-rig.test-helper.ts';+import { getWatcherDecisionRingSnapshot } from './file-watcher.ts';+import { getMetrics } from './metrics.ts';+import {+ forgetNativeSubscriptions,+ nativeSubscriptionDirs,+ nativeSubscriptionOn,+} from './parcel-watcher-double.test-helper.ts';++vi.mock('@parcel/watcher', async () => {+ const { parcelWatcherModule } = await import('./parcel-watcher-double.test-helper.ts');+ return parcelWatcherModule;+});++const LIVENESS = { timeout: 10_000 };++let root: string;+let server: BootedServer | undefined;++beforeEach(() => {+ forgetNativeSubscriptions();+ root = realpathSync(mkdtempSync(join(tmpdir(), 'ok-parcel-shutdown-')));+ execFileSync('git', ['init', '--quiet', '--initial-branch=main'], {+ cwd: root,+ stdio: 'ignore',+ env: {+ ...Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_'))),+ GIT_CONFIG_GLOBAL: '/dev/null',+ GIT_CONFIG_NOSYSTEM: '1',+ },+ });+});++afterEach(async () => {+ try {+ await server?.destroy();+ } finally {+ server = undefined;+ rmSync(root, { recursive: true, force: true });+ }+});++function writeDoc(name: string): string {+ const path = join(root, name);+ writeFileSync(path, `# ${name}\n`, 'utf-8');+ return path;+}++function dispatchedKinds(fileName: string): string[] {+ return getWatcherDecisionRingSnapshot()+ .filter(+ (record) => record.decision === 'dispatched' && record.path.endsWith(`${sep}${fileName}`),+ )+ .map((record) => record.kind);+}++test('once the server is destroyed, a native delivery neither dispatches a disk event nor begins a batch', async () => {+ server = await bootCompositionRig(root);+ await server.ready;+ const gitDir = join(root, '.git');+ expect(nativeSubscriptionDirs().sort()).toEqual([root, gitDir].sort());+ const content = nativeSubscriptionOn(root);+ const head = nativeSubscriptionOn(gitDir);+ const headUpdate: { type: 'update'; path: string } = {+ type: 'update',+ path: join(gitDir, 'HEAD'),+ };++ await content.deliver([{ type: 'create', path: writeDoc('before.md') }]);+ await vi.waitFor(() => expect(dispatchedKinds('before.md')).toEqual(['create']), LIVENESS);+ const batchesBeforeHeadUpdate = getMetrics().batchCount;+ await head.deliver([headUpdate]);+ await vi.waitFor(+ () => expect(getMetrics().batchCount).toBe(batchesBeforeHeadUpdate + 1),+ LIVENESS,+ );++ await server.destroy();+ server = undefined;++ const nativeReleasesPerSubscription = process.platform === 'win32' ? 0 : 1;+ expect({ content: content.nativeReleases(), head: head.nativeReleases() }).toEqual({+ content: nativeReleasesPerSubscription,+ head: nativeReleasesPerSubscription,+ });++ const batchesAtDestroy = getMetrics().batchCount;+ await content.deliver([{ type: 'create', path: writeDoc('after.md') }]);+ await head.deliver([headUpdate]);++ expect({+ dispatched: dispatchedKinds('after.md'),+ batchesBegun: getMetrics().batchCount - batchesAtDestroy,+ }).toEqual({ dispatched: [], batchesBegun: 0 });+}, 60_000);