Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Keep the boot narration a desktop smoke give-up already read (#4780)
Nick Gomezb4d2e4ecde6c
diff --git a/packages/desktop/tests/smoke/_helpers/boot-gap-emit.ts b/packages/desktop/tests/smoke/_helpers/boot-gap-emit.tsnew file mode 100644index 000000000..2dee28e2c--- /dev/null+++ b/packages/desktop/tests/smoke/_helpers/boot-gap-emit.ts@@ -0,0 +1,57 @@+import type { TestInfo } from '@playwright/test';+import { shouldAttachStderr } from './electron-stderr';+import {+ bootGapLineFor,+ bootNarrationFor,+ formatBootGapLine,+ readBootLog,+ readyWaitsFor,+ tryBootLogFor,+ tryFirstWaitFor,+ tryLaunchHomeFor,+} from './launch-readiness';++export type BootGapAttachTarget = Pick<TestInfo, 'attach'> &+ Pick<TestInfo, 'status' | 'retry' | 'project'>;++export async function emitBootGapLines(+ apps: readonly object[],+ testInfo: BootGapAttachTarget,+ log: (line: string) => void = console.log,+ warn: (line: string) => void = console.warn,+): Promise<void> {+ const homes = apps.map((app) => tryLaunchHomeFor(app));+ for (const [slot, app] of apps.entries()) {+ const home = homes[slot];+ if (home === undefined) continue;+ const suffix = `-slot${slot}`;+ const narration = bootNarrationFor(tryBootLogFor(app), readBootLog(home));+ const readyWaits = readyWaitsFor(app);+ const firstWait = tryFirstWaitFor(app);+ const gap = bootGapLineFor({+ slot,+ narration,+ readyWaitCount: readyWaits?.length ?? 0,+ ...(firstWait === undefined ? {} : { firstWait }),+ homeShared: homes.filter((h) => h === home).length > 1,+ });+ log(formatBootGapLine(gap));+ let attempted = `boot-log-gaps${suffix}`;+ try {+ await testInfo.attach(attempted, {+ body: JSON.stringify(gap, null, 2),+ contentType: 'application/json',+ });+ if (narration.lines.length > 0 && shouldAttachStderr(testInfo)) {+ attempted = `boot-log${suffix}`;+ await testInfo.attach(attempted, {+ body: narration.lines.join('\n'),+ contentType: 'text/plain',+ });+ }+ } catch (error) {+ const reason = error instanceof Error ? error.message : String(error);+ warn(`[smoke-test] slot=${slot} could not attach ${attempted}: ${reason}`);+ }+ }+}diff --git a/packages/desktop/tests/smoke/_helpers/launch-readiness.test.ts b/packages/desktop/tests/smoke/_helpers/launch-readiness.test.tsindex a26a7f9af..f83a7997f 100644--- a/packages/desktop/tests/smoke/_helpers/launch-readiness.test.ts+++ b/packages/desktop/tests/smoke/_helpers/launch-readiness.test.ts@@ -19,14 +19,17 @@ import {BOOT_LOG_HEARTBEAT_MS,BOOT_LOG_STALL_MS,type BootLogSnapshot,+ bootGapLineFor,bootGapSourceFor,bootLogDirFor,bootLogGapSummary,+ bootNarrationFor,classifyBootLog,describeMissingBootLog,formatBootGapLine,giveUpReason,hasBootCompleted,+ isMoreCompleteNarration,launchDesktopApp,launchHomeFor,READY_WAIT_GIVE_UP_REASONS,@@ -204,7 +207,9 @@ describe('waitForReadySignal — progress gating', () => {},readLog: () => snapshot({ exists: false }),}),- ).rejects.toThrow(/NOT FOUND/);+ ).rejects.toThrow(+ 'Boot log: /tmp/x/.ok/logs (NOT FOUND, the cause is not determined here (it may have been removed, never written, or written elsewhere))',+ );});it('says the log cannot explain the wait, rather than blaming the app, on the stall path', async () => {@@ -706,7 +711,7 @@ describe('the stall rule applies only while boot narration is live', () => {});describe('boot-log evidence survives a spec that removes its own launch home', () => {- it('snapshots the boot log when boot ends, not at teardown', async () => {+ it('snapshots the boot log when the wait ends, not at teardown', async () => {const home = seedHome([JSON.stringify({ time: '2026-09-04T00:00:00.000Z', event: DESKTOP_BOOT_EVENT }),markLine('appReady', 0, '2026-09-04T00:00:01.000Z'),@@ -727,8 +732,198 @@ describe('boot-log evidence survives a spec that removes its own launch home', (await waitForWindowByMode(app, 'editor');expect(tryBootLogFor(app)).toBeUndefined();});++ it('remembers the narration a give-up read, so a removed log dir cannot erase it', async () => {+ const narration = [+ JSON.stringify({ time: '2026-09-04T00:00:00.000Z', event: DESKTOP_BOOT_EVENT }),+ markLine('appReady', 0, '2026-09-04T00:00:01.000Z'),+ markLine('serverSpawned', 500, '2026-09-04T00:00:01.500Z'),+ ];+ const home = seedHome(narration);+ const app = { windows: () => [] };+ rememberLaunchHome(app, home);+ await expect(+ waitForWindowByMode(app, 'editor', { capMs: 300, stallMs: 600_000, pollMs: 20 }),+ ).rejects.toThrow(/did not arrive/);+ expect(tryFirstWaitFor(app)).toMatchObject({ gaveUp: true, reason: 'cap' });+ rmSync(join(home, '.ok'), { recursive: true, force: true });+ expect(readBootLogLines(home)).toEqual([]);+ expect(tryBootLogFor(app)).toEqual(narration);+ });++ it('remembers the narration even when the give-up probe never answered', async () => {+ const narration = [+ JSON.stringify({ time: '2026-09-04T00:00:00.000Z', event: DESKTOP_BOOT_EVENT }),+ markLine('appReady', 0, '2026-09-04T00:00:01.000Z'),+ markLine('serverSpawned', 500, '2026-09-04T00:00:01.500Z'),+ ];+ const home = seedHome(narration);+ const stuck = Promise.withResolvers<string | undefined>();+ let answered = false;+ const page = {+ evaluate: () =>+ stuck.promise.then((mode) => {+ answered = true;+ return mode;+ }),+ };+ const app = { windows: () => [page] };+ rememberLaunchHome(app, home);+ await expect(+ waitForWindowByMode(app, 'editor', { capMs: 300, stallMs: 600_000, pollMs: 20 }),+ ).rejects.toThrow(/did not arrive/);+ const probeAnswered = answered;+ stuck.resolve(undefined);+ expect({ probeAnswered, wait: tryFirstWaitFor(app) }).toMatchObject({+ probeAnswered: false,+ wait: { gaveUp: true, reason: 'cap' },+ });+ rmSync(join(home, '.ok'), { recursive: true, force: true });+ expect(tryBootLogFor(app)).toEqual(narration);+ });++ it('still remembers nothing when a give-up found no log, so unavailable stays honest', async () => {+ const app = { windows: () => [] };+ rememberLaunchHome(app, seedHome());+ await expect(+ waitForWindowByMode(app, 'editor', { capMs: 300, stallMs: 600_000, pollMs: 20 }),+ ).rejects.toThrow(/did not arrive/);+ expect(tryFirstWaitFor(app)).toMatchObject({ gaveUp: true, reason: 'notfound' });+ expect(tryBootLogFor(app)).toBeUndefined();+ });++ it('keeps the fuller narration when a later wait reads a log that has since shrunk', async () => {+ const opening = JSON.stringify({ time: '2026-09-04T00:00:00.000Z', event: DESKTOP_BOOT_EVENT });+ const whole = [+ opening,+ markLine('appReady', 0, '2026-09-04T00:00:01.000Z'),+ markLine('serverLockReady', 14_428, '2026-09-04T00:00:14.428Z'),+ ];+ const home = seedHome(whole);+ const editor = { evaluate: async () => 'editor' };+ const app = { windows: () => [editor] };+ rememberLaunchHome(app, home);+ await waitForWindowByMode(app, 'editor');+ expect(tryBootLogFor(app)).toEqual(whole);++ writeFileSync(join(bootLogDirFor(home), 'desktop.2026-09-03.log'), `${opening}\n`, 'utf8');+ expect(readBootLogLines(home)).toEqual([opening]);++ await waitForWindowByMode(app, 'editor');+ expect(tryBootLogFor(app)).toEqual(whole);+ });});+describe('the teardown line reports the most complete narration the run produced', () => {+ const early = [+ JSON.stringify({ time: '2026-09-04T00:00:00.000Z', event: DESKTOP_BOOT_EVENT }),+ markLine('appReady', 0, '2026-09-04T00:00:01.000Z'),+ ];+ const whole = [+ ...early,+ markLine('serverLockReady', 14_428, '2026-09-04T00:00:14.428Z'),+ markLine('windowCreated', 14_521, '2026-09-04T00:00:14.521Z'),+ markLine('loadUrlResolved', 18_569, '2026-09-04T00:00:18.569Z'),+ ];++ it('prefers the longer on-disk log to a snapshot taken earlier in the run', () => {+ const onDisk = readBootLog(seedHome(whole));+ expect(onDisk.lines).toEqual(whole);+ const gap = bootGapLineFor({+ slot: 0,+ narration: bootNarrationFor(early, onDisk),+ readyWaitCount: 1,+ homeShared: false,+ });+ expect(gap.summary?.lineCount).toBe(whole.length);+ expect(gap.reason).toBeUndefined();+ });++ it('keeps the snapshot when the disk read came back empty', () => {+ const onDisk = readBootLog(seedHome());+ expect(onDisk.lines).toEqual([]);+ const gap = bootGapLineFor({+ slot: 0,+ narration: bootNarrationFor(whole, onDisk),+ readyWaitCount: 1,+ homeShared: false,+ });+ expect(gap.summary?.lineCount).toBe(whole.length);+ expect(gap.source).toBe('wait-snapshot');+ });++ it('names no cause at all when it has narration to report', () => {+ const gap = bootGapLineFor({+ slot: 0,+ narration: bootNarrationFor(early, readBootLog(seedHome(whole))),+ readyWaitCount: 1,+ homeShared: false,+ });+ expect(gap.summary).toBeDefined();+ expect(gap.reason).toBeUndefined();+ });++ it('names the cause it can see when neither side narrated anything at all', () => {+ const onDisk = readBootLog(seedHome());+ expect(onDisk.exists).toBe(false);+ const gap = bootGapLineFor({+ slot: 0,+ narration: bootNarrationFor(undefined, onDisk),+ readyWaitCount: 1,+ homeShared: false,+ });+ expect({ summary: gap.summary, source: gap.source, reason: gap.reason }).toEqual({+ summary: undefined,+ source: 'unavailable',+ reason:+ 'no desktop log file when the fixture read it; the cause is not determined here (it may have been removed, never written, or written elsewhere)',+ });+ });++ it('credits the disk read when the disk read is what it reported', () => {+ const onDisk = readBootLog(seedHome(whole));+ expect(onDisk.lines).toEqual(whole);+ expect(+ bootGapLineFor({+ slot: 0,+ narration: bootNarrationFor(early, onDisk),+ readyWaitCount: 1,+ homeShared: false,+ }).source,+ ).toBe('teardown-read');+ expect(+ bootGapLineFor({+ slot: 0,+ narration: bootNarrationFor(early, onDisk),+ readyWaitCount: 1,+ homeShared: true,+ }).source,+ ).toBe('teardown-read-shared-home');+ });++ it('labels a give-up snapshot by the wait that took it, not by a boot that never completed', async () => {+ const home = seedHome(early);+ const app = { windows: () => [] };+ rememberLaunchHome(app, home);+ await expect(+ waitForWindowByMode(app, 'editor', { capMs: 300, stallMs: 600_000, pollMs: 20 }),+ ).rejects.toThrow(/did not arrive/);+ rmSync(join(home, '.ok'), { recursive: true, force: true });+ const firstWait = tryFirstWaitFor(app);+ const gap = bootGapLineFor({+ slot: 0,+ narration: bootNarrationFor(tryBootLogFor(app), readBootLog(home)),+ readyWaitCount: readyWaitsFor(app)?.length ?? 0,+ ...(firstWait === undefined ? {} : { firstWait }),+ homeShared: false,+ });+ expect(gap.summary?.lineCount).toBe(early.length);+ expect({ source: gap.source, bootComplete: gap.summary?.bootComplete }).toEqual({+ source: 'wait-snapshot',+ bootComplete: false,+ });+ });+});describe('the recorded ready wait names which wait it measured', () => {const slowFirstPoll = () => {const editor = { evaluate: async () => 'editor' };@@ -812,7 +1007,7 @@ describe('one classifier decides both the prose and the reason token', () => {it('names the teardown states it can tell apart, without claiming a cause it cannot know', () => {expect(describeMissingBootLog(snapshot({ exists: false }))).toBe(- 'no desktop log file at teardown (a test.afterEach removed the launch home before the fixture could read it, or the app wrote no log file)',+ 'no desktop log file when the fixture read it; the cause is not determined here (it may have been removed, never written, or written elsewhere)',);expect(describeMissingBootLog(snapshot({ exists: true, lineCount: 0 }))).toBe('log files present but empty',@@ -927,10 +1122,10 @@ describe('bootGapSourceFor', () => {'unavailable',);expect(bootGapSourceFor({ hasLines: true, snapshotted: true, homeShared: false })).toBe(- 'boot-complete',+ 'wait-snapshot',);expect(bootGapSourceFor({ hasLines: true, snapshotted: true, homeShared: true })).toBe(- 'boot-complete',+ 'wait-snapshot',);expect(bootGapSourceFor({ hasLines: true, snapshotted: false, homeShared: false })).toBe('teardown-read',@@ -941,11 +1136,24 @@ describe('bootGapSourceFor', () => {});});+describe('isMoreCompleteNarration', () => {+ it('accepts a candidate that says more than what is already held', () => {+ expect(isMoreCompleteNarration(['a', 'b'], ['a'])).toBe(true);+ expect(isMoreCompleteNarration(['a'], undefined)).toBe(true);+ });++ it('rejects a candidate that says the same or less, so a tie keeps what is held', () => {+ expect(isMoreCompleteNarration(['a'], ['a', 'b'])).toBe(false);+ expect(isMoreCompleteNarration(['b'], ['a'])).toBe(false);+ expect(isMoreCompleteNarration([], undefined)).toBe(false);+ });+});+describe('formatBootGapLine', () => {it('states the measured gap next to the bound it has to clear', () => {const line = formatBootGapLine({slot: 0,- source: 'boot-complete',+ source: 'wait-snapshot',readyWaitCount: 2,firstWait: {ordinal: 0,@@ -962,7 +1170,7 @@ describe('formatBootGapLine', () => {]),});expect(line).toContain('[boot-gap] slot=0');- expect(line).toContain('source=boot-complete');+ expect(line).toContain('source=wait-snapshot');expect(line).toContain(`stallMs=${BOOT_LOG_STALL_MS}`);expect(line).toContain('totalBootMs=3000');expect(line).toContain('maxGapMs=1600');@@ -1007,7 +1215,7 @@ describe('formatBootGapLine', () => {for (const reason of READY_WAIT_GIVE_UP_REASONS) {const line = formatBootGapLine({slot: 0,- source: 'boot-complete',+ source: 'wait-snapshot',readyWaitCount: 1,firstWait: {ordinal: 0,diff --git a/packages/desktop/tests/smoke/_helpers/launch-readiness.ts b/packages/desktop/tests/smoke/_helpers/launch-readiness.tsindex c9e1ec37b..db413915f 100644--- a/packages/desktop/tests/smoke/_helpers/launch-readiness.ts+++ b/packages/desktop/tests/smoke/_helpers/launch-readiness.ts@@ -209,10 +209,13 @@ export function bootLogGapSummary(all: readonly string[]): BootLogGapSummary {type BootGapSource =| 'unavailable'- | 'boot-complete'+ | 'wait-snapshot'| 'teardown-read'| 'teardown-read-shared-home';+const UNDETERMINED_ABSENT_LOG_CAUSE =+ 'the cause is not determined here (it may have been removed, never written, or written elsewhere)';+export function describeMissingBootLog(snapshot: BootLogSnapshot): string {switch (classifyBootLog(snapshot)) {case 'unreadable':@@ -220,7 +223,7 @@ export function describeMissingBootLog(snapshot: BootLogSnapshot): string {? `log dir unreadable (${snapshot.unreadableReason})`: `log files unreadable: ${snapshot.unreadableFiles.join(', ')}`;case 'notfound':- return 'no desktop log file at teardown (a test.afterEach removed the launch home before the fixture could read it, or the app wrote no log file)';+ return `no desktop log file when the fixture read it; ${UNDETERMINED_ABSENT_LOG_CAUSE}`;case 'empty':return 'log files present but empty';case 'ok':@@ -228,14 +231,12 @@ export function describeMissingBootLog(snapshot: BootLogSnapshot): string {}}-export interface BootGapLine {+export type BootGapLine = {slot: number;source: BootGapSource;firstWait?: ReadyWaitRecord;readyWaitCount?: number;- summary: BootLogGapSummary | undefined;- reason?: string;-}+} & ({ summary: BootLogGapSummary; reason?: never } | { summary?: never; reason: string });export function bootGapSourceFor(input: {hasLines: boolean;@@ -243,10 +244,60 @@ export function bootGapSourceFor(input: {homeShared: boolean;}): BootGapSource {if (!input.hasLines) return 'unavailable';- if (input.snapshotted) return 'boot-complete';+ if (input.snapshotted) return 'wait-snapshot';return input.homeShared ? 'teardown-read-shared-home' : 'teardown-read';}+class NarrationOfOneRead {+ readonly lines: readonly string[];+ readonly snapshotted: boolean;+ readonly #read: BootLogSnapshot;++ constructor(atBoot: readonly string[] | undefined, onDisk: BootLogSnapshot) {+ const useDisk = isMoreCompleteNarration(onDisk.lines, atBoot);+ this.lines = useDisk ? onDisk.lines : (atBoot ?? []);+ this.snapshotted = !useDisk && atBoot !== undefined;+ this.#read = onDisk;+ }++ get missingLogReason(): string | undefined {+ return this.lines.length === 0 ? describeMissingBootLog(this.#read) : undefined;+ }+}++export type BootNarration = NarrationOfOneRead;++export function bootNarrationFor(+ atBoot: readonly string[] | undefined,+ onDisk: BootLogSnapshot,+): BootNarration {+ return new NarrationOfOneRead(atBoot, onDisk);+}++export function bootGapLineFor(input: {+ slot: number;+ narration: BootNarration;+ readyWaitCount: number;+ firstWait?: ReadyWaitRecord;+ homeShared: boolean;+}): BootGapLine {+ const { narration } = input;+ const reason = narration.missingLogReason;+ const base = {+ slot: input.slot,+ source: bootGapSourceFor({+ hasLines: reason === undefined,+ snapshotted: narration.snapshotted,+ homeShared: input.homeShared,+ }),+ readyWaitCount: input.readyWaitCount,+ ...(input.firstWait === undefined ? {} : { firstWait: input.firstWait }),+ };+ return reason === undefined+ ? { ...base, summary: bootLogGapSummary(narration.lines) }+ : { ...base, reason };+}+export function formatBootGapLine(line: BootGapLine): string {const parts = [`[boot-gap] slot=${line.slot}`,@@ -270,7 +321,7 @@ export function formatBootGapLine(line: BootGapLine): string {]),];if (line.summary === undefined) {- parts.push(`reason=${JSON.stringify(line.reason ?? 'unknown')}`);+ parts.push(`reason=${JSON.stringify(line.reason)}`);return parts.join(' ');}parts.push(@@ -333,10 +384,7 @@ function describeBootLog(snapshot: BootLogSnapshot): string {`${snapshot.unreadableFiles.join(', ')} — a runner filesystem problem, not evidence ` +'about the app)';case 'notfound':- return (- `Boot log: ${snapshot.dir} (NOT FOUND — the app may have died before it could log, ` +- 'or a required build artifact is missing)'- );+ return `Boot log: ${snapshot.dir} (NOT FOUND, ${UNDETERMINED_ABSENT_LOG_CAUSE})`;case 'empty':return (`Boot log: ${snapshot.dir} (${snapshot.fileCount} file(s) present but EMPTY — the app ` +@@ -548,8 +596,15 @@ export function tryLaunchHomeFor(app: object): string | undefined {return HOME_BY_APP.get(app);}+export function isMoreCompleteNarration(+ candidate: readonly string[],+ held: readonly string[] | undefined,+): boolean {+ return candidate.length > (held?.length ?? 0);+}+export function rememberBootLog(app: object, lines: readonly string[]): void {- if (lines.length === 0) return;+ if (!isMoreCompleteNarration(lines, BOOT_LOG_BY_APP.get(app))) return;BOOT_LOG_BY_APP.set(app, [...lines]);}@@ -636,12 +691,12 @@ export async function waitForWindowByMode<TPage extends ModeProbePage>(},});succeeded = true;- rememberBootLog(app, readBootLogLines(home));return found;} catch (error) {if (error instanceof ReadySignalGiveUp) reason = error.reason;throw error;} finally {+ rememberBootLog(app, readBootLogLines(home));rememberReadyWait(app, {what,elapsedMs: Date.now() - startedAt,diff --git a/packages/desktop/tests/smoke/_helpers/smoke-test.ts b/packages/desktop/tests/smoke/_helpers/smoke-test.tsindex 6dd38396c..aa4986593 100644--- a/packages/desktop/tests/smoke/_helpers/smoke-test.ts+++ b/packages/desktop/tests/smoke/_helpers/smoke-test.ts@@ -1,6 +1,7 @@import type { ChildProcess } from 'node:child_process';import { rmSync } from 'node:fs';import { expect as baseExpect, test as baseTest, type ElectronApplication } from '@playwright/test';+import { emitBootGapLines } from './boot-gap-emit';import { captureAppProcess, closeAppBounded, reapDetachedServers } from './electron-cleanup';import {attachCapturedStderr,@@ -8,19 +9,7 @@ import {type ElectronStderrCapture,shouldAttachStderr,} from './electron-stderr';-import {- type BootGapLine,- bootGapSourceFor,- bootLogGapSummary,- describeMissingBootLog,- formatBootGapLine,- readBootLog,- readyWaitsFor,- rememberLaunchHome,- tryBootLogFor,- tryFirstWaitFor,- tryLaunchHomeFor,-} from './launch-readiness';+import { rememberLaunchHome } from './launch-readiness';export interface SmokeRegistrationOpts {cleanupDirs?: readonly string[];@@ -47,45 +36,7 @@ export const test = baseTest.extend<SmokeFixtures>({for (const dir of opts.cleanupDirs) cleanupDirs.push(dir);}});- const homes = apps.map((app) => tryLaunchHomeFor(app));- for (const [slot, app] of apps.entries()) {- const home = homes[slot];- if (home === undefined) continue;- const suffix = `-slot${slot}`;- const atBoot = tryBootLogFor(app);- const onDisk = readBootLog(home);- const lines = atBoot ?? onDisk.lines;- const readyWaits = readyWaitsFor(app);- const firstWait = tryFirstWaitFor(app);- const gap: BootGapLine = {- slot,- source: bootGapSourceFor({- hasLines: lines.length > 0,- snapshotted: atBoot !== undefined,- homeShared: homes.filter((h) => h === home).length > 1,- }),- readyWaitCount: readyWaits?.length ?? 0,- ...(firstWait === undefined ? {} : { firstWait }),- summary: lines.length > 0 ? bootLogGapSummary(lines) : undefined,- };- if (gap.summary === undefined) gap.reason = describeMissingBootLog(onDisk);- console.log(formatBootGapLine(gap));- try {- await testInfo.attach(`boot-log-gaps${suffix}`, {- body: JSON.stringify(gap, null, 2),- contentType: 'application/json',- });- if (lines.length > 0 && shouldAttachStderr(testInfo)) {- await testInfo.attach(`boot-log${suffix}`, {- body: lines.join('\n'),- contentType: 'text/plain',- });- }- } catch (error) {- const reason = error instanceof Error ? error.message : String(error);- console.warn(`[smoke-test] boot-log attach failed: ${reason}`);- }- }+ await emitBootGapLines(apps, testInfo);const unclosed: Error[] = [];for (const proc of procs) {try {diff --git a/packages/desktop/tests/unit/smoke-test-boot-gap-emit.test.ts b/packages/desktop/tests/unit/smoke-test-boot-gap-emit.test.tsnew file mode 100644index 000000000..4bcb9702f--- /dev/null+++ b/packages/desktop/tests/unit/smoke-test-boot-gap-emit.test.ts@@ -0,0 +1,203 @@+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { TestInfo } from '@playwright/test';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { type BootGapAttachTarget, emitBootGapLines } from '../smoke/_helpers/boot-gap-emit';+import {+ bootLogDirFor,+ formatBootGapLine,+ rememberBootLog,+ rememberLaunchHome,+} from '../smoke/_helpers/launch-readiness';+import { removeTempDirBestEffort } from '../support/temp-dir-cleanup.test-helper';++interface Attachment {+ name: string;+ body: string;+}++const seededHomes: string[] = [];++afterEach(() => {+ for (const home of seededHomes.splice(0)) removeTempDirBestEffort(home);+ vi.restoreAllMocks();+});++function recorder(over: Partial<TestInfo> = {}): {+ info: BootGapAttachTarget;+ attachments: Attachment[];+ lines: string[];+} {+ const attachments: Attachment[] = [];+ const lines: string[] = [];+ const info = {+ status: 'failed',+ retry: 2,+ project: { retries: 2 },+ attach: async (name: string, opts: { body: string }) => {+ attachments.push({ name, body: String(opts.body) });+ },+ ...over,+ } as unknown as BootGapAttachTarget;+ return { info, attachments, lines };+}++function seedHome(narration: readonly string[]): string {+ const home = mkdtempSync(join(tmpdir(), 'ok-bootgap-'));+ seededHomes.push(home);+ if (narration.length > 0) {+ const dir = bootLogDirFor(home);+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'desktop.2026-09-03.log'), `${narration.join('\n')}\n`, 'utf8');+ }+ return home;+}++const line = (phase: string, at: string) =>+ JSON.stringify({ time: at, event: `desktop.startup.${phase}`, phase, elapsedMs: 0 });++const gapOf = (attachments: Attachment[], slot: number) =>+ JSON.parse(attachments.find((a) => a.name === `boot-log-gaps-slot${slot}`)?.body ?? '{}');++describe('the fixture emits one boot-gap line per launch it registered', () => {+ it('names a home shared by two launches, so the label is not derived from one app alone', async () => {+ const home = seedHome([line('appReady', '2026-09-04T00:00:01.000Z')]);+ const first = {};+ const second = {};+ rememberLaunchHome(first, home);+ rememberLaunchHome(second, home);+ const { info, attachments, lines } = recorder();++ await emitBootGapLines([first, second], info, (l) => lines.push(l));++ expect(gapOf(attachments, 0).source).toBe('teardown-read-shared-home');+ expect(gapOf(attachments, 1).source).toBe('teardown-read-shared-home');+ expect(lines).toHaveLength(2);+ });++ it('reports the snapshot a give-up kept, and still attaches the log the disk no longer holds', async () => {+ const narration = [+ line('appReady', '2026-09-04T00:00:01.000Z'),+ line('serverLockReady', '2026-09-04T00:00:14.428Z'),+ ];+ const home = seedHome(narration);+ const app = {};+ rememberLaunchHome(app, home);+ rememberBootLog(app, narration);+ rmSync(join(home, '.ok'), { recursive: true, force: true });+ const { info, attachments, lines } = recorder();++ await emitBootGapLines([app], info, (l) => lines.push(l));++ expect(gapOf(attachments, 0).source).toBe('wait-snapshot');+ expect(gapOf(attachments, 0).summary.lineCount).toBe(narration.length);+ expect(attachments.map((a) => a.name)).toContain('boot-log-slot0');+ expect(attachments.find((a) => a.name === 'boot-log-slot0')?.body).toBe(narration.join('\n'));+ });++ it('prefers the fuller on-disk log over an earlier snapshot, in that order', async () => {+ const early = [line('appReady', '2026-09-04T00:00:01.000Z')];+ const whole = [...early, line('serverLockReady', '2026-09-04T00:00:14.428Z')];+ const home = seedHome(whole);+ const app = {};+ rememberLaunchHome(app, home);+ rememberBootLog(app, early);+ const { info, attachments, lines } = recorder();++ await emitBootGapLines([app], info, (l) => lines.push(l));++ expect(gapOf(attachments, 0).source).toBe('teardown-read');+ expect(gapOf(attachments, 0).summary.lineCount).toBe(whole.length);+ });++ it('withholds the log attachment while a retry is still to come, and keeps the gap line', async () => {+ const narration = [line('appReady', '2026-09-04T00:00:01.000Z')];+ const home = seedHome(narration);+ const app = {};+ rememberLaunchHome(app, home);+ const { info, attachments, lines } = recorder({ retry: 0 } as Partial<TestInfo>);++ await emitBootGapLines([app], info, (l) => lines.push(l));++ expect(attachments.map((a) => a.name)).toEqual(['boot-log-gaps-slot0']);+ expect(lines).toHaveLength(1);+ });++ it('skips a registered app that never recorded a launch home', async () => {+ const { info, attachments, lines } = recorder();++ await emitBootGapLines([{}], info, (l) => lines.push(l));++ expect(attachments).toEqual([]);+ expect(lines).toEqual([]);+ });++ it('writes the boot-gap line to the default console sink at the call shape the fixture uses', async () => {+ const app = {};+ rememberLaunchHome(app, seedHome([line('appReady', '2026-09-04T00:00:01.000Z')]));+ const { info, attachments } = recorder();+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ await emitBootGapLines([app], info);++ expect(gapOf(attachments, 0).source).toBe('teardown-read');+ expect(log).toHaveBeenCalledTimes(1);+ expect(log.mock.calls[0][0]).toMatch(/^\[boot-gap\] slot=0 source=teardown-read /u);+ expect(log.mock.calls[0][0]).toBe(formatBootGapLine(gapOf(attachments, 0)));+ expect(warn).not.toHaveBeenCalled();+ });++ it('keeps attaching later slots when one slot attach rejects, and names the failure on warn', async () => {+ const narration = [line('appReady', '2026-09-04T00:00:01.000Z')];+ const first = {};+ const second = {};+ rememberLaunchHome(first, seedHome(narration));+ rememberLaunchHome(second, seedHome(narration));+ const { info, attachments } = recorder();+ const failsOnFirstSlot = {+ ...info,+ attach: async (name: string, opts: { body: string }) => {+ if (name === 'boot-log-gaps-slot0') throw new Error('output dir vanished');+ await info.attach(name, opts);+ },+ } as unknown as BootGapAttachTarget;+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ await expect(emitBootGapLines([first, second], failsOnFirstSlot)).resolves.toBeUndefined();++ expect(attachments.map((a) => a.name)).toEqual(['boot-log-gaps-slot1', 'boot-log-slot1']);+ expect(gapOf(attachments, 1).source).toBe('teardown-read');+ expect(log).toHaveBeenCalledTimes(2);+ expect(warn).toHaveBeenCalledTimes(1);+ expect(warn.mock.calls[0][0]).toContain('boot-log-gaps-slot0');+ expect(warn.mock.calls[0][0]).toContain('output dir vanished');+ });++ it('names the raw log, not the summary, when the second attach is the one that rejects', async () => {+ const narration = [line('appReady', '2026-09-04T00:00:01.000Z')];+ const app = {};+ rememberLaunchHome(app, seedHome(narration));+ const { info, attachments } = recorder();+ const failsOnRawLog = {+ ...info,+ attach: async (name: string, opts: { body: string }) => {+ if (name === 'boot-log-slot0') throw new Error('testInfo torn down');+ await info.attach(name, opts);+ },+ } as unknown as BootGapAttachTarget;+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ await expect(emitBootGapLines([app], failsOnRawLog)).resolves.toBeUndefined();++ expect(attachments.map((a) => a.name)).toEqual(['boot-log-gaps-slot0']);+ expect(log).toHaveBeenCalledTimes(1);+ expect(warn).toHaveBeenCalledTimes(1);+ expect(warn.mock.calls[0][0]).toContain('boot-log-slot0');+ expect(warn.mock.calls[0][0]).not.toContain('boot-log-gaps-slot0');+ expect(warn.mock.calls[0][0]).toContain('testInfo torn down');+ });+});