Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): wait on the app's own readiness signal in desktop smoke (#4128)

Nick Gomeze057237659e9
diff --git a/packages/desktop/src/main/boot-heartbeat.test.ts b/packages/desktop/src/main/boot-heartbeat.test.ts
new file mode 100644
index 000000000..a49c275ab
--- /dev/null
+++ b/packages/desktop/src/main/boot-heartbeat.test.ts
@@ -0,0 +1,98 @@
+import { describe, expect, test } from 'vitest';
+import {
+ BOOT_HEARTBEAT_ABANDONED_SUFFIX,
+ BOOT_HEARTBEAT_EVENTS,
+ SPAWN_WAIT_HEARTBEAT_MS,
+} from '../shared/boot-narration.ts';
+import { type BootHeartbeatDeps, startBootHeartbeat } from './boot-heartbeat.ts';
+
+function harness() {
+ const intervals: { cb: () => void; ms: number; cleared: boolean; tick: () => void }[] = [];
+ const lines: Record<string, unknown>[] = [];
+ let flushes = 0;
+ const deps: Required<BootHeartbeatDeps> = {
+ log: {
+ info: (obj: Record<string, unknown>) => {
+ lines.push(obj);
+ },
+ },
+ flushLog: () => {
+ flushes += 1;
+ },
+ setInterval: (cb: () => void, ms: number) => {
+ const rec = {
+ cb,
+ ms,
+ cleared: false,
+ tick: () => {
+ if (!rec.cleared) cb();
+ },
+ };
+ intervals.push(rec);
+ return rec;
+ },
+ clearInterval: (handle: unknown) => {
+ (handle as { cleared: boolean }).cleared = true;
+ },
+ };
+ return { deps, intervals, lines, flushes: () => flushes };
+}
+
+describe('startBootHeartbeat', () => {
+ test('beats on the app cadence and stops when told to', () => {
+ const h = harness();
+ const stop = startBootHeartbeat(h.deps, BOOT_HEARTBEAT_EVENTS.boot, 'probing', () => ({
+ phase: 'x',
+ }));
+ const beat = h.intervals[0];
+ expect(beat?.ms).toBe(SPAWN_WAIT_HEARTBEAT_MS);
+ beat?.tick();
+ beat?.tick();
+ expect(h.lines.map((l) => l.event)).toEqual([
+ BOOT_HEARTBEAT_EVENTS.boot,
+ BOOT_HEARTBEAT_EVENTS.boot,
+ ]);
+ expect(h.lines[0]).toMatchObject({ phase: 'x' });
+ expect(h.flushes()).toBe(2);
+ stop();
+ expect(h.intervals.every((i) => i.cleared)).toBe(true);
+ });
+
+ test('an unbudgeted heartbeat never abandons', () => {
+ const h = harness();
+ startBootHeartbeat(h.deps, BOOT_HEARTBEAT_EVENTS.boot, 'probing', () => ({}));
+ for (let i = 0; i < 50; i += 1) h.intervals[0]?.tick();
+ expect(h.lines).toHaveLength(50);
+ expect(h.lines.every((l) => l.event === BOOT_HEARTBEAT_EVENTS.boot)).toBe(true);
+ expect(h.intervals[0]?.cleared).toBe(false);
+ });
+
+ test('a budgeted heartbeat beats exactly its budget, then abandons once', () => {
+ const h = harness();
+ startBootHeartbeat(h.deps, BOOT_HEARTBEAT_EVENTS.boot, 'probing', () => ({ phase: 'parked' }), {
+ maxBeats: 3,
+ });
+ for (let i = 0; i < 10; i += 1) h.intervals[0]?.tick();
+ const normal = h.lines.filter((l) => l.event === BOOT_HEARTBEAT_EVENTS.boot);
+ const abandoned = h.lines.filter(
+ (l) => l.event === `${BOOT_HEARTBEAT_EVENTS.boot}${BOOT_HEARTBEAT_ABANDONED_SUFFIX}`,
+ );
+ expect(normal).toHaveLength(3);
+ expect(abandoned).toHaveLength(1);
+ expect(abandoned[0]).toMatchObject({ beats: 3, phase: 'parked' });
+ expect(h.intervals[0]?.cleared).toBe(true);
+ expect(h.flushes()).toBe(4);
+ });
+
+ test('stopping twice clears once, so it composes with a second stop path', () => {
+ const h = harness();
+ let cleared = 0;
+ h.deps.clearInterval = () => {
+ cleared += 1;
+ };
+ const stop = startBootHeartbeat(h.deps, BOOT_HEARTBEAT_EVENTS.boot, 'probing', () => ({}));
+ stop();
+ stop();
+ expect(cleared).toBe(1);
+ });
+});
diff --git a/packages/desktop/src/main/boot-heartbeat.ts b/packages/desktop/src/main/boot-heartbeat.ts
new file mode 100644
index 000000000..484a5fcb9
--- /dev/null
+++ b/packages/desktop/src/main/boot-heartbeat.ts
@@ -0,0 +1,55 @@
+import {
+ BOOT_HEARTBEAT_ABANDONED_SUFFIX,
+ type BootHeartbeatEvent,
+ SPAWN_WAIT_HEARTBEAT_MS,
+} from '../shared/boot-narration.ts';
+
+export interface BootHeartbeatDeps {
+ log?: { info(obj: Record<string, unknown>, msg: string): void } | undefined;
+ flushLog?: (() => void) | undefined;
+ setInterval?: ((cb: () => void, ms: number) => unknown) | undefined;
+ clearInterval?: ((handle: unknown) => void) | undefined;
+}
+
+export interface BootHeartbeatOptions {
+ maxBeats?: number;
+}
+
+export function startBootHeartbeat(
+ deps: BootHeartbeatDeps,
+ event: BootHeartbeatEvent,
+ message: string,
+ fields: () => Record<string, unknown>,
+ options: BootHeartbeatOptions = {},
+): () => void {
+ const startedAt = Date.now();
+ const maxBeats = options.maxBeats;
+ let beats = 0;
+ let handle: unknown;
+ const stop = () => {
+ if (handle === undefined) return;
+ deps.clearInterval?.(handle);
+ handle = undefined;
+ };
+ handle = deps.setInterval?.(() => {
+ beats += 1;
+ const elapsedMs = Date.now() - startedAt;
+ if (maxBeats !== undefined && beats > maxBeats) {
+ stop();
+ deps.log?.info(
+ {
+ event: `${event}${BOOT_HEARTBEAT_ABANDONED_SUFFIX}`,
+ elapsedMs,
+ beats: beats - 1,
+ ...fields(),
+ },
+ `${message} — giving up on narration after ${elapsedMs}ms`,
+ );
+ deps.flushLog?.();
+ return;
+ }
+ deps.log?.info({ event, elapsedMs, ...fields() }, message);
+ deps.flushLog?.();
+ }, SPAWN_WAIT_HEARTBEAT_MS);
+ return stop;
+}
diff --git a/packages/desktop/src/main/desktop-logger.test.ts b/packages/desktop/src/main/desktop-logger.test.ts
index 30b875816..0ffc8f24d 100644
--- a/packages/desktop/src/main/desktop-logger.test.ts
+++ b/packages/desktop/src/main/desktop-logger.test.ts
@@ -1,5 +1,6 @@
+import pino from 'pino';
import { describe, expect, test } from 'vitest';
-import { flushDesktopLogger, getLogger } from './desktop-logger.ts';
+import { flushDesktopLogger, getLogger, getRootDesktopLogger } from './desktop-logger.ts';
describe('flushDesktopLogger', () => {
test('does not throw when called before any logging has initialized the destination', () => {
@@ -12,3 +13,19 @@ describe('flushDesktopLogger', () => {
expect(() => flushDesktopLogger()).not.toThrow();
});
});
+
+describe('error serialization (what the raw-err discipline buys)', () => {
+ test("this package's root logger binds the stack-preserving serializer on both err keys", () => {
+ const serializers = (
+ getRootDesktopLogger() as unknown as Record<symbol, Record<string, unknown>>
+ )[pino.symbols.serializersSym];
+ for (const key of ['err', 'error'] as const) {
+ expect(serializers?.[key]).toBe(pino.stdSerializers.err);
+ const rendered = (serializers?.[key] as (e: Error) => { message?: string; stack?: string })(
+ new Error('boom-probe'),
+ );
+ expect(rendered.message).toBe('boom-probe');
+ expect(rendered.stack ?? '').toContain('boom-probe');
+ }
+ });
+});
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index ea1dd69ee..84a168954 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -120,6 +120,12 @@ import {
shell,
utilityProcess,
} from 'electron';
+import {
+ BOOT_HEARTBEAT_EVENTS,
+ BOOT_HEARTBEAT_MAX_BEATS,
+ DESKTOP_BOOT_EVENT,
+ startupMarkLine,
+} from '../shared/boot-narration.ts';
import type {
ClaudeReadiness,
CliReadiness,
@@ -159,6 +165,7 @@ import {
type StartAutoUpdaterHandle,
} from './auto-updater.ts';
import { applyBackgroundThrottle } from './background-throttle.ts';
+import { type BootHeartbeatDeps, startBootHeartbeat } from './boot-heartbeat.ts';
import {
describeDesktopLanguage,
readStoredLanguagePreference,
@@ -940,7 +947,29 @@ function persistTerminalDockForWindow(
appState = committed.state;
return committed.result;
}
-const startupWaterfall = new StartupWaterfall({ otelEnabled: false });
+const startupWaterfall = new StartupWaterfall({
+ otelEnabled: false,
+ onMark: ({ phase, elapsedMs }) => {
+ getLogger('startup').info(startupMarkLine(phase, elapsedMs), `startup ${phase}`);
+ flushDesktopLogger();
+ },
+});
+const bootHeartbeatDeps: Required<BootHeartbeatDeps> = {
+ log: getLogger('startup'),
+ flushLog: flushDesktopLogger,
+ setInterval: (cb, ms) => setInterval(cb, ms).unref(),
+ clearInterval: (handle) => clearInterval(handle as ReturnType<typeof setInterval>),
+};
+
+const stopBootHeartbeat = startBootHeartbeat(
+ bootHeartbeatDeps,
+ BOOT_HEARTBEAT_EVENTS.boot,
+ '[startup] boot in progress',
+ () => ({ lastPhase: startupWaterfall.lastPhase ?? '(no phase marked yet)' }),
+ { maxBeats: BOOT_HEARTBEAT_MAX_BEATS },
+);
+app.on('will-quit', stopBootHeartbeat);
+
let firstWindowShown = false;
let waterfallDeadlineTimer: ReturnType<typeof setTimeout> | undefined;
@@ -965,6 +994,7 @@ function emitStartupWaterfall(): void {
function onFirstWindowShown(): void {
if (firstWindowShown) return;
firstWindowShown = true;
+ stopBootHeartbeat();
startupWaterfall.mark('windowShown');
if (startupWaterfall.readyToEmit) {
emitStartupWaterfall();
@@ -1419,6 +1449,7 @@ function ensureWindowManager() {
ensureDebugIpc().cancelPendingForUtility(utility);
},
log: getLogger('window-manager'),
+ flushLog: flushDesktopLogger,
recordServerExit: (info) =>
getServerExitRecorder().recordExit({ ...info, observer: 'utility-process' }),
createKeepalive: createDesktopKeepaliveFactory({
@@ -1502,6 +1533,10 @@ function openNavigator(pendingPayload?: ShareNavigatorPayload) {
),
showGate,
pendingPayload,
+ log: getLogger('navigator'),
+ flushLog: flushDesktopLogger,
+ setInterval: (cb, ms) => setInterval(cb, ms).unref(),
+ clearInterval: (handle) => clearInterval(handle as ReturnType<typeof setInterval>),
});
}
@@ -5634,7 +5669,7 @@ if (isDriverBootSmokeMode(process.env)) {
function bootPrimaryInstance(): void {
getRootDesktopLogger().info(
{
- event: 'desktop.boot',
+ event: DESKTOP_BOOT_EVENT,
version: app.getVersion(),
isPackaged: app.isPackaged,
electronVersion: process.versions.electron,
diff --git a/packages/desktop/src/main/navigator-window.ts b/packages/desktop/src/main/navigator-window.ts
index 9e1d072e5..ed782e22c 100644
--- a/packages/desktop/src/main/navigator-window.ts
+++ b/packages/desktop/src/main/navigator-window.ts
@@ -1,5 +1,8 @@
import type { LanguagePreference } from '@inkeep/open-knowledge-core';
+import { BOOT_HEARTBEAT_EVENTS } from '../shared/boot-narration.ts';
import { registerPendingDelivery } from '../shared/ipc-send.ts';
+import { type BootHeartbeatDeps, startBootHeartbeat } from './boot-heartbeat.ts';
+import type { DesktopLogger } from './desktop-logger.ts';
import type { ShowGateRegistry } from './show-gate.ts';
import type { ShareNavigatorPayload } from './url-scheme.ts';
import type { BrowserWindowLike, WindowManagerDeps } from './window-manager.ts';
@@ -13,10 +16,7 @@ function tryCloseNavigator(
try {
if (nav && nav.isDestroyed?.() !== true) nav.close?.();
} catch (err) {
- log('failed to close Navigator after project open', {
- projectPath: context.projectPath,
- err: err instanceof Error ? err.message : String(err),
- });
+ log('failed to close Navigator after project open', { projectPath: context.projectPath, err });
}
}
@@ -39,7 +39,11 @@ export function beginNavigatorHandoff(navAtStart: BrowserWindowLike | null): Nav
};
}
-interface NavigatorDeps {
+interface NavigatorDeps extends BootHeartbeatDeps {
+ log: Pick<DesktopLogger, 'info' | 'warn'>;
+ flushLog: () => void;
+ setInterval: (cb: () => void, ms: number) => unknown;
+ clearInterval: (handle: unknown) => void;
createWindow: WindowManagerDeps['createWindow'];
rendererEntryPath: string;
rendererDevUrl?: string | null;
@@ -70,17 +74,36 @@ export function createNavigatorWindow(deps: NavigatorDeps): BrowserWindowLike {
const payload = deps.pendingPayload;
registerPendingDelivery(window.webContents, 'ok:share:received', payload);
}
- const loadPromise = deps.rendererDevUrl
- ? window.loadURL(deps.rendererDevUrl)
- : window.loadFile(deps.rendererEntryPath);
- loadPromise.catch((err: unknown) => {
- console.warn(
- JSON.stringify({
- event: 'navigator-load-failed',
- target: deps.rendererDevUrl ?? deps.rendererEntryPath,
- message: err instanceof Error ? err.message : String(err),
- }),
- );
- });
+ const target = deps.rendererDevUrl ?? deps.rendererEntryPath;
+ const stopHeartbeat = startBootHeartbeat(
+ deps,
+ BOOT_HEARTBEAT_EVENTS.navigatorLoad,
+ '[navigator] still waiting for the navigator renderer to finish loading',
+ () => ({ target }),
+ );
+ let loadPromise: Promise<void>;
+ try {
+ loadPromise = deps.rendererDevUrl
+ ? window.loadURL(deps.rendererDevUrl)
+ : window.loadFile(deps.rendererEntryPath);
+ } catch (err) {
+ stopHeartbeat();
+ throw err;
+ }
+ loadPromise.then(
+ () => {
+ stopHeartbeat();
+ deps.log.info({ event: 'desktop-navigator-load-resolved', target }, '[navigator] loaded');
+ deps.flushLog();
+ },
+ (err: unknown) => {
+ stopHeartbeat();
+ deps.log.warn(
+ { event: 'desktop-navigator-load-failed', target, err },
+ '[navigator] load failed',
+ );
+ deps.flushLog();
+ },
+ );
return window;
}
diff --git a/packages/desktop/src/main/startup-waterfall.test.ts b/packages/desktop/src/main/startup-waterfall.test.ts
index 782e63197..9578a679b 100644
--- a/packages/desktop/src/main/startup-waterfall.test.ts
+++ b/packages/desktop/src/main/startup-waterfall.test.ts
@@ -175,3 +175,102 @@ describe('StartupWaterfall', () => {
expect(p?.otelEnabled).toBe(false);
});
});
+
+describe('mark-time narration (the boot log the smoke harness reads)', () => {
+ test('reports every phase as it happens, not only at emit time', () => {
+ const seen: { phase: string; elapsedMs: number }[] = [];
+ let clock = 500;
+ const w = new StartupWaterfall({
+ otelEnabled: false,
+ now: () => clock,
+ onMark: (m) => seen.push(m),
+ });
+ clock = 1_500;
+ w.mark('appReady', clock);
+ clock = 9_000;
+ w.mark('serverSpawned', clock);
+ clock = 26_000;
+ w.mark('serverLockReady', clock);
+ expect(seen.map((s) => s.phase)).toEqual(['appReady', 'serverSpawned', 'serverLockReady']);
+ expect(seen.map((s) => s.elapsedMs)).toEqual([0, 7_500, 24_500]);
+ });
+
+ test('shares one time origin with the waterfall payload, so both are comparable', () => {
+ const seen: { phase: string; elapsedMs: number }[] = [];
+ const w = new StartupWaterfall({
+ otelEnabled: false,
+ now: () => 0,
+ onMark: (m) => seen.push(m),
+ });
+ w.mark('appReady', 1_000);
+ w.mark('windowShown', 4_200);
+ expect(seen.find((s) => s.phase === 'windowShown')?.elapsedMs).toBe(
+ w.buildPayload().totalLaunchToShownMs,
+ );
+ });
+
+ test('measures a mark that precedes appReady from construction, the only origin it has', () => {
+ const seen: { phase: string; elapsedMs: number }[] = [];
+ const w = new StartupWaterfall({
+ otelEnabled: false,
+ now: () => 500,
+ onMark: (m) => seen.push(m),
+ });
+ w.mark('bootstrapDone', 900);
+ expect(seen[0]?.elapsedMs).toBe(400);
+ });
+
+ test('never lets a telemetry callback abandon boot', () => {
+ const w = new StartupWaterfall({
+ otelEnabled: false,
+ now: () => 0,
+ onMark: () => {
+ throw new Error('logger not ready');
+ },
+ });
+ expect(() => w.mark('appReady', 10)).not.toThrow();
+ expect(() => w.mark('windowShown', 2_010)).not.toThrow();
+ expect(w.buildPayload().totalLaunchToShownMs).toBe(2_000);
+ });
+
+ test('narrates a phase once, matching the first-write-wins mark semantics', () => {
+ const seen: string[] = [];
+ const w = new StartupWaterfall({
+ otelEnabled: false,
+ now: () => 0,
+ onMark: (m) => seen.push(m.phase),
+ });
+ w.mark('appReady', 10);
+ w.mark('appReady', 20);
+ expect(seen).toEqual(['appReady']);
+ });
+});
+
+describe('lastPhase (what the boot heartbeat names while it waits)', () => {
+ test('is undefined before anything is marked', () => {
+ expect(new StartupWaterfall({ otelEnabled: false }).lastPhase).toBeUndefined();
+ });
+
+ test('names the phase with the latest timestamp, not the last call', () => {
+ const w = new StartupWaterfall({ otelEnabled: false });
+ w.mark('serverSpawned', 9_000);
+ w.mark('appReady', 1_000);
+ expect(w.lastPhase).toBe('serverSpawned');
+ });
+
+ test('a repeat mark cannot rewind the phase, since the first write wins', () => {
+ const w = new StartupWaterfall({ otelEnabled: false });
+ w.mark('appReady', 1_000);
+ w.mark('serverSpawned', 2_000);
+ w.mark('appReady', 9_000);
+ expect(w.lastPhase).toBe('serverSpawned');
+ });
+
+ test('advances as boot advances', () => {
+ const w = new StartupWaterfall({ otelEnabled: false });
+ w.mark('appReady', 1_000);
+ expect(w.lastPhase).toBe('appReady');
+ w.mark('windowCreated', 3_000);
+ expect(w.lastPhase).toBe('windowCreated');
+ });
+});
diff --git a/packages/desktop/src/main/startup-waterfall.ts b/packages/desktop/src/main/startup-waterfall.ts
index f787b67fb..925351df5 100644
--- a/packages/desktop/src/main/startup-waterfall.ts
+++ b/packages/desktop/src/main/startup-waterfall.ts
@@ -48,6 +48,8 @@ export interface WaterfallPayload {
export interface StartupWaterfallOptions {
otelEnabled: boolean;
flushDeadlineMs?: number;
+ onMark?: (mark: { phase: WaterfallPhase; elapsedMs: number }) => void;
+ now?: () => number;
}
function round(n: number): number {
@@ -75,14 +77,37 @@ export class StartupWaterfall {
private emitted = false;
otelEnabled: boolean;
readonly flushDeadlineMs: number;
+ private readonly onMark:
+ | ((mark: { phase: WaterfallPhase; elapsedMs: number }) => void)
+ | undefined;
+ private readonly startedAtMs: number;
constructor(opts: StartupWaterfallOptions) {
this.otelEnabled = opts.otelEnabled;
this.flushDeadlineMs = opts.flushDeadlineMs ?? 1500;
+ this.onMark = opts.onMark;
+ this.startedAtMs = (opts.now ?? Date.now)();
+ }
+
+ get lastPhase(): WaterfallPhase | undefined {
+ let latest: WaterfallPhase | undefined;
+ let latestAt = Number.NEGATIVE_INFINITY;
+ for (const [phase, at] of this.marks) {
+ if (at >= latestAt) {
+ latestAt = at;
+ latest = phase;
+ }
+ }
+ return latest;
}
mark(phase: WaterfallPhase, atMs: number = Date.now()): void {
- if (!this.marks.has(phase)) this.marks.set(phase, atMs);
+ if (this.marks.has(phase)) return;
+ this.marks.set(phase, atMs);
+ const origin = this.marks.get('appReady') ?? this.startedAtMs;
+ try {
+ this.onMark?.({ phase, elapsedMs: round(atMs - origin) });
+ } catch {}
}
ingestServerBoot(boot: ServerBootTimings | undefined): void {
diff --git a/packages/desktop/src/main/window-manager.ts b/packages/desktop/src/main/window-manager.ts
index 7edcca4ae..3690f1fb9 100644
--- a/packages/desktop/src/main/window-manager.ts
+++ b/packages/desktop/src/main/window-manager.ts
@@ -9,10 +9,18 @@ import {
} from '@inkeep/open-knowledge-core';
import type { KeepaliveHandle } from '@inkeep/open-knowledge-core/keepalive';
import { getLocalDir } from '@inkeep/open-knowledge-server';
+import {
+ BOOT_HEARTBEAT_EVENTS,
+ SPAWN_STARTUP_DEADLINE_MS,
+ SPAWN_WAIT_EXTENSION_FACTOR,
+ SPAWN_WAIT_HEARTBEAT_MS,
+ UTILITY_INIT_TIMEOUT_MS,
+} from '../shared/boot-narration.ts';
import type { OkServerRestartOutcome } from '../shared/bridge-contract.ts';
import { registerPendingDelivery } from '../shared/ipc-send.ts';
import type { AssetOpenResult } from './asset-allowlist.ts';
import { attachAssetSafetyNet } from './asset-safety-net.ts';
+import { startBootHeartbeat } from './boot-heartbeat.ts';
import type { ServerExitInfo } from './server-exit-record.ts';
import type { ShowGateRegistry } from './show-gate.ts';
import type { RestoredWindow } from './state-store.ts';
@@ -21,9 +29,7 @@ import { classifyServerVersion } from './version-drift.ts';
const RESTART_SIGTERM_GRACE_MS = 3_000;
-const DEFAULT_SPAWN_STARTUP_DEADLINE_MS = 15_000;
-
-const SPAWN_WAIT_EXTENSION_FACTOR = 8;
+export { SPAWN_WAIT_HEARTBEAT_MS };
const FOREIGN_LOCK_PROBE_ATTEMPTS = 3;
const FOREIGN_LOCK_PROBE_RETRY_MS = 500;
@@ -238,6 +244,7 @@ export interface WindowManagerDeps {
removeDir?(dir: string): Promise<void>;
spawnLockPollDeadlineMs?: number;
spawnLockProgressDeadlineMs?: number;
+ flushLog?: () => void;
sigtermGraceMs?: number;
createKeepalive?(opts: { lockDir: string }): KeepaliveHandle;
rendererEntryPath: string;
@@ -1058,8 +1065,7 @@ export class WindowManager {
reactShellDistDir,
});
this.spawnedDetachedPids.set(canonicalKey, handle.pid);
- const POLL_DEADLINE_MS =
- this.deps.spawnLockPollDeadlineMs ?? DEFAULT_SPAWN_STARTUP_DEADLINE_MS;
+ const POLL_DEADLINE_MS = this.deps.spawnLockPollDeadlineMs ?? SPAWN_STARTUP_DEADLINE_MS;
const { lock, waitedDeadlineMs } = await this.pollServerLock(
lockDir,
POLL_DEADLINE_MS,
@@ -1193,7 +1199,7 @@ export class WindowManager {
});
}
- const INIT_TIMEOUT_MS = this.deps.utilityInitTimeoutMs ?? 15_000;
+ const INIT_TIMEOUT_MS = this.deps.utilityInitTimeoutMs ?? UTILITY_INIT_TIMEOUT_MS;
const utility = this.deps.forkUtility(
this.deps.utilityEntryPath,
@@ -1203,11 +1209,18 @@ export class WindowManager {
},
);
const utilityRef = utility;
+ const stopUtilityWaitHeartbeat = startBootHeartbeat(
+ this.deps,
+ BOOT_HEARTBEAT_EVENTS.utilityWait,
+ '[window-manager] still waiting for the utility process to report ready',
+ () => ({ pid: utilityRef.pid, lockDir, initTimeoutMs: INIT_TIMEOUT_MS }),
+ );
const ready = new Promise<{ port: number; apiOrigin: string }>((resolveReady, reject) => {
let settled = false;
const settle = (fn: () => void) => {
if (settled) return;
settled = true;
+ stopUtilityWaitHeartbeat();
utilityRef.removeListener?.('message', onMessage);
utilityRef.removeListener?.('exit', onExit);
fn();
@@ -1355,6 +1368,12 @@ export class WindowManager {
ownsServer: true,
};
const releaseLoadingContext = this.publishLoadingContext(context);
+ const stopRendererLoadHeartbeat = startBootHeartbeat(
+ this.deps,
+ BOOT_HEARTBEAT_EVENTS.rendererLoad,
+ '[window-manager] still waiting for the renderer to finish loading',
+ () => ({ projectPath }),
+ );
try {
if (this.deps.rendererDevUrl) {
await window.loadURL(this.deps.rendererDevUrl);
@@ -1377,6 +1396,7 @@ export class WindowManager {
this.windowsByPath.set(canonicalKey, context);
} finally {
+ stopRendererLoadHeartbeat();
releaseLoadingContext();
}
return context;
@@ -1467,7 +1487,7 @@ export class WindowManager {
throw err;
}
- const POLL_DEADLINE_MS = this.deps.spawnLockPollDeadlineMs ?? DEFAULT_SPAWN_STARTUP_DEADLINE_MS;
+ const POLL_DEADLINE_MS = this.deps.spawnLockPollDeadlineMs ?? SPAWN_STARTUP_DEADLINE_MS;
const { lock, waitedDeadlineMs } = await this.pollServerLock(
lockDir,
POLL_DEADLINE_MS,
@@ -1782,6 +1802,7 @@ export class WindowManager {
let effectiveDeadlineMs = deadlineMs;
let deadline = started + deadlineMs;
let extended = false;
+ let lastHeartbeatAt = started;
for (;;) {
const lock = reader(lockDir);
if (lock !== null && lock.draining !== true && lock.port > 0 && lock.kind !== undefined) {
@@ -1815,6 +1836,23 @@ export class WindowManager {
'[window-manager] server still starting at the spawn deadline — extending the wait',
);
}
+ const nowMs = Date.now();
+ if (nowMs - lastHeartbeatAt >= SPAWN_WAIT_HEARTBEAT_MS) {
+ lastHeartbeatAt = nowMs;
+ this.deps.log?.info(
+ {
+ event: BOOT_HEARTBEAT_EVENTS.spawnWait,
+ pid: child?.pid,
+ lockDir,
+ elapsedMs: nowMs - started,
+ childAlive: child !== undefined ? isAlive?.(child.pid) === true : undefined,
+ lockPublished: lock !== null,
+ extended,
+ },
+ '[window-manager] still waiting for the server lock',
+ );
+ this.deps.flushLog?.();
+ }
await new Promise<void>((resolveSleep) => {
this.deps.setTimeout(() => {
resolveSleep();
@@ -2035,6 +2073,12 @@ export class WindowManager {
ownsServer: false,
};
const releaseLoadingContext = this.publishLoadingContext(context);
+ const stopRendererLoadHeartbeat = startBootHeartbeat(
+ this.deps,
+ BOOT_HEARTBEAT_EVENTS.rendererLoad,
+ '[window-manager] still waiting for the renderer to finish loading',
+ () => ({ projectPath }),
+ );
try {
if (this.deps.rendererDevUrl) {
await window.loadURL(this.deps.rendererDevUrl);
@@ -2064,6 +2108,7 @@ export class WindowManager {
this.windowsByPath.set(canonicalKey, context);
} finally {
+ stopRendererLoadHeartbeat();
releaseLoadingContext();
}
return context;
diff --git a/packages/desktop/src/shared/boot-narration.ts b/packages/desktop/src/shared/boot-narration.ts
new file mode 100644
index 000000000..600f183b6
--- /dev/null
+++ b/packages/desktop/src/shared/boot-narration.ts
@@ -0,0 +1,45 @@
+import type { WaterfallPhase } from '../main/startup-waterfall.ts';
+
+export const SPAWN_WAIT_HEARTBEAT_MS = 5_000;
+
+export const SPAWN_STARTUP_DEADLINE_MS = 15_000;
+
+export const UTILITY_INIT_TIMEOUT_MS = 15_000;
+
+export const SPAWN_WAIT_EXTENSION_FACTOR = 8;
+
+export const BOOT_HEARTBEAT_MAX_BEATS = 24;
+
+export const DESKTOP_BOOT_EVENT = 'desktop.boot';
+
+export const BOOT_HEARTBEAT_EVENTS = {
+ boot: 'desktop-boot-progress',
+ utilityWait: 'desktop-utility-wait-progress',
+ spawnWait: 'desktop-spawn-wait-progress',
+ rendererLoad: 'desktop-renderer-load-progress',
+ navigatorLoad: 'desktop-navigator-load-progress',
+} as const;
+
+export const BOOT_HEARTBEAT_ABANDONED_SUFFIX = '-abandoned';
+
+export type BootHeartbeatEvent = (typeof BOOT_HEARTBEAT_EVENTS)[keyof typeof BOOT_HEARTBEAT_EVENTS];
+
+/** @lintignore knip reports this unused without the marker: its only consumer is tests/smoke/_helpers/launch-readiness.ts, which this package's knip project (src/**) does not analyze. Verified by deleting this line and running knip. */
+export function isBootHeartbeatEvent(event: string): boolean {
+ const base = event.endsWith(BOOT_HEARTBEAT_ABANDONED_SUFFIX)
+ ? event.slice(0, -BOOT_HEARTBEAT_ABANDONED_SUFFIX.length)
+ : event;
+ return (Object.values(BOOT_HEARTBEAT_EVENTS) as readonly string[]).includes(base);
+}
+
+const STARTUP_MARK_EVENT_PREFIX = 'desktop.startup.';
+
+export interface StartupMarkLine extends Record<string, unknown> {
+ readonly event: `${typeof STARTUP_MARK_EVENT_PREFIX}${WaterfallPhase}`;
+ readonly phase: WaterfallPhase;
+ readonly elapsedMs: number;
+}
+
+export function startupMarkLine(phase: WaterfallPhase, elapsedMs: number): StartupMarkLine {
+ return { event: `${STARTUP_MARK_EVENT_PREFIX}${phase}`, phase, elapsedMs };
+}
diff --git a/packages/desktop/tests/integration/boot-heartbeat-wiring.test.ts b/packages/desktop/tests/integration/boot-heartbeat-wiring.test.ts
new file mode 100644
index 000000000..15090b443
--- /dev/null
+++ b/packages/desktop/tests/integration/boot-heartbeat-wiring.test.ts
@@ -0,0 +1,61 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
+
+const indexTsPath = resolve(fileURLToPath(new URL('../../src/main/index.ts', import.meta.url)));
+const src = readFileSync(indexTsPath, 'utf-8');
+
+const FIX = (what: string): string =>
+ `\n[boot-heartbeat] ${what}\n\n` +
+ `The desktop smoke harness gives up when the app stops narrating for BOOT_LOG_STALL_MS.\n` +
+ `That bound is only sound while main emits a line every SPAWN_WAIT_HEARTBEAT_MS from process\n` +
+ `start until the first window is shown, which is what this wiring provides. Sever it and every\n` +
+ `smoke test still passes — safeShow() marks the window shown before it calls onShown, inside a\n` +
+ `warn-only try/catch — while a slow boot starts failing against a log that is silent by design.\n` +
+ `Three earlier revisions of this PR shipped a heartbeat wired to only part of the boot path.\n`;
+
+describe('global boot-heartbeat wiring (bypass-pin)', () => {
+ test('the heartbeat is armed exactly once and is budgeted', () => {
+ const arms = src.match(/\bstartBootHeartbeat\(/g) ?? [];
+ expect(
+ arms.length,
+ FIX(`index.ts has ${arms.length} \`startBootHeartbeat(\` call(s); expected exactly 1.`),
+ ).toBe(1);
+ expect(
+ /startBootHeartbeat\(\s*bootHeartbeatDeps\b[\s\S]{0,400}?maxBeats:\s*BOOT_HEARTBEAT_MAX_BEATS/.test(
+ src,
+ ),
+ FIX(
+ 'the global heartbeat is no longer budgeted, so a boot parked on a modal narrates forever.',
+ ),
+ ).toBe(true);
+ });
+
+ test('it is stopped when the first window is shown', () => {
+ const body = src.match(/function onFirstWindowShown\(\): void \{[\s\S]*?\n\}/)?.[0] ?? '';
+ expect(body, FIX('onFirstWindowShown() was not found in index.ts.')).not.toBe('');
+ expect(
+ body.includes('stopBootHeartbeat()'),
+ FIX('onFirstWindowShown() does not call stopBootHeartbeat().'),
+ ).toBe(true);
+ });
+
+ test('onFirstWindowShown is reachable from the show gate', () => {
+ expect(
+ /onShown:\s*\(\)\s*=>\s*onFirstWindowShown\(\)/.test(src),
+ FIX('the show gate no longer routes onShown to onFirstWindowShown().'),
+ ).toBe(true);
+ });
+
+ test('a boot that never shows a window still stops narrating, on every branch', () => {
+ expect(
+ /^app\.on\('will-quit', stopBootHeartbeat\);$/m.test(src),
+ FIX(
+ 'the will-quit stop is not registered at module scope beside the arm, so branches that ' +
+ 'never call bootPrimaryInstance() (driver-boot-smoke, the single-instance-lock loser) ' +
+ 'quit with the heartbeat still armed.',
+ ),
+ ).toBe(true);
+ });
+});
diff --git a/packages/desktop/tests/main/navigator-window.test.ts b/packages/desktop/tests/main/navigator-window.test.ts
index 89c4ed6ef..bdfae9002 100644
--- a/packages/desktop/tests/main/navigator-window.test.ts
+++ b/packages/desktop/tests/main/navigator-window.test.ts
@@ -3,6 +3,7 @@ import { beginNavigatorHandoff, createNavigatorWindow } from '../../src/main/nav
import type { ShowGateRegistry } from '../../src/main/show-gate.ts';
import type { ShareNavigatorPayload } from '../../src/main/url-scheme.ts';
import type { BrowserWindowLike } from '../../src/main/window-manager.ts';
+import { SPAWN_WAIT_HEARTBEAT_MS } from '../../src/shared/boot-narration.ts';
interface MockNav extends BrowserWindowLike {
closeMock: ReturnType<typeof vi.fn>;
@@ -73,12 +74,12 @@ describe('navigator close path', () => {
'failed to close Navigator after project open',
expect.objectContaining({
projectPath: '/path/to/proj',
- err: 'Object has been destroyed',
+ err: expect.objectContaining({ message: 'Object has been destroyed' }),
}),
);
});
- test('stringifies non-Error throws so the log carries diagnostic signal', () => {
+ test('passes a non-Error throw through untouched, for the serializer to render', () => {
const nav = makeNav({
closeImpl: () => {
throw 'native-string-throw';
@@ -220,6 +221,16 @@ describe('createNavigatorWindow — pendingPayload dom-ready gate (US-004)', ()
};
}
+ function silentNarration() {
+ return {
+ log: { info: () => {}, warn: () => {} },
+ flushLog: () => {},
+ setInterval: () => undefined,
+ clearInterval: () => {},
+ languagePreference: 'system' as const,
+ };
+ }
+
function makeShowGate(): ShowGateRegistry {
return {
register: () => () => {},
@@ -243,6 +254,7 @@ describe('createNavigatorWindow — pendingPayload dom-ready gate (US-004)', ()
test("cold path: pendingPayload registers webContents.once('dom-ready') BEFORE loadFile", () => {
const win = makeNavWindow();
createNavigatorWindow({
+ ...silentNarration(),
createWindow: () => win,
rendererEntryPath: '/fake/index.html',
appVersion: '9.9.9-test',
@@ -278,6 +290,7 @@ describe('createNavigatorWindow — pendingPayload dom-ready gate (US-004)', ()
test('cold path: no pendingPayload → no ok:share:received event fires on dom-ready', () => {
const win = makeNavWindow();
createNavigatorWindow({
+ ...silentNarration(),
createWindow: () => win,
rendererEntryPath: '/fake/index.html',
appVersion: '9.9.9-test',
@@ -303,6 +316,7 @@ describe('createNavigatorWindow — pendingPayload dom-ready gate (US-004)', ()
candidatePath: '/Users/me/playbooks/worktrees/wt-1',
};
createNavigatorWindow({
+ ...silentNarration(),
createWindow: () => win,
rendererEntryPath: '/fake/index.html',
appVersion: '9.9.9-test',
@@ -317,3 +331,94 @@ describe('createNavigatorWindow — pendingPayload dom-ready gate (US-004)', ()
expect(shareCall?.[1]).toEqual(payload);
});
});
+
+describe('navigator boot narration (the phase consent-dialog waits over)', () => {
+ function makeShowGate(): ShowGateRegistry {
+ return {
+ register: () => () => {},
+ fireThemeApplied: () => {},
+ };
+ }
+
+ function harness(loadResult: Promise<void>) {
+ const intervals: { cb: () => void; ms: number; cleared: boolean }[] = [];
+ const lines: Record<string, unknown>[] = [];
+ let flushes = 0;
+ const win = {
+ focus: vi.fn(() => {}),
+ isDestroyed: vi.fn(() => false),
+ on: vi.fn(() => {}) as BrowserWindowLike['on'],
+ close: vi.fn(() => {}),
+ loadFile: vi.fn(() => loadResult),
+ loadURL: vi.fn(() => loadResult),
+ webContents: { send: vi.fn(() => {}), once: vi.fn(() => {}), isLoading: vi.fn(() => false) },
+ } as unknown as BrowserWindowLike;
+ const deps = {
+ createWindow: () => win,
+ rendererEntryPath: '/fake/index.html',
+ appVersion: '9.9.9-test',
+ showGate: makeShowGate(),
+ log: {
+ info: (obj: Record<string, unknown>) => {
+ lines.push({ ...obj, level: 'info' });
+ },
+ warn: (obj: Record<string, unknown>) => {
+ lines.push({ ...obj, level: 'warn' });
+ },
+ },
+ flushLog: () => {
+ flushes += 1;
+ },
+ setInterval: (cb: () => void, ms: number) => {
+ const rec = { cb, ms, cleared: false };
+ intervals.push(rec);
+ return rec;
+ },
+ clearInterval: (handle: unknown) => {
+ (handle as { cleared: boolean }).cleared = true;
+ },
+ };
+ return { deps, intervals, lines, flushes: () => flushes };
+ }
+
+ test('narrates while the navigator renderer is still loading, on the app cadence', () => {
+ let resolveLoad: (() => void) | undefined;
+ const h = harness(
+ new Promise<void>((r) => {
+ resolveLoad = r;
+ }),
+ );
+ createNavigatorWindow(h.deps);
+
+ const beat = h.intervals.find((i) => !i.cleared);
+ expect(beat).toBeDefined();
+ expect(beat?.ms).toBe(SPAWN_WAIT_HEARTBEAT_MS);
+ beat?.cb();
+ beat?.cb();
+ expect(h.lines.filter((l) => l.event === 'desktop-navigator-load-progress')).toHaveLength(2);
+ expect(h.flushes()).toBe(2);
+ resolveLoad?.();
+ });
+
+ test('stops narrating and records the terminal line once the renderer resolves', async () => {
+ const h = harness(Promise.resolve());
+ createNavigatorWindow(h.deps);
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(h.intervals.every((i) => i.cleared)).toBe(true);
+ expect(h.lines.map((l) => l.event)).toContain('desktop-navigator-load-resolved');
+ });
+
+ test('a load failure reaches the boot log instead of only the console', async () => {
+ const h = harness(Promise.reject(new Error('ERR_FILE_NOT_FOUND')));
+ createNavigatorWindow(h.deps);
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(h.intervals.every((i) => i.cleared)).toBe(true);
+ const failure = h.lines.find((l) => l.event === 'desktop-navigator-load-failed');
+ expect(failure).toMatchObject({ level: 'warn' });
+ expect((failure?.err as Error).message).toBe('ERR_FILE_NOT_FOUND');
+ const resolved = h.lines.find((l) => l.event === 'desktop-navigator-load-resolved');
+ expect(resolved).toBeUndefined();
+ });
+});
diff --git a/packages/desktop/tests/main/window-manager-ephemeral.test.ts b/packages/desktop/tests/main/window-manager-ephemeral.test.ts
index cec138c14..cd9cd7f96 100644
--- a/packages/desktop/tests/main/window-manager-ephemeral.test.ts
+++ b/packages/desktop/tests/main/window-manager-ephemeral.test.ts
@@ -6,6 +6,7 @@ import {
type BrowserWindowLike,
type EphemeralOpenIdentity,
type ServerLockMetadataLike,
+ SPAWN_WAIT_HEARTBEAT_MS,
WindowManager,
type WindowManagerDeps,
} from '../../src/main/window-manager.ts';
@@ -1111,3 +1112,52 @@ describe('restartServerForWindow (IPC routing seam)', () => {
expect(outcome).toEqual({ ok: false, reason: 'eperm' });
});
});
+
+describe('spawn-wait heartbeat (the contract the smoke stall bound relies on)', () => {
+ test('narrates progress at least every SPAWN_WAIT_HEARTBEAT_MS while the lock is pending', async () => {
+ const env = buildEphemeralEnv();
+ const wm = new WindowManager(env.deps);
+ const lines: { event: string; atMs: number }[] = [];
+ let clock = 1_000_000;
+ let flushes = 0;
+ env.deps.flushLog = () => {
+ flushes += 1;
+ };
+ env.deps.log = {
+ info: (obj: Record<string, unknown>) => {
+ if (typeof obj.event === 'string') lines.push({ event: obj.event, atMs: clock });
+ },
+ warn: () => {},
+ error: () => {},
+ debug: () => {},
+ } as unknown as WindowManagerDeps['log'];
+ const realNow = Date.now;
+ Date.now = () => clock;
+ env.deps.setTimeout = ((cb: () => void) => {
+ clock += 50;
+ cb();
+ return null;
+ }) as unknown as WindowManagerDeps['setTimeout'];
+ env.deps.spawnLockPollDeadlineMs = 60_000;
+ const spawnAt = clock;
+ env.deps.readServerLock = () =>
+ clock - spawnAt >= 22_000
+ ? { pid: 4242, port: 51234, kind: 'interactive', url: 'http://127.0.0.1:51234' }
+ : null;
+ try {
+ await wm.createEphemeralWindow({
+ canonicalFilePath: FILE,
+ contentDir: PARENT,
+ docName: 'todo',
+ });
+ } finally {
+ Date.now = realNow;
+ }
+ expect(flushes).toBeGreaterThanOrEqual(4);
+ const beats = lines.filter((l) => l.event === 'desktop-spawn-wait-progress');
+ expect(beats.length).toBeGreaterThanOrEqual(4);
+ const stamps = [spawnAt, ...beats.map((b) => b.atMs)];
+ const gaps = stamps.slice(1).map((s, i) => s - (stamps[i] ?? 0));
+ expect(Math.max(...gaps)).toBeLessThanOrEqual(SPAWN_WAIT_HEARTBEAT_MS + 200);
+ });
+});
diff --git a/packages/desktop/tests/main/window-manager.test.ts b/packages/desktop/tests/main/window-manager.test.ts
index ac3a2c4a1..c7ce2ffac 100644
--- a/packages/desktop/tests/main/window-manager.test.ts
+++ b/packages/desktop/tests/main/window-manager.test.ts
@@ -13,6 +13,7 @@ import {
WindowManager,
type WindowManagerDeps,
} from '../../src/main/window-manager.ts';
+import { SPAWN_WAIT_HEARTBEAT_MS } from '../../src/shared/boot-narration.ts';
interface MockUtility extends UtilityProcessLike {
fire: (msg: unknown) => void;
@@ -3844,3 +3845,72 @@ describe('WindowManager — show-gate integration', () => {
expect(fiveSecondTimers).toHaveLength(0);
});
});
+
+describe('boot heartbeats (the unpackaged path CI runs)', () => {
+ let env: TestEnv;
+ let intervals: { cb: () => void; ms: number; cleared: boolean }[];
+ let beats: Record<string, unknown>[];
+ let flushes: number;
+
+ beforeEach(() => {
+ env = buildEnv();
+ intervals = [];
+ beats = [];
+ flushes = 0;
+ env.deps.setInterval = ((cb: () => void, ms: number) => {
+ const rec = { cb, ms, cleared: false };
+ intervals.push(rec);
+ return rec;
+ }) as unknown as WindowManagerDeps['setInterval'];
+ env.deps.clearInterval = ((handle: unknown) => {
+ (handle as { cleared: boolean }).cleared = true;
+ }) as unknown as WindowManagerDeps['clearInterval'];
+ env.deps.flushLog = () => {
+ flushes += 1;
+ };
+ env.deps.log = {
+ info: (obj: Record<string, unknown>) => {
+ if (typeof obj.event === 'string' && obj.event.endsWith('-progress')) beats.push(obj);
+ },
+ warn: () => {},
+ error: () => {},
+ debug: () => {},
+ } as unknown as WindowManagerDeps['log'];
+ });
+
+ test('narrates while the forked utility has not reported ready, and stops on ready', async () => {
+ const wm = new WindowManager(env.deps);
+ const promise = wm.createProjectWindow({ projectPath: '/tmp/test-project' });
+
+ const beat = intervals.find((i) => !i.cleared);
+ expect(beat).toBeDefined();
+ expect(beat?.ms).toBe(SPAWN_WAIT_HEARTBEAT_MS);
+ beat?.cb();
+ beat?.cb();
+ expect(beats).toHaveLength(2);
+ expect(beats[0]).toMatchObject({ event: 'desktop-utility-wait-progress' });
+ expect(flushes).toBe(2);
+
+ env.utilities[0]?.fire({ type: 'ready', port: 51234, apiOrigin: 'http://localhost:51234' });
+ await promise;
+ expect(intervals.every((i) => i.cleared)).toBe(true);
+ });
+
+ test('narrates the renderer load, the stage between windowCreated and loadUrlResolved', async () => {
+ const wm = new WindowManager(env.deps);
+ const promise = wm.createProjectWindow({ projectPath: '/tmp/test-project' });
+ env.utilities[0]?.fire({ type: 'ready', port: 51234, apiOrigin: 'http://localhost:51234' });
+ await promise;
+
+ const narrated = intervals.map((i) => {
+ beats.length = 0;
+ i.cb();
+ return { ms: i.ms, event: beats[0]?.event };
+ });
+ const renderer = narrated.find((n) => n.event === 'desktop-renderer-load-progress');
+ expect(narrated.map((n) => n.event)).toContain('desktop-utility-wait-progress');
+ expect(renderer).toBeDefined();
+ expect(renderer?.ms).toBe(SPAWN_WAIT_HEARTBEAT_MS);
+ expect(intervals.every((i) => i.cleared)).toBe(true);
+ });
+});
diff --git a/packages/desktop/tests/smoke/_helpers/launch-desktop.ts b/packages/desktop/tests/smoke/_helpers/launch-desktop.ts
index 070fc60fd..0cb77547b 100644
--- a/packages/desktop/tests/smoke/_helpers/launch-desktop.ts
+++ b/packages/desktop/tests/smoke/_helpers/launch-desktop.ts
@@ -95,5 +95,5 @@ export function desktopLaunchOptions(input: DesktopLaunchOptionsInput = {}): Des
? { args: [...extraArgs], timeout, executablePath: target.targetPath }
: { args: [target.targetPath, ...extraArgs], timeout };
- return { ...base, env: { ...process.env, ...input.env, OK_LANG: 'en' } };
+ return { ...base, env: { ...process.env, ...input.env, OK_LANG: 'en', OK_LOG_LEVEL: 'info' } };
}
diff --git a/packages/desktop/tests/smoke/_helpers/launch-readiness.test.ts b/packages/desktop/tests/smoke/_helpers/launch-readiness.test.ts
new file mode 100644
index 000000000..601bde8ed
--- /dev/null
+++ b/packages/desktop/tests/smoke/_helpers/launch-readiness.test.ts
@@ -0,0 +1,990 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { describe, expect, it } from 'vitest';
+import {
+ BOOT_HEARTBEAT_ABANDONED_SUFFIX,
+ BOOT_HEARTBEAT_EVENTS,
+ BOOT_HEARTBEAT_MAX_BEATS,
+ DESKTOP_BOOT_EVENT,
+ SPAWN_STARTUP_DEADLINE_MS,
+ SPAWN_WAIT_EXTENSION_FACTOR,
+ SPAWN_WAIT_HEARTBEAT_MS,
+ startupMarkLine,
+ UTILITY_INIT_TIMEOUT_MS,
+} from '../../../src/shared/boot-narration.ts';
+import {
+ BOOT_LOG_CAP_MS,
+ BOOT_LOG_HEARTBEAT_MS,
+ BOOT_LOG_STALL_MS,
+ type BootLogSnapshot,
+ bootGapSourceFor,
+ bootLogDirFor,
+ bootLogGapSummary,
+ classifyBootLog,
+ describeMissingBootLog,
+ formatBootGapLine,
+ giveUpReason,
+ hasBootCompleted,
+ launchDesktopApp,
+ launchHomeFor,
+ READY_WAIT_GIVE_UP_REASONS,
+ readBootLog,
+ readBootLogLines,
+ readyWaitsFor,
+ rememberLaunchHome,
+ tryBootLogFor,
+ tryFirstWaitFor,
+ type WindowMode,
+ waitForReadySignal,
+ waitForWindowByMode,
+} from './launch-readiness.ts';
+
+function markLine(phase: string, elapsedMs: number, time: string): string {
+ return JSON.stringify({ time, ...startupMarkLine(phase, elapsedMs) });
+}
+
+function seedHome(lines: string[] = []): string {
+ const home = mkdtempSync(join(tmpdir(), 'ok-readiness-'));
+ if (lines.length > 0) {
+ const dir = bootLogDirFor(home);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'desktop.2026-09-03.log'), `${lines.join('\n')}\n`, 'utf8');
+ }
+ return home;
+}
+
+function snapshot(over: Partial<BootLogSnapshot> = {}): BootLogSnapshot {
+ return {
+ dir: '/tmp/x/.ok/logs',
+ exists: true,
+ fileCount: 1,
+ unreadableReason: undefined,
+ unreadableFiles: [],
+ lines: [],
+ lineCount: 0,
+ lastEvent: undefined,
+ tail: '',
+ ...over,
+ };
+}
+
+describe('readBootLog', () => {
+ it('reports absent when the app never wrote a log', () => {
+ const snap = readBootLog(seedHome());
+ expect(snap.exists).toBe(false);
+ expect(snap.lineCount).toBe(0);
+ expect(snap.lastEvent).toBeUndefined();
+ });
+
+ it('names the boot phase the app actually emitted, not the record type', () => {
+ const snap = readBootLog(
+ seedHome([
+ JSON.stringify({ event: 'desktop.boot', version: '1.2.3' }),
+ markLine('serverSpawned', 8_500, '2026-09-04T00:00:08.500Z'),
+ ]),
+ );
+ expect(snap.exists).toBe(true);
+ expect(snap.lineCount).toBe(2);
+ expect(snap.lastEvent).toBe('desktop.startup.serverSpawned');
+ });
+
+ it('skips unparseable trailing lines when naming the last event', () => {
+ const snap = readBootLog(
+ seedHome([
+ markLine('serverLockReady', 25_500, '2026-09-04T00:00:25.500Z'),
+ 'not-json-at-all',
+ ]),
+ );
+ expect(snap.lastEvent).toBe('desktop.startup.serverLockReady');
+ });
+
+ it('exposes the same lines readBootLogLines returns, from one scan', () => {
+ const home = seedHome([
+ JSON.stringify({ event: DESKTOP_BOOT_EVENT }),
+ markLine('appReady', 0, '2026-09-04T00:00:00.000Z'),
+ ]);
+ expect(readBootLogLines(home)).toEqual(readBootLog(home).lines);
+ expect(readBootLogLines(home)).toHaveLength(2);
+ });
+
+ it('separates "present but empty" from "the app never logged"', () => {
+ const home = seedHome([]);
+ mkdirSync(bootLogDirFor(home), { recursive: true });
+ writeFileSync(join(bootLogDirFor(home), 'desktop.2026-09-03.log'), '', 'utf8');
+ const snap = readBootLog(home);
+ expect(snap.exists).toBe(true);
+ expect(snap.fileCount).toBe(1);
+ expect(snap.lineCount).toBe(0);
+ });
+});
+
+describe('waitForReadySignal — progress gating', () => {
+ it('returns as soon as the probe resolves', async () => {
+ const found = await waitForReadySignal<string>({
+ probe: async () => 'editor-page',
+ home: '/unused',
+ what: 'editor window',
+ readLog: () => snapshot(),
+ now: () => 0,
+ sleep: async () => {},
+ });
+ expect(found).toBe('editor-page');
+ });
+
+ it('keeps waiting while the app is still logging progress, well past the stall bound', async () => {
+ let clock = 0;
+ let ticks = 0;
+ const found = await waitForReadySignal<string>({
+ probe: async () => (clock >= BOOT_LOG_CAP_MS - 2_000 ? 'editor-page' : undefined),
+ home: '/unused',
+ what: 'editor window',
+ now: () => clock,
+ sleep: async () => {
+ clock += 1_000;
+ ticks += 1;
+ },
+ readLog: () => snapshot({ lineCount: ticks, lastEvent: 'serverSpawned' }),
+ });
+ expect(found).toBe('editor-page');
+ expect(clock).toBeGreaterThan(BOOT_LOG_STALL_MS);
+ });
+
+ it('gives up long before the cap when the app logs nothing new', async () => {
+ let clock = 0;
+ await expect(
+ waitForReadySignal<string>({
+ probe: async () => undefined,
+ home: '/unused',
+ what: 'editor window',
+ now: () => clock,
+ sleep: async () => {
+ clock += 1_000;
+ },
+ readLog: () => snapshot({ lineCount: 3, lastEvent: 'desktop.boot' }),
+ }),
+ ).rejects.toThrow(/logged no new boot activity/);
+ expect(clock).toBeLessThan(BOOT_LOG_CAP_MS);
+ expect(clock).toBeLessThanOrEqual(BOOT_LOG_STALL_MS + 1_000);
+ });
+
+ it('names the boot phase and the log tail when it gives up', async () => {
+ let clock = 0;
+ await expect(
+ waitForReadySignal<string>({
+ probe: async () => undefined,
+ home: '/unused',
+ what: 'editor window',
+ now: () => clock,
+ sleep: async () => {
+ clock += 1_000;
+ },
+ readLog: () =>
+ snapshot({
+ lineCount: 1,
+ lastEvent: 'spawn-lock-timeout',
+ tail: '{"event":"spawn-lock-timeout"}',
+ }),
+ }),
+ ).rejects.toThrow(/spawn-lock-timeout/);
+ });
+
+ it('says the log is missing when the app never logged at all', async () => {
+ let clock = 0;
+ await expect(
+ waitForReadySignal<string>({
+ probe: async () => undefined,
+ home: '/unused',
+ what: 'editor window',
+ now: () => clock,
+ sleep: async () => {
+ clock += 1_000;
+ },
+ readLog: () => snapshot({ exists: false }),
+ }),
+ ).rejects.toThrow(/NOT FOUND/);
+ });
+
+ it('says the log cannot explain the wait, rather than blaming the app, on the stall path', async () => {
+ let guardClock = 0;
+ const error = await waitForReadySignal<string>({
+ probe: async () => undefined,
+ home: '/unused',
+ what: 'editor window',
+ now: () => guardClock,
+ sleep: async () => {
+ guardClock += 1_000;
+ },
+ readLog: () => snapshot({ exists: false }),
+ }).catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(Error);
+ expect((error as Error).message).toContain('and the boot log cannot say why');
+ expect((error as Error).message).not.toContain('stopped making progress');
+ expect(guardClock).toBe(BOOT_LOG_STALL_MS);
+ });
+
+ it('stops at the absolute cap even while progress keeps arriving', async () => {
+ let clock = 0;
+ let ticks = 0;
+ await expect(
+ waitForReadySignal<string>({
+ probe: async () => undefined,
+ home: '/unused',
+ what: 'editor window',
+ now: () => clock,
+ sleep: async () => {
+ clock += 1_000;
+ ticks += 1;
+ },
+ readLog: () => snapshot({ lineCount: ticks }),
+ }),
+ ).rejects.toThrow(/kept logging boot activity/);
+ expect(clock).toBeGreaterThanOrEqual(BOOT_LOG_CAP_MS);
+ });
+
+ it('surfaces the last probe error instead of swallowing it', async () => {
+ let clock = 0;
+ await expect(
+ waitForReadySignal<string>({
+ probe: async () => {
+ throw new Error('Execution context was destroyed');
+ },
+ home: '/unused',
+ what: 'editor window',
+ now: () => clock,
+ sleep: async () => {
+ clock += 1_000;
+ },
+ readLog: () => snapshot({ lineCount: 1 }),
+ }),
+ ).rejects.toThrow(/Execution context was destroyed/);
+ });
+
+ it('still reports a probe error that stopped throwing before the deadline', async () => {
+ let clock = 0;
+ await expect(
+ waitForReadySignal<string>({
+ probe: async () => {
+ if (clock < 5_000) throw new Error('Execution context was destroyed');
+ return undefined;
+ },
+ home: '/unused',
+ what: 'editor window',
+ now: () => clock,
+ sleep: async () => {
+ clock += 1_000;
+ },
+ readLog: () => snapshot({ lineCount: 1 }),
+ }),
+ ).rejects.toThrow(/Probe threw on 5 of \d+ polls; last: Execution context was destroyed/);
+ });
+
+ it('says plainly when the probe never threw, so absence is not read as evidence', async () => {
+ let clock = 0;
+ await expect(
+ waitForReadySignal<string>({
+ probe: async () => undefined,
+ home: '/unused',
+ what: 'editor window',
+ now: () => clock,
+ sleep: async () => {
+ clock += 1_000;
+ },
+ readLog: () => snapshot({ lineCount: 1 }),
+ }),
+ ).rejects.toThrow(/Probe errors: none on any poll\./);
+ });
+
+ it("liveness 'none' waits out a post-boot silence the stall rule would have failed", async () => {
+ let clock = 0;
+ const found = await waitForReadySignal<string>({
+ probe: async () => (clock >= 20_000 ? 'terminal-page' : undefined),
+ home: '/unused',
+ what: 'terminal window',
+ liveness: 'none',
+ capMs: BOOT_LOG_CAP_MS,
+ now: () => clock,
+ sleep: async () => {
+ clock += 1_000;
+ },
+ readLog: () => snapshot({ lineCount: 7, lastEvent: 'desktop.startup.windowShown' }),
+ });
+ expect(found).toBe('terminal-page');
+ expect(clock).toBeGreaterThan(BOOT_LOG_STALL_MS);
+ });
+});
+
+describe('waitForWindowByMode', () => {
+ it('returns the page whose renderer reports the requested mode', async () => {
+ const editor = { evaluate: async () => 'editor' };
+ const navigator = { evaluate: async () => 'navigator' };
+ const found = await waitForWindowByMode({ windows: () => [navigator, editor] }, 'editor', {
+ home: '/unused',
+ });
+ expect(found).toBe(editor);
+ });
+
+ it('keeps scanning past a page that throws, and finds a later match', async () => {
+ const broken = {
+ evaluate: async (): Promise<string | undefined> => {
+ throw new Error('Target closed');
+ },
+ };
+ const editor = { evaluate: async () => 'editor' };
+ const found = await waitForWindowByMode({ windows: () => [broken, editor] }, 'editor', {
+ home: '/unused',
+ });
+ expect(found).toBe(editor);
+ });
+});
+
+describe('launchDesktopApp', () => {
+ it('passes the app through on success', async () => {
+ const app = { id: 'app' };
+ const launched = await launchDesktopApp({ launch: async () => app }, {}, { home: '/unused' });
+ expect(launched).toBe(app);
+ });
+
+ it('annotates a launch timeout with the boot phase the harness could not otherwise see', async () => {
+ await expect(
+ launchDesktopApp(
+ {
+ launch: async () => {
+ throw new Error('electron.launch: Timeout 30000ms exceeded.');
+ },
+ },
+ {},
+ {
+ home: '/unused',
+ readLog: () =>
+ snapshot({ lineCount: 4, lastEvent: 'appReady', tail: '{"event":"appReady"}' }),
+ },
+ ),
+ ).rejects.toThrow(/appReady/);
+ });
+
+ it('keeps the original launch failure text alongside the annotation', async () => {
+ await expect(
+ launchDesktopApp(
+ {
+ launch: async () => {
+ throw new Error('electron.launch: Timeout 30000ms exceeded.');
+ },
+ },
+ {},
+ { home: '/unused', readLog: () => snapshot({ exists: false }) },
+ ),
+ ).rejects.toThrow(/Timeout 30000ms exceeded/);
+ });
+});
+
+describe('launch-home registry', () => {
+ it('remembers the home a launch used, so readiness can find the boot log', () => {
+ const app = {};
+ rememberLaunchHome(app, '/tmp/home-a');
+ expect(launchHomeFor(app)).toBe('/tmp/home-a');
+ });
+
+ it('records the home as part of a successful launch', async () => {
+ const app = {};
+ await launchDesktopApp({ launch: async () => app }, {}, { home: '/tmp/home-b' });
+ expect(launchHomeFor(app)).toBe('/tmp/home-b');
+ });
+
+ it('explains itself when an app was not launched through the helper', () => {
+ expect(() => launchHomeFor({})).toThrow(/not launched through launchDesktopApp/);
+ });
+
+ it('lets waitForWindowByMode resolve the home from the registry', async () => {
+ const editor = { evaluate: async () => 'editor' };
+ const app = { windows: () => [editor] };
+ rememberLaunchHome(app, '/tmp/home-c');
+ await expect(waitForWindowByMode(app, 'editor')).resolves.toBe(editor);
+ });
+});
+
+describe("stall bound is a contract against the app's boot narration", () => {
+ it("reads its cadence from the app's own heartbeat constant, not a second copy", () => {
+ expect(BOOT_LOG_HEARTBEAT_MS).toBe(SPAWN_WAIT_HEARTBEAT_MS);
+ });
+
+ it("tolerates at least two heartbeats missed at the app's cadence", () => {
+ expect(BOOT_LOG_STALL_MS).toBeGreaterThanOrEqual(SPAWN_WAIT_HEARTBEAT_MS * 2);
+ });
+
+ it("does not fail a boot that keeps heartbeating on the app's own cadence", async () => {
+ let clock = 0;
+ let lines = 0;
+ const found = await waitForReadySignal<string>({
+ probe: async () => (clock >= BOOT_LOG_CAP_MS - 2_000 ? 'editor-page' : undefined),
+ home: '/unused',
+ what: 'editor window',
+ now: () => clock,
+ sleep: async () => {
+ clock += 1_000;
+ if (clock % BOOT_LOG_HEARTBEAT_MS === 0) lines += 1;
+ },
+ readLog: () => snapshot({ lineCount: lines, lastEvent: 'desktop-spawn-wait-progress' }),
+ });
+ expect(found).toBe('editor-page');
+ expect(clock).toBeGreaterThan(BOOT_LOG_STALL_MS);
+ });
+});
+
+describe('bootLogGapSummary', () => {
+ it("reports the largest silence between the app's own stages", () => {
+ const lines = [
+ JSON.stringify({ time: '2026-09-04T00:00:00.000Z', event: DESKTOP_BOOT_EVENT }),
+ markLine('serverSpawned', 2_000, '2026-09-04T00:00:02.000Z'),
+ JSON.stringify({
+ time: '2026-09-04T00:00:16.000Z',
+ event: 'desktop-spawn-wait-progress',
+ }),
+ ];
+ const s = bootLogGapSummary(lines);
+ expect(s.lineCount).toBe(3);
+ expect(s.maxGapMs).toBe(14_000);
+ expect(s.maxGapAfterPhase).toBe('desktop.startup.serverSpawned');
+ expect(s.beatsSeen).toBe(1);
+ expect(s.bootComplete).toBe(false);
+ });
+
+ it("measures the app's own stages, not the liveness beat bracketing them", () => {
+ const lines = [
+ markLine('appReady', 0, '2026-09-04T00:00:00.000Z'),
+ JSON.stringify({
+ time: '2026-09-04T00:00:05.000Z',
+ event: BOOT_HEARTBEAT_EVENTS.boot,
+ lastPhase: 'appReady',
+ }),
+ JSON.stringify({
+ time: '2026-09-04T00:00:10.000Z',
+ event: BOOT_HEARTBEAT_EVENTS.boot,
+ lastPhase: 'appReady',
+ }),
+ markLine('serverSpawned', 12_000, '2026-09-04T00:00:12.000Z'),
+ ];
+ const s = bootLogGapSummary(lines);
+ expect(s.maxGapMs).toBe(12_000);
+ expect(s.maxGapAfterPhase).toBe('desktop.startup.appReady');
+ expect(s.beatsSeen).toBe(2);
+ expect(s.lastBeatPhase).toBe('appReady');
+ expect(s.phases).toEqual(['desktop.startup.appReady', 'desktop.startup.serverSpawned']);
+ });
+
+ it('reports the silence the app is still sitting in, not just the hops it finished', () => {
+ const beat = (sec: number) =>
+ JSON.stringify({
+ time: `2026-09-04T00:00:${String(sec).padStart(2, '0')}.000Z`,
+ event: BOOT_HEARTBEAT_EVENTS.boot,
+ lastPhase: 'serverSpawned',
+ });
+ const s = bootLogGapSummary([
+ JSON.stringify({ time: '2026-09-04T00:00:00.000Z', event: DESKTOP_BOOT_EVENT }),
+ markLine('serverSpawned', 2_000, '2026-09-04T00:00:02.000Z'),
+ beat(7),
+ beat(12),
+ beat(17),
+ beat(22),
+ beat(27),
+ ]);
+ expect(s.maxGapMs).toBe(25_000);
+ expect(s.maxGapAfterPhase).toBe('desktop.startup.serverSpawned');
+ expect(s.openStageMs).toBe(25_000);
+ expect(s.lastBeatPhase).toBe('serverSpawned');
+ });
+
+ it('classifies an abandoned heartbeat as a beat, not as a boot stage', () => {
+ const s = bootLogGapSummary([
+ markLine('appReady', 0, '2026-09-04T00:00:00.000Z'),
+ JSON.stringify({
+ time: '2026-09-04T00:02:05.000Z',
+ event: `${BOOT_HEARTBEAT_EVENTS.boot}${BOOT_HEARTBEAT_ABANDONED_SUFFIX}`,
+ lastPhase: 'appReady',
+ }),
+ ]);
+ expect(s.phases).toEqual(['desktop.startup.appReady']);
+ expect(s.beatsSeen).toBe(1);
+ expect(s.openStageMs).toBe(125_000);
+ });
+
+ it('describes the launch in progress, not the one that already finished', () => {
+ const boot = (t: string) => JSON.stringify({ time: t, event: DESKTOP_BOOT_EVENT });
+ const s = bootLogGapSummary([
+ boot('2026-09-04T00:00:00.000Z'),
+ markLine('appReady', 0, '2026-09-04T00:00:01.000Z'),
+ markLine('windowShown', 2_000, '2026-09-04T00:00:02.000Z'),
+ boot('2026-09-04T00:01:00.000Z'),
+ markLine('serverSpawned', 1_000, '2026-09-04T00:01:01.000Z'),
+ JSON.stringify({
+ time: '2026-09-04T00:01:26.000Z',
+ event: BOOT_HEARTBEAT_EVENTS.boot,
+ lastPhase: 'serverSpawned',
+ }),
+ ]);
+ expect(s.bootComplete).toBe(false);
+ expect(s.openStageMs).toBe(25_000);
+ expect(s.maxGapAfterPhase).toBe('desktop.startup.serverSpawned');
+ expect(s.phases).not.toContain('desktop.startup.appReady');
+ });
+
+ it('reports how long the app took to boot, not just the gaps within it', () => {
+ const s = bootLogGapSummary([
+ JSON.stringify({ time: '2026-09-04T00:00:00.000Z', event: DESKTOP_BOOT_EVENT }),
+ markLine('appReady', 1_000, '2026-09-04T00:00:01.000Z'),
+ markLine('serverSpawned', 3_000, '2026-09-04T00:00:03.000Z'),
+ markLine('windowShown', 9_000, '2026-09-04T00:00:09.000Z'),
+ ]);
+ expect(s.totalBootMs).toBe(9_000);
+ expect(s.maxGapMs).toBe(6_000);
+ expect(s.bootComplete).toBe(true);
+ });
+
+ it('counts trailing beats in the total, which stop at no phase line', () => {
+ const s = bootLogGapSummary([
+ JSON.stringify({ time: '2026-09-04T00:00:00.000Z', event: DESKTOP_BOOT_EVENT }),
+ markLine('serverSpawned', 1_000, '2026-09-04T00:00:01.000Z'),
+ JSON.stringify({
+ time: '2026-09-04T00:00:06.000Z',
+ event: BOOT_HEARTBEAT_EVENTS.boot,
+ lastPhase: 'serverSpawned',
+ }),
+ JSON.stringify({
+ time: '2026-09-04T00:00:11.000Z',
+ event: BOOT_HEARTBEAT_EVENTS.boot,
+ lastPhase: 'serverSpawned',
+ }),
+ ]);
+ expect(s.totalBootMs).toBe(11_000);
+ expect(s.phases.at(-1)).toBe('desktop.startup.serverSpawned');
+ });
+
+ it('measures boot, not the idle test that follows it', () => {
+ const lines = [
+ markLine('appReady', 0, '2026-09-04T00:00:00.000Z'),
+ markLine('windowShown', 3_000, '2026-09-04T00:00:03.000Z'),
+ JSON.stringify({ time: '2026-09-04T00:00:45.000Z', event: 'terminal-session-exit' }),
+ ];
+ const s = bootLogGapSummary(lines);
+ expect(s.bootComplete).toBe(true);
+ expect(s.lineCount).toBe(2);
+ expect(s.maxGapMs).toBe(3_000);
+ });
+
+ it('is empty-safe when the app logged nothing', () => {
+ expect(bootLogGapSummary([])).toEqual({
+ totalBootMs: 0,
+ lineCount: 0,
+ maxGapMs: 0,
+ maxGapAfterPhase: undefined,
+ openStageMs: 0,
+ beatsSeen: 0,
+ bootComplete: false,
+ phases: [],
+ });
+ });
+});
+
+describe('the cap is a livelock backstop, deliberately tighter than the app can take', () => {
+ it('keeps the stall bound below the cap, so a silent boot reads as silence not as a timeout', () => {
+ expect(BOOT_LOG_STALL_MS).toBeLessThan(BOOT_LOG_CAP_MS);
+ });
+
+ it("clears the unpackaged app's own utility-fork deadline", () => {
+ expect(BOOT_LOG_CAP_MS).toBeGreaterThan(UTILITY_INIT_TIMEOUT_MS);
+ });
+
+ it('lets the cap stay the operative verdict on a boot that never shows a window', () => {
+ expect(BOOT_HEARTBEAT_MAX_BEATS * SPAWN_WAIT_HEARTBEAT_MS).toBeGreaterThan(BOOT_LOG_CAP_MS);
+ });
+
+ it("is deliberately below the packaged path's graduated spawn budget", () => {
+ expect(BOOT_LOG_CAP_MS).toBeLessThan(SPAWN_STARTUP_DEADLINE_MS * SPAWN_WAIT_EXTENSION_FACTOR);
+ });
+});
+
+describe('the stall rule applies only while boot narration is live', () => {
+ const late = (mode: string) => {
+ let polls = 0;
+ return { evaluate: async () => (++polls >= 20 ? mode : undefined) };
+ };
+ const waitFor = (
+ mode: WindowMode,
+ page: { evaluate: () => Promise<string | undefined> },
+ home: string,
+ ) =>
+ waitForWindowByMode({ windows: () => [page] }, mode, {
+ home,
+ stallMs: 150,
+ pollMs: 20,
+ capMs: 5_000,
+ });
+
+ it('arms it for a wait issued before the app has shown its first window', async () => {
+ const home = seedHome([JSON.stringify({ event: DESKTOP_BOOT_EVENT })]);
+ await expect(waitFor('editor', late('editor'), home)).rejects.toThrow(
+ /logged no new boot activity/,
+ );
+ await expect(waitFor('navigator', late('navigator'), home)).rejects.toThrow(
+ /logged no new boot activity/,
+ );
+ });
+
+ it('drops it once boot is over, whatever the mode — the log is silent by design then', async () => {
+ const home = seedHome([
+ JSON.stringify({ event: DESKTOP_BOOT_EVENT }),
+ markLine('windowShown', 3_000, '2026-09-04T00:00:03.000Z'),
+ ]);
+ const editor = late('editor');
+ await expect(waitFor('editor', editor, home)).resolves.toBe(editor);
+ const terminal = late('terminal');
+ await expect(waitFor('terminal', terminal, home)).resolves.toBe(terminal);
+ });
+
+ it('disarms mid-wait when the app shows its window, so the cap decides not the stall', async () => {
+ let clock = 0;
+ const lines = [JSON.stringify({ event: DESKTOP_BOOT_EVENT, time: '2026-09-04T00:00:00.000Z' })];
+ await expect(
+ waitForReadySignal<string>({
+ probe: async () => undefined,
+ home: '/unused',
+ what: 'editor window',
+ capMs: 20_000,
+ now: () => clock,
+ sleep: async () => {
+ clock += 1_000;
+ if (clock === 3_000)
+ lines.push(markLine('windowShown', 3_000, '2026-09-04T00:00:03.000Z'));
+ },
+ readLog: () => snapshot({ lines, lineCount: lines.length, lastEvent: 'desktop.boot' }),
+ }),
+ ).rejects.toThrow(/kept logging boot activity/);
+ expect(clock).toBeGreaterThan(BOOT_LOG_STALL_MS);
+ });
+
+ it('reads boot completion off the app mark, not off a mode list', () => {
+ expect(hasBootCompleted([JSON.stringify({ event: DESKTOP_BOOT_EVENT })])).toBe(false);
+ expect(hasBootCompleted([markLine('windowShown', 0, '2026-09-04T00:00:00.000Z')])).toBe(true);
+ expect(
+ hasBootCompleted([
+ markLine('windowShown', 0, '2026-09-04T00:00:00.000Z'),
+ JSON.stringify({ event: DESKTOP_BOOT_EVENT, time: '2026-09-04T00:01:00.000Z' }),
+ ]),
+ ).toBe(false);
+ });
+});
+
+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 () => {
+ 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'),
+ ]);
+ const editor = { evaluate: async () => 'editor' };
+ const app = { windows: () => [editor] };
+ rememberLaunchHome(app, home);
+ await waitForWindowByMode(app, 'editor');
+ rmSync(home, { recursive: true, force: true });
+ expect(readBootLogLines(home)).toEqual([]);
+ expect(tryBootLogFor(app)).toHaveLength(2);
+ });
+
+ it('remembers nothing when the app never logged, so callers can say so', async () => {
+ const editor = { evaluate: async () => 'editor' };
+ const app = { windows: () => [editor] };
+ rememberLaunchHome(app, seedHome());
+ await waitForWindowByMode(app, 'editor');
+ expect(tryBootLogFor(app)).toBeUndefined();
+ });
+});
+
+describe('the recorded ready wait names which wait it measured', () => {
+ const slowFirstPoll = () => {
+ const editor = { evaluate: async () => 'editor' };
+ let polls = 0;
+ return { windows: () => (polls++ === 0 ? [] : [editor]) };
+ };
+
+ it('carries the cap that actually bounded it, not the module default', async () => {
+ const app = slowFirstPoll();
+ rememberLaunchHome(app, seedHome());
+ await waitForWindowByMode(app, 'editor', { pollMs: 80, capMs: 9_000 });
+ const wait = tryFirstWaitFor(app);
+ expect(wait?.what).toBe('editor window');
+ expect(wait?.capMs).toBe(9_000);
+ expect(wait?.gaveUp).toBe(false);
+ expect(wait?.elapsedMs).toBeGreaterThanOrEqual(50);
+ });
+
+ it('reports the first wait, not a later re-find of an already-open window', async () => {
+ const app = slowFirstPoll();
+ rememberLaunchHome(app, seedHome());
+ await waitForWindowByMode(app, 'editor', { pollMs: 80 });
+ await waitForWindowByMode(app, 'editor', { capMs: 10_000 });
+ const waits = readyWaitsFor(app) ?? [];
+ expect(waits).toHaveLength(2);
+ const launch = tryFirstWaitFor(app);
+ expect(launch?.ordinal).toBe(0);
+ expect(launch?.capMs).toBe(BOOT_LOG_CAP_MS);
+ expect(launch?.elapsedMs).toBeGreaterThan(waits[1]?.elapsedMs ?? Number.POSITIVE_INFINITY);
+ });
+
+ it('records the wait that gave up, so the over-cap sample is not dropped', async () => {
+ const app = { windows: () => [] };
+ rememberLaunchHome(app, seedHome());
+ await expect(waitForWindowByMode(app, 'editor', { capMs: 300, pollMs: 60 })).rejects.toThrow();
+ const wait = tryFirstWaitFor(app);
+ expect(wait?.gaveUp).toBe(true);
+ expect(wait?.capMs).toBe(300);
+ expect(wait?.reason).toBe('notfound');
+ });
+
+ it('separates a cap fired over a narrating app from one that never logged', async () => {
+ const app = { windows: () => [] };
+ rememberLaunchHome(
+ app,
+ seedHome([
+ JSON.stringify({ time: '2026-09-04T00:00:00.000Z', event: DESKTOP_BOOT_EVENT }),
+ markLine('appReady', 0, '2026-09-04T00:00:01.000Z'),
+ ]),
+ );
+ await expect(waitForWindowByMode(app, 'editor', { capMs: 300, pollMs: 60 })).rejects.toThrow();
+ expect(tryFirstWaitFor(app)?.reason).toBe('cap');
+ });
+});
+
+describe('one classifier decides both the prose and the reason token', () => {
+ it('calls a per-file read failure unreadable, though the directory itself read fine', () => {
+ expect(
+ classifyBootLog(
+ snapshot({
+ exists: true,
+ unreadableFiles: ['desktop.2026-09-04.log (EBUSY)'],
+ lineCount: 3,
+ }),
+ ),
+ ).toBe('unreadable');
+ });
+
+ it('keeps unreadable ahead of notfound, which co-occur whenever the directory itself failed', () => {
+ expect(classifyBootLog(snapshot({ exists: false, unreadableReason: 'EACCES' }))).toBe(
+ 'unreadable',
+ );
+ expect(classifyBootLog(snapshot({ exists: false }))).toBe('notfound');
+ });
+
+ 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)',
+ );
+ expect(describeMissingBootLog(snapshot({ exists: true, lineCount: 0 }))).toBe(
+ 'log files present but empty',
+ );
+ expect(describeMissingBootLog(snapshot({ exists: true, lineCount: 4 }))).toBe(
+ 'log files present and readable',
+ );
+ });
+
+ it('names which half of an unreadable log failed, so a dir fault is not read as a file fault', () => {
+ expect(describeMissingBootLog(snapshot({ exists: false, unreadableReason: 'EACCES' }))).toBe(
+ 'log dir unreadable (EACCES)',
+ );
+ expect(
+ describeMissingBootLog(
+ snapshot({
+ exists: true,
+ lineCount: 3,
+ unreadableFiles: ['desktop.2026-09-04.log (EBUSY)'],
+ }),
+ ),
+ ).toBe('log files unreadable: desktop.2026-09-04.log (EBUSY)');
+ });
+
+ it('separates a log that was opened and never written from one that is absent', () => {
+ expect(classifyBootLog(snapshot({ exists: true, lineCount: 0 }))).toBe('empty');
+ expect(classifyBootLog(snapshot({ exists: true, lineCount: 4 }))).toBe('ok');
+ });
+
+ it('maps every log state to its reason, so the token cannot blame the app for a runner fault', () => {
+ const locked = snapshot({
+ exists: true,
+ lineCount: 3,
+ unreadableFiles: ['desktop.2026-09-04.log (EBUSY)'],
+ });
+ expect(giveUpReason('stall', locked)).toBe('unreadable');
+ expect(giveUpReason('cap', locked)).toBe('unreadable');
+ expect(giveUpReason('cap', snapshot({ exists: false, unreadableReason: 'EACCES' }))).toBe(
+ 'unreadable',
+ );
+ expect(giveUpReason('cap', snapshot({ exists: false }))).toBe('notfound');
+ expect(giveUpReason('cap', snapshot({ exists: true, lineCount: 0 }))).toBe('empty');
+ expect(giveUpReason('cap', snapshot({ exists: true, lineCount: 4 }))).toBe('cap');
+ expect(giveUpReason('stall', snapshot({ exists: true, lineCount: 4 }))).toBe('stall');
+ });
+
+ it('names the fault and declines to blame the app in one message, on the unreadable path', async () => {
+ let clock = 0;
+ const locked = snapshot({
+ exists: true,
+ lineCount: 3,
+ unreadableFiles: ['desktop.2026-09-04.log (EBUSY)'],
+ });
+ expect(classifyBootLog(locked)).toBe('unreadable');
+ const error = await waitForReadySignal<string>({
+ probe: async () => undefined,
+ home: '/unused',
+ what: 'editor window',
+ capMs: 500,
+ now: () => clock,
+ sleep: async () => {
+ clock += 100;
+ },
+ readLog: () => locked,
+ }).catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(Error);
+ expect((error as Error).message).toMatch(/UNREADABLE files: [\s\S]*not evidence about the app/);
+ expect((error as Error).message).toContain('and the boot log cannot say why');
+ });
+
+ it('records stall as the reason on the path that already drives it', async () => {
+ const home = seedHome([JSON.stringify({ event: DESKTOP_BOOT_EVENT })]);
+ const app = { windows: () => [{ evaluate: async () => 'navigator' }] };
+ rememberLaunchHome(app, home);
+ await expect(
+ waitForWindowByMode(app, 'editor', { home, stallMs: 150, pollMs: 20, capMs: 5_000 }),
+ ).rejects.toThrow(/logged no new boot activity/);
+ expect(tryFirstWaitFor(app)?.reason).toBe('stall');
+ });
+});
+
+describe('boot-log unreadability is not blamed on the app', () => {
+ it('separates a permissions/fd failure from "the app never logged"', async () => {
+ let clock = 0;
+ await expect(
+ waitForReadySignal<string>({
+ probe: async () => undefined,
+ home: '/unused',
+ what: 'editor window',
+ now: () => clock,
+ sleep: async () => {
+ clock += 1_000;
+ },
+ readLog: () => snapshot({ exists: false, unreadableReason: 'EACCES' }),
+ }),
+ ).rejects.toThrow(/UNREADABLE, EACCES .*runner\s+filesystem problem/s);
+ });
+
+ it('still says NOT FOUND when the directory is simply absent', () => {
+ const s = readBootLog(seedHome());
+ expect(s.exists).toBe(false);
+ expect(s.unreadableReason).toBeUndefined();
+ });
+});
+
+describe('bootGapSourceFor', () => {
+ it('labels every combination the teardown loop can produce', () => {
+ expect(bootGapSourceFor({ hasLines: false, snapshotted: false, homeShared: false })).toBe(
+ 'unavailable',
+ );
+ expect(bootGapSourceFor({ hasLines: false, snapshotted: false, homeShared: true })).toBe(
+ 'unavailable',
+ );
+ expect(bootGapSourceFor({ hasLines: true, snapshotted: true, homeShared: false })).toBe(
+ 'boot-complete',
+ );
+ expect(bootGapSourceFor({ hasLines: true, snapshotted: true, homeShared: true })).toBe(
+ 'boot-complete',
+ );
+ expect(bootGapSourceFor({ hasLines: true, snapshotted: false, homeShared: false })).toBe(
+ 'teardown-read',
+ );
+ expect(bootGapSourceFor({ hasLines: true, snapshotted: false, homeShared: true })).toBe(
+ 'teardown-read-shared-home',
+ );
+ });
+});
+
+describe('formatBootGapLine', () => {
+ it('states the measured gap next to the bound it has to clear', () => {
+ const line = formatBootGapLine({
+ slot: 0,
+ source: 'boot-complete',
+ readyWaitCount: 2,
+ firstWait: {
+ ordinal: 0,
+ what: 'editor window',
+ elapsedMs: 2_100,
+ capMs: 9_000,
+ gaveUp: false,
+ reason: 'none',
+ },
+ summary: bootLogGapSummary([
+ markLine('appReady', 0, '2026-09-04T00:00:00.000Z'),
+ markLine('serverSpawned', 1_400, '2026-09-04T00:00:01.400Z'),
+ markLine('windowShown', 3_000, '2026-09-04T00:00:03.000Z'),
+ ]),
+ });
+ expect(line).toContain('[boot-gap] slot=0');
+ expect(line).toContain('source=boot-complete');
+ expect(line).toContain(`stallMs=${BOOT_LOG_STALL_MS}`);
+ expect(line).toContain('totalBootMs=3000');
+ expect(line).toContain('maxGapMs=1600');
+ expect(line).toContain('firstWaitMs=2100');
+ expect(line).toContain('firstWaitCapMs=9000');
+ expect(line).not.toContain(`firstWaitCapMs=${BOOT_LOG_CAP_MS}`);
+ expect(line).toContain('firstWaitWhat="editor window"');
+ expect(line).toContain('firstWaitGaveUp=false');
+ expect(line).toContain('firstWaitReason=none');
+ expect(line).toContain('readyWaitCount=2');
+ expect(line).toContain('bootComplete=true');
+ });
+
+ it('says why there is no measurement rather than printing a zero', () => {
+ const line = formatBootGapLine({
+ slot: 1,
+ source: 'unavailable',
+ summary: undefined,
+ reason: 'log dir gone at teardown',
+ });
+ expect(line).toContain('slot=1');
+ expect(line).toContain('source=unavailable');
+ expect(line).toContain('reason="log dir gone at teardown"');
+ expect(line).toContain('firstWaitMs=none');
+ expect(line).toContain('firstWaitCapMs=none');
+ expect(line).toContain('firstWaitWhat=none');
+ expect(line).toContain('firstWaitGaveUp=none');
+ expect(line).toContain('firstWaitReason=none');
+ expect(line).toContain('readyWaitCount=0');
+ expect(line).not.toContain('maxGapMs');
+ });
+
+ it('emits every give-up reason from the closed set, so a new one cannot appear unannounced', () => {
+ expect([...READY_WAIT_GIVE_UP_REASONS]).toEqual([
+ 'stall',
+ 'cap',
+ 'unreadable',
+ 'notfound',
+ 'empty',
+ 'none',
+ ]);
+ for (const reason of READY_WAIT_GIVE_UP_REASONS) {
+ const line = formatBootGapLine({
+ slot: 0,
+ source: 'boot-complete',
+ readyWaitCount: 1,
+ firstWait: {
+ ordinal: 0,
+ what: 'editor window',
+ elapsedMs: 25_000,
+ capMs: BOOT_LOG_CAP_MS,
+ gaveUp: reason !== 'none',
+ reason,
+ },
+ summary: undefined,
+ reason: 'no summary',
+ });
+ expect(line).toContain(`firstWaitReason=${reason}`);
+ expect(line).toContain(reason === 'none' ? 'firstWaitGaveUp=false' : 'firstWaitGaveUp=true');
+ }
+ });
+});
diff --git a/packages/desktop/tests/smoke/_helpers/launch-readiness.ts b/packages/desktop/tests/smoke/_helpers/launch-readiness.ts
new file mode 100644
index 000000000..51fe03ac2
--- /dev/null
+++ b/packages/desktop/tests/smoke/_helpers/launch-readiness.ts
@@ -0,0 +1,626 @@
+import { readdirSync, readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import {
+ DESKTOP_BOOT_EVENT,
+ isBootHeartbeatEvent,
+ SPAWN_WAIT_HEARTBEAT_MS,
+ startupMarkLine,
+} from '../../../src/shared/boot-narration.ts';
+
+export const BOOT_LOG_HEARTBEAT_MS = SPAWN_WAIT_HEARTBEAT_MS;
+
+export const BOOT_LOG_STALL_MS = BOOT_LOG_HEARTBEAT_MS * 3;
+
+export const BOOT_LOG_POLL_MS = 250;
+
+export const BOOT_LOG_CAP_MS = 25_000;
+
+const BOOT_LOG_TAIL_LINES = 12;
+
+export interface BootLogSnapshot {
+ dir: string;
+ exists: boolean;
+ fileCount: number;
+ unreadableReason: string | undefined;
+ unreadableFiles: string[];
+ lines: string[];
+ lineCount: number;
+ lastEvent: string | undefined;
+ tail: string;
+}
+
+export function bootLogDirFor(home: string): string {
+ return join(home, '.ok', 'logs');
+}
+
+function emptyBootLog(dir: string, unreadableReason?: string): BootLogSnapshot {
+ return {
+ dir,
+ exists: false,
+ fileCount: 0,
+ unreadableReason,
+ unreadableFiles: [],
+ lines: [],
+ lineCount: 0,
+ lastEvent: undefined,
+ tail: '',
+ };
+}
+
+function parseEvent(line: string): string | undefined {
+ try {
+ const parsed = JSON.parse(line) as { event?: unknown; msg?: unknown };
+ if (typeof parsed.event === 'string') return parsed.event;
+ if (typeof parsed.msg === 'string') return parsed.msg;
+ } catch {}
+ return undefined;
+}
+
+export function readBootLog(home: string): BootLogSnapshot {
+ const dir = bootLogDirFor(home);
+ let names: string[];
+ try {
+ names = readdirSync(dir).filter((n) => n.startsWith('desktop.') && n.endsWith('.log'));
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ return emptyBootLog(dir, code === undefined || code === 'ENOENT' ? undefined : code);
+ }
+ const lines: string[] = [];
+ const unreadableFiles: string[] = [];
+ for (const name of names.sort()) {
+ try {
+ const raw = readFileSync(join(dir, name), 'utf8');
+ for (const line of raw.split('\n')) {
+ if (line.trim().length > 0) lines.push(line);
+ }
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code ?? 'unknown';
+ unreadableFiles.push(`${name} (${code})`);
+ }
+ }
+ let lastEvent: string | undefined;
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
+ const line = lines[i];
+ if (line === undefined) continue;
+ const event = parseEvent(line);
+ if (event !== undefined) {
+ lastEvent = event;
+ break;
+ }
+ }
+ return {
+ dir,
+ exists: names.length > 0,
+ fileCount: names.length,
+ unreadableReason: undefined,
+ unreadableFiles,
+ lines,
+ lineCount: lines.length,
+ lastEvent,
+ tail: lines.slice(-BOOT_LOG_TAIL_LINES).join('\n'),
+ };
+}
+
+export function readBootLogLines(home: string): string[] {
+ return readBootLog(home).lines;
+}
+
+export interface BootLogGapSummary {
+ totalBootMs: number;
+ lineCount: number;
+ maxGapMs: number;
+ maxGapAfterPhase: string | undefined;
+ openStageMs: number;
+ beatsSeen: number;
+ lastBeatPhase?: string;
+ bootComplete: boolean;
+ phases: string[];
+}
+
+function parseTime(line: string): number | undefined {
+ try {
+ const parsed = JSON.parse(line) as { time?: unknown };
+ if (typeof parsed.time === 'string') {
+ const ms = Date.parse(parsed.time);
+ return Number.isNaN(ms) ? undefined : ms;
+ }
+ if (typeof parsed.time === 'number') return parsed.time;
+ } catch {}
+ return undefined;
+}
+
+const BOOT_COMPLETE_EVENT = startupMarkLine('windowShown', 0).event;
+
+function currentLaunch(lines: readonly string[]): string[] {
+ const lastBoot = lines.map(parseEvent).lastIndexOf(DESKTOP_BOOT_EVENT);
+ return lastBoot === -1 ? [...lines] : lines.slice(lastBoot);
+}
+
+function bootPrefix(lines: readonly string[]): string[] {
+ const launch = currentLaunch(lines);
+ const end = launch.findIndex((line) => parseEvent(line) === BOOT_COMPLETE_EVENT);
+ return end === -1 ? launch : launch.slice(0, end + 1);
+}
+
+export function hasBootCompleted(all: readonly string[]): boolean {
+ return currentLaunch(all).some((line) => parseEvent(line) === BOOT_COMPLETE_EVENT);
+}
+
+function parseLastPhase(line: string): string | undefined {
+ try {
+ const parsed = JSON.parse(line) as { lastPhase?: unknown };
+ if (typeof parsed.lastPhase === 'string') return parsed.lastPhase;
+ } catch {}
+ return undefined;
+}
+
+export function bootLogGapSummary(all: readonly string[]): BootLogGapSummary {
+ const lines = bootPrefix(all);
+ const stamped = lines
+ .map((line) => ({
+ at: parseTime(line),
+ event: parseEvent(line),
+ beat: isBootHeartbeatEvent(parseEvent(line) ?? ''),
+ lastPhase: parseLastPhase(line),
+ }))
+ .filter((entry) => entry.at !== undefined);
+ const phases = stamped.filter((entry) => !entry.beat);
+ let maxGapMs = 0;
+ let maxGapAfterPhase: string | undefined;
+ for (let i = 1; i < phases.length; i += 1) {
+ const prev = phases[i - 1];
+ const cur = phases[i];
+ if (prev === undefined || cur === undefined) continue;
+ const gap = (cur.at as number) - (prev.at as number);
+ if (gap > maxGapMs) {
+ maxGapMs = gap;
+ maxGapAfterPhase = prev.event;
+ }
+ }
+ const lastStageAt = phases.at(-1)?.at;
+ const lastLineAt = stamped.at(-1)?.at;
+ const openStageMs =
+ lastStageAt !== undefined && lastLineAt !== undefined ? lastLineAt - lastStageAt : 0;
+ if (openStageMs > maxGapMs) {
+ maxGapMs = openStageMs;
+ maxGapAfterPhase = phases.at(-1)?.event;
+ }
+ const firstAt = stamped[0]?.at;
+ const lastAt = stamped.at(-1)?.at;
+ const totalBootMs = firstAt !== undefined && lastAt !== undefined ? lastAt - firstAt : 0;
+ const beatsSeen = stamped.length - phases.length;
+ const lastBeatPhase = stamped
+ .filter((e) => e.beat && e.lastPhase !== undefined)
+ .at(-1)?.lastPhase;
+ return {
+ totalBootMs,
+ lineCount: lines.length,
+ maxGapMs,
+ maxGapAfterPhase,
+ openStageMs,
+ beatsSeen,
+ ...(lastBeatPhase === undefined ? {} : { lastBeatPhase }),
+ bootComplete: hasBootCompleted(lines),
+ phases: phases.map((s) => s.event).filter((e): e is string => e !== undefined),
+ };
+}
+
+type BootGapSource =
+ | 'unavailable'
+ | 'boot-complete'
+ | 'teardown-read'
+ | 'teardown-read-shared-home';
+
+export function describeMissingBootLog(snapshot: BootLogSnapshot): string {
+ switch (classifyBootLog(snapshot)) {
+ case 'unreadable':
+ return snapshot.unreadableReason !== undefined
+ ? `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)';
+ case 'empty':
+ return 'log files present but empty';
+ case 'ok':
+ return 'log files present and readable';
+ }
+}
+
+export interface BootGapLine {
+ slot: number;
+ source: BootGapSource;
+ firstWait?: ReadyWaitRecord;
+ readyWaitCount?: number;
+ summary: BootLogGapSummary | undefined;
+ reason?: string;
+}
+
+export function bootGapSourceFor(input: {
+ hasLines: boolean;
+ snapshotted: boolean;
+ homeShared: boolean;
+}): BootGapSource {
+ if (!input.hasLines) return 'unavailable';
+ if (input.snapshotted) return 'boot-complete';
+ return input.homeShared ? 'teardown-read-shared-home' : 'teardown-read';
+}
+
+export function formatBootGapLine(line: BootGapLine): string {
+ const parts = [
+ `[boot-gap] slot=${line.slot}`,
+ `source=${line.source}`,
+ `stallMs=${BOOT_LOG_STALL_MS}`,
+ `readyWaitCount=${line.readyWaitCount ?? 0}`,
+ ...(line.firstWait === undefined
+ ? [
+ 'firstWaitMs=none',
+ 'firstWaitCapMs=none',
+ 'firstWaitWhat=none',
+ 'firstWaitGaveUp=none',
+ 'firstWaitReason=none',
+ ]
+ : [
+ `firstWaitMs=${line.firstWait.elapsedMs}`,
+ `firstWaitCapMs=${line.firstWait.capMs}`,
+ `firstWaitWhat=${JSON.stringify(line.firstWait.what)}`,
+ `firstWaitGaveUp=${line.firstWait.gaveUp}`,
+ `firstWaitReason=${line.firstWait.reason}`,
+ ]),
+ ];
+ if (line.summary === undefined) {
+ parts.push(`reason=${JSON.stringify(line.reason ?? 'unknown')}`);
+ return parts.join(' ');
+ }
+ parts.push(
+ `totalBootMs=${line.summary.totalBootMs}`,
+ `maxGapMs=${line.summary.maxGapMs}`,
+ `openStageMs=${line.summary.openStageMs}`,
+ `beatsSeen=${line.summary.beatsSeen}`,
+ `lineCount=${line.summary.lineCount}`,
+ `bootComplete=${line.summary.bootComplete}`,
+ `afterPhase=${JSON.stringify(line.summary.maxGapAfterPhase ?? '')}`,
+ `lastBeatPhase=${JSON.stringify(line.summary.lastBeatPhase ?? '')}`,
+ );
+ return parts.join(' ');
+}
+
+export type ReadyLiveness = 'boot' | 'none';
+
+export interface ReadySignalOptions<T> {
+ probe: () => Promise<T | undefined>;
+ home: string;
+ what: string;
+ liveness?: ReadyLiveness;
+ stallMs?: number;
+ capMs?: number;
+ pollMs?: number;
+ now?: () => number;
+ sleep?: (ms: number) => Promise<void>;
+ readLog?: (home: string) => BootLogSnapshot;
+}
+
+export interface ProbeErrorSummary {
+ last: string;
+ threwPolls: number;
+ totalPolls: number;
+}
+
+export type BootLogState = 'unreadable' | 'notfound' | 'empty' | 'ok';
+
+export function classifyBootLog(snapshot: BootLogSnapshot): BootLogState {
+ if (snapshot.unreadableReason !== undefined || snapshot.unreadableFiles.length > 0)
+ return 'unreadable';
+ if (!snapshot.exists) return 'notfound';
+ if (snapshot.lineCount === 0) return 'empty';
+ return 'ok';
+}
+
+function describeBootLog(snapshot: BootLogSnapshot): string {
+ switch (classifyBootLog(snapshot)) {
+ case 'unreadable':
+ return snapshot.unreadableReason !== undefined
+ ? `Boot log: ${snapshot.dir} (UNREADABLE, ${snapshot.unreadableReason} — this is a runner ` +
+ 'filesystem problem, not evidence about the app)'
+ : `Boot log: ${snapshot.dir} (${snapshot.lineCount} line(s) read; UNREADABLE files: ` +
+ `${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)'
+ );
+ case 'empty':
+ return (
+ `Boot log: ${snapshot.dir} (${snapshot.fileCount} file(s) present but EMPTY — the app ` +
+ 'opened its log and wrote nothing)'
+ );
+ case 'ok':
+ return `Boot log: ${snapshot.dir}`;
+ }
+}
+
+function describeFailure(
+ reason: 'stalled' | 'cap',
+ what: string,
+ elapsedMs: number,
+ stallMs: number,
+ snapshot: BootLogSnapshot,
+ probeError: ProbeErrorSummary | undefined,
+): string {
+ const phase = snapshot.lastEvent ?? '(no boot event recorded)';
+ const state = classifyBootLog(snapshot);
+ const head =
+ state !== 'ok'
+ ? `${what} did not arrive within ${elapsedMs}ms, and the boot log cannot say why.`
+ : reason === 'stalled'
+ ? `${what} did not arrive, and the app logged no new boot activity for ${stallMs}ms ` +
+ `(gave up after ${elapsedMs}ms). Main narrates every ${BOOT_LOG_HEARTBEAT_MS}ms from ` +
+ 'process start until the first window is shown, so this silence after phase ' +
+ `${phase} means the app stopped making progress.`
+ : `${what} did not arrive within ${elapsedMs}ms, though the app kept logging boot activity.`;
+ const lines = [head, `Last main-process boot event: ${phase}`, describeBootLog(snapshot)];
+ lines.push(
+ probeError === undefined
+ ? 'Probe errors: none on any poll.'
+ : `Probe threw on ${probeError.threwPolls} of ${probeError.totalPolls} polls; ` +
+ `last: ${probeError.last}`,
+ );
+ if (snapshot.tail.length > 0) lines.push('', 'Boot log tail:', snapshot.tail);
+ return lines.join('\n');
+}
+
+class ReadySignalGiveUp extends Error {
+ readonly reason: ReadyWaitGiveUpReason;
+ constructor(message: string, reason: ReadyWaitGiveUpReason) {
+ super(message);
+ this.reason = reason;
+ }
+}
+
+export function giveUpReason(
+ base: 'stall' | 'cap',
+ snapshot: BootLogSnapshot,
+): ReadyWaitGiveUpReason {
+ switch (classifyBootLog(snapshot)) {
+ case 'unreadable':
+ return 'unreadable';
+ case 'notfound':
+ return 'notfound';
+ case 'empty':
+ return 'empty';
+ case 'ok':
+ return base;
+ }
+}
+
+export async function waitForReadySignal<T>(options: ReadySignalOptions<T>): Promise<T> {
+ const stallMs = options.stallMs ?? BOOT_LOG_STALL_MS;
+ const capMs = options.capMs ?? BOOT_LOG_CAP_MS;
+ const pollMs = options.pollMs ?? BOOT_LOG_POLL_MS;
+ const now = options.now ?? (() => Date.now());
+ const sleep = options.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms)));
+ const readLog = options.readLog ?? readBootLog;
+
+ const startedAt = now();
+ let lastProgressAt = startedAt;
+ let cursor = -1;
+ let snapshot = emptyBootLog(bootLogDirFor(options.home));
+ const explicitLiveness = options.liveness;
+ let lastProbeError: string | undefined;
+ let threwPolls = 0;
+ let totalPolls = 0;
+
+ for (;;) {
+ totalPolls += 1;
+ try {
+ const hit = await options.probe();
+ if (hit !== undefined) return hit;
+ } catch (error) {
+ lastProbeError = error instanceof Error ? error.message : String(error);
+ threwPolls += 1;
+ }
+
+ snapshot = readLog(options.home);
+ if (snapshot.lineCount > cursor) {
+ cursor = snapshot.lineCount;
+ lastProgressAt = now();
+ }
+
+ const probeError: ProbeErrorSummary | undefined =
+ lastProbeError === undefined ? undefined : { last: lastProbeError, threwPolls, totalPolls };
+ const elapsed = now() - startedAt;
+ const stallArmed =
+ explicitLiveness !== undefined
+ ? explicitLiveness === 'boot'
+ : !hasBootCompleted(snapshot.lines);
+ if (stallArmed && now() - lastProgressAt >= stallMs) {
+ throw new ReadySignalGiveUp(
+ describeFailure('stalled', options.what, elapsed, stallMs, snapshot, probeError),
+ giveUpReason('stall', snapshot),
+ );
+ }
+ if (elapsed >= capMs) {
+ throw new ReadySignalGiveUp(
+ describeFailure('cap', options.what, elapsed, stallMs, snapshot, probeError),
+ giveUpReason('cap', snapshot),
+ );
+ }
+ await sleep(pollMs);
+ }
+}
+
+export type WindowMode = 'editor' | 'navigator' | 'terminal' | 'note';
+
+interface ModeProbePage {
+ evaluate(fn: () => string | undefined): Promise<string | undefined>;
+}
+
+interface ModeProbeApp<TPage> {
+ windows(): TPage[];
+}
+
+const HOME_BY_APP = new WeakMap<object, string>();
+
+const BOOT_LOG_BY_APP = new WeakMap<object, string[]>();
+
+export const READY_WAIT_GIVE_UP_REASONS = [
+ 'stall',
+ 'cap',
+ 'unreadable',
+ 'notfound',
+ 'empty',
+ 'none',
+] as const;
+
+export type ReadyWaitGiveUpReason = (typeof READY_WAIT_GIVE_UP_REASONS)[number];
+
+export interface ReadyWaitRecord {
+ ordinal: number;
+ what: string;
+ elapsedMs: number;
+ capMs: number;
+ gaveUp: boolean;
+ reason: ReadyWaitGiveUpReason;
+}
+
+const READY_WAITS_BY_APP = new WeakMap<object, ReadyWaitRecord[]>();
+
+export function rememberLaunchHome(app: object, home: string): void {
+ HOME_BY_APP.set(app, home);
+}
+
+export function tryLaunchHomeFor(app: object): string | undefined {
+ return HOME_BY_APP.get(app);
+}
+
+export function rememberBootLog(app: object, lines: readonly string[]): void {
+ if (lines.length === 0) return;
+ BOOT_LOG_BY_APP.set(app, [...lines]);
+}
+
+export function tryBootLogFor(app: object): string[] | undefined {
+ return BOOT_LOG_BY_APP.get(app);
+}
+
+export function rememberReadyWait(app: object, record: Omit<ReadyWaitRecord, 'ordinal'>): void {
+ const existing = READY_WAITS_BY_APP.get(app);
+ if (existing === undefined) {
+ READY_WAITS_BY_APP.set(app, [{ ordinal: 0, ...record }]);
+ return;
+ }
+ existing.push({ ordinal: existing.length, ...record });
+}
+
+export function readyWaitsFor(app: object): readonly ReadyWaitRecord[] | undefined {
+ return READY_WAITS_BY_APP.get(app);
+}
+
+export function tryFirstWaitFor(app: object): ReadyWaitRecord | undefined {
+ return READY_WAITS_BY_APP.get(app)?.[0];
+}
+
+export function launchHomeFor(app: object): string {
+ const home = HOME_BY_APP.get(app);
+ if (home === undefined) {
+ throw new Error(
+ 'This ElectronApplication was not launched through launchDesktopApp(), so the smoke ' +
+ 'harness cannot locate its boot log. Launch via launchDesktopApp({ home }) or pass ' +
+ '{ home } explicitly to the readiness helper.',
+ );
+ }
+ return home;
+}
+
+export interface WaitForWindowOptions {
+ home?: string;
+ liveness?: ReadyLiveness;
+ stallMs?: number;
+ capMs?: number;
+ pollMs?: number;
+}
+
+function evaluateWindowMode(page: ModeProbePage): Promise<string | undefined> {
+ return page.evaluate(
+ () => (window as { okDesktop?: { config?: { mode?: string } } }).okDesktop?.config?.mode,
+ );
+}
+
+export async function waitForWindowByMode<TPage extends ModeProbePage>(
+ app: ModeProbeApp<TPage>,
+ mode: WindowMode,
+ options: WaitForWindowOptions = {},
+): Promise<TPage> {
+ const home = options.home ?? launchHomeFor(app);
+ const what = `${mode} window`;
+ const capMs = options.capMs ?? BOOT_LOG_CAP_MS;
+ const startedAt = Date.now();
+ let succeeded = false;
+ let reason: ReadyWaitGiveUpReason = 'none';
+ try {
+ const found = await waitForReadySignal<TPage>({
+ home,
+ what,
+ ...(options.liveness !== undefined ? { liveness: options.liveness } : {}),
+ ...(options.stallMs !== undefined ? { stallMs: options.stallMs } : {}),
+ capMs,
+ ...(options.pollMs !== undefined ? { pollMs: options.pollMs } : {}),
+ probe: async () => {
+ let lastError: Error | undefined;
+ let readCleanly = false;
+ for (const page of app.windows()) {
+ try {
+ const found = await evaluateWindowMode(page);
+ readCleanly = true;
+ if (found === mode) return page;
+ } catch (error) {
+ lastError = error instanceof Error ? error : new Error(String(error));
+ }
+ }
+ if (!readCleanly && lastError !== undefined) throw lastError;
+ return undefined;
+ },
+ });
+ succeeded = true;
+ rememberBootLog(app, readBootLogLines(home));
+ return found;
+ } catch (error) {
+ if (error instanceof ReadySignalGiveUp) reason = error.reason;
+ throw error;
+ } finally {
+ rememberReadyWait(app, {
+ what,
+ elapsedMs: Date.now() - startedAt,
+ capMs,
+ gaveUp: !succeeded,
+ reason,
+ });
+ }
+}
+
+export interface DesktopLauncher<TApp> {
+ launch(options: object): Promise<TApp>;
+}
+
+export async function launchDesktopApp<TApp>(
+ launcher: DesktopLauncher<TApp>,
+ launchOptions: object,
+ options: { home: string; readLog?: (home: string) => BootLogSnapshot },
+): Promise<TApp> {
+ const readLog = options.readLog ?? readBootLog;
+ try {
+ const app = await launcher.launch(launchOptions);
+ if (typeof app === 'object' && app !== null) rememberLaunchHome(app, options.home);
+ return app;
+ } catch (error) {
+ const snapshot = readLog(options.home);
+ const reason = error instanceof Error ? error.message : String(error);
+ const detail = [
+ reason,
+ '',
+ `Last main-process boot event: ${snapshot.lastEvent ?? '(no boot event recorded)'}`,
+ describeBootLog(snapshot),
+ ];
+ if (snapshot.tail.length > 0) detail.push('', 'Boot log tail:', snapshot.tail);
+ throw new Error(detail.join('\n'), { cause: error });
+ }
+}
diff --git a/packages/desktop/tests/smoke/_helpers/parse-timeouts.test.ts b/packages/desktop/tests/smoke/_helpers/parse-timeouts.test.ts
index d61a827b8..5209c1743 100644
--- a/packages/desktop/tests/smoke/_helpers/parse-timeouts.test.ts
+++ b/packages/desktop/tests/smoke/_helpers/parse-timeouts.test.ts
@@ -2,8 +2,10 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import { BOOT_LOG_CAP_MS } from './launch-readiness';
import {
extractHelperBudgets,
+ extractReadinessBudgets,
extractTestEntries,
parseNumericLiteral,
parsePlaywrightConfigTimeout,
@@ -409,6 +411,28 @@ describe('parseTestFile (real file, sanity)', () => {
expect(fa.tests.length).toBeGreaterThanOrEqual(3);
const byName = new Map(fa.helpers.map((h) => [h.name, h.maxTimeoutMs]));
expect(byName.get('launchApp') ?? 0).toBeGreaterThan(0);
- expect(byName.get('findWindowByMode') ?? 0).toBeGreaterThan(0);
+ expect(byName.get('expandAdvancedSettings') ?? 0).toBeGreaterThan(0);
+ expect(byName.get('findWindowByMode') ?? 0).toBe(BOOT_LOG_CAP_MS);
+ });
+});
+
+describe('readiness-helper attribution', () => {
+ test('scores the default cap for a plain waitForWindowByMode call', () => {
+ expect(extractReadinessBudgets('return waitForWindowByMode(app, mode);')).toEqual([
+ BOOT_LOG_CAP_MS,
+ ]);
+ });
+
+ test('prefers an inline capMs over the default', () => {
+ expect(
+ extractReadinessBudgets("waitForWindowByMode(app, 'navigator', { capMs: 60_000 })"),
+ ).toEqual([60_000]);
+ });
+
+ test('scores a waitForWindowByMode called straight from a test body', () => {
+ const src = `test('x', async () => {\n await waitForWindowByMode(app, 'editor');\n});\n`;
+ const entry = extractTestEntries(src, [])[0];
+ expect(entry?.directTimeoutsMs).toEqual([BOOT_LOG_CAP_MS]);
+ expect(entry?.cumulativeMs).toBe(BOOT_LOG_CAP_MS);
});
});
diff --git a/packages/desktop/tests/smoke/_helpers/parse-timeouts.ts b/packages/desktop/tests/smoke/_helpers/parse-timeouts.ts
index 684404c44..4848742f1 100644
--- a/packages/desktop/tests/smoke/_helpers/parse-timeouts.ts
+++ b/packages/desktop/tests/smoke/_helpers/parse-timeouts.ts
@@ -1,8 +1,13 @@
import { readFileSync } from 'node:fs';
import { DEFAULT_LAUNCH_TIMEOUT_MS } from './launch-desktop';
+import { BOOT_LOG_CAP_MS } from './launch-readiness';
const TIMEOUT_LITERAL_RE = /\btimeout:\s*(\d+(?:_\d+)*)/g;
const LAUNCH_HELPER_CALL_RE = /\bdesktopLaunchOptions\(/;
+
+const READINESS_HELPER_CALL_RE = /\bwaitForWindowByMode\s*\(/g;
+
+const READINESS_CAPMS_RE = /\bcapMs:\s*(\d+(?:_\d+)*)/;
const TOPASS_TIMEOUT_RE = /\.toPass\(\s*\{[^}]*timeout:\s*(\d+(?:_\d+)*)/g;
const DEFAULT_TIMEOUT_ARG_RE = /\btimeoutMs\s*=\s*(\d+(?:_\d+)*)/g;
const FUNCTION_HEADER_RE = /(?:^|\n)(?:export\s+)?(?:async\s+)?function\s+(\w+)\s*\(/g;
@@ -156,6 +161,26 @@ export function stripCommentsAndStrings(src: string): string {
return out.join('');
}
+export function extractReadinessBudgets(src: string): number[] {
+ const budgets: number[] = [];
+ for (const m of src.matchAll(READINESS_HELPER_CALL_RE)) {
+ const openIdx = src.indexOf('(', m.index ?? 0);
+ if (openIdx === -1) continue;
+ let depth = 1;
+ let i = openIdx + 1;
+ while (i < src.length && depth > 0) {
+ const c = src[i];
+ if (c === '(') depth += 1;
+ else if (c === ')') depth -= 1;
+ i += 1;
+ }
+ const args = src.slice(openIdx + 1, Math.max(openIdx + 1, i - 1));
+ const cap = args.match(READINESS_CAPMS_RE);
+ budgets.push(cap ? parseNumericLiteral(cap[1]) : BOOT_LOG_CAP_MS);
+ }
+ return budgets;
+}
+
export function extractHelperBudgets(src: string): HelperBudget[] {
const helpers: HelperBudget[] = [];
for (const m of src.matchAll(FUNCTION_HEADER_RE)) {
@@ -178,10 +203,10 @@ export function extractHelperBudgets(src: string): HelperBudget[] {
if (bodyOpenIdx === -1) continue;
const bodyCloseIdx = findMatchingClose(src, bodyOpenIdx);
if (bodyCloseIdx === -1) continue;
- const body = src.slice(bodyOpenIdx + 1, bodyCloseIdx);
+ const body = stripCommentsAndStrings(src.slice(bodyOpenIdx + 1, bodyCloseIdx));
const budgets: number[] = [];
- for (const dm of argsBlock.matchAll(DEFAULT_TIMEOUT_ARG_RE)) {
+ for (const dm of stripCommentsAndStrings(argsBlock).matchAll(DEFAULT_TIMEOUT_ARG_RE)) {
budgets.push(parseNumericLiteral(dm[1]));
}
for (const tm of body.matchAll(TIMEOUT_LITERAL_RE)) {
@@ -190,6 +215,7 @@ export function extractHelperBudgets(src: string): HelperBudget[] {
if (LAUNCH_HELPER_CALL_RE.test(body)) {
budgets.push(DEFAULT_LAUNCH_TIMEOUT_MS);
}
+ budgets.push(...extractReadinessBudgets(body));
const maxTimeoutMs = budgets.length > 0 ? Math.max(...budgets) : 0;
if (maxTimeoutMs > 0) {
helpers.push({ name, maxTimeoutMs });
@@ -219,6 +245,7 @@ export function extractTestEntries(src: string, helpers: HelperBudget[]): TestEn
for (const tm of strippedForTimeouts.matchAll(TIMEOUT_LITERAL_RE)) {
directTimeoutsMs.push(parseNumericLiteral(tm[1]));
}
+ directTimeoutsMs.push(...extractReadinessBudgets(strippedForTimeouts));
const toPassBudgetsMs: number[] = [];
for (const tm of strippedForTimeouts.matchAll(TOPASS_TIMEOUT_RE)) {
toPassBudgetsMs.push(parseNumericLiteral(tm[1]));
diff --git a/packages/desktop/tests/smoke/_helpers/smoke-test.ts b/packages/desktop/tests/smoke/_helpers/smoke-test.ts
index 70cf53e7a..c46cb582d 100644
--- a/packages/desktop/tests/smoke/_helpers/smoke-test.ts
+++ b/packages/desktop/tests/smoke/_helpers/smoke-test.ts
@@ -8,9 +8,23 @@ import {
type ElectronStderrCapture,
shouldAttachStderr,
} from './electron-stderr';
+import {
+ type BootGapLine,
+ bootGapSourceFor,
+ bootLogGapSummary,
+ describeMissingBootLog,
+ formatBootGapLine,
+ readBootLog,
+ readyWaitsFor,
+ rememberLaunchHome,
+ tryBootLogFor,
+ tryFirstWaitFor,
+ tryLaunchHomeFor,
+} from './launch-readiness';
export interface SmokeRegistrationOpts {
cleanupDirs?: readonly string[];
+ home?: string;
}
export interface SmokeFixtures {
@@ -23,13 +37,55 @@ export const test = baseTest.extend<SmokeFixtures>({
const captures: ElectronStderrCapture[] = [];
const procs: ChildProcess[] = [];
const cleanupDirs: string[] = [];
+ const apps: ElectronApplication[] = [];
await use((app, opts) => {
captures.push(captureElectronStderr(app));
procs.push(captureAppProcess(app));
+ apps.push(app);
+ if (opts?.home !== undefined) rememberLaunchHome(app, opts.home);
if (opts?.cleanupDirs) {
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}`);
+ }
+ }
if (shouldAttachStderr(testInfo)) {
await attachCapturedStderr(testInfo, captures);
}
diff --git a/packages/desktop/tests/smoke/_helpers/stale-build-guard.test.ts b/packages/desktop/tests/smoke/_helpers/stale-build-guard.test.ts
new file mode 100644
index 000000000..08f3f50b3
--- /dev/null
+++ b/packages/desktop/tests/smoke/_helpers/stale-build-guard.test.ts
@@ -0,0 +1,197 @@
+import { describe, expect, it } from 'vitest';
+import {
+ type BuildArtifactCheck,
+ evaluateBuild,
+ formatMissingArtifacts,
+ formatStaleArtifacts,
+ runBuildGuard,
+} from './stale-build-guard.ts';
+
+const MAIN: BuildArtifactCheck = {
+ name: 'main',
+ out: '/pkg/out/main/index.js',
+ srcs: ['/pkg/src/main/index.ts'],
+};
+
+const CLI: BuildArtifactCheck = {
+ name: '@inkeep/open-knowledge CLI',
+ out: '/pkg/../cli/dist/index.mjs',
+ srcs: [],
+};
+
+describe('evaluateBuild — missing-artifact polarity', () => {
+ it('reports a missing required artifact instead of silently passing', () => {
+ const verdict = evaluateBuild({
+ checks: [MAIN],
+ exists: () => false,
+ mtimeMs: () => 0,
+ smokeEnabled: true,
+ packagedOverride: undefined,
+ });
+ expect(verdict.missing).toEqual([{ name: 'main', out: '/pkg/out/main/index.js' }]);
+ });
+
+ it('reports a missing CLI build — the artifact that used to surface as a readiness timeout', () => {
+ const verdict = evaluateBuild({
+ checks: [MAIN, CLI],
+ exists: (p) => p !== CLI.out,
+ mtimeMs: () => 0,
+ smokeEnabled: true,
+ packagedOverride: undefined,
+ });
+ expect(verdict.missing).toEqual([{ name: CLI.name, out: CLI.out }]);
+ });
+
+ it('stays quiet when smoke is not enabled, so a non-smoke run still lists tests', () => {
+ const verdict = evaluateBuild({
+ checks: [MAIN],
+ exists: () => false,
+ mtimeMs: () => 0,
+ smokeEnabled: false,
+ packagedOverride: undefined,
+ });
+ expect(verdict.missing).toEqual([]);
+ });
+
+ it('stays quiet for unpackaged artifacts when a packaged app is under test', () => {
+ const verdict = evaluateBuild({
+ checks: [MAIN],
+ exists: () => false,
+ mtimeMs: () => 0,
+ smokeEnabled: true,
+ packagedOverride: '/Applications/OpenKnowledge.app',
+ });
+ expect(verdict.missing).toEqual([]);
+ });
+});
+
+describe('evaluateBuild — staleness (preserved behaviour)', () => {
+ it('flags a source newer than its build output', () => {
+ const verdict = evaluateBuild({
+ checks: [MAIN],
+ exists: () => true,
+ mtimeMs: (p) => (p === MAIN.out ? 100 : 200),
+ smokeEnabled: true,
+ packagedOverride: undefined,
+ });
+ expect(verdict.stale).toHaveLength(1);
+ expect(verdict.stale[0]).toContain('is newer than');
+ });
+
+ it('passes a build newer than its sources', () => {
+ const verdict = evaluateBuild({
+ checks: [MAIN],
+ exists: () => true,
+ mtimeMs: (p) => (p === MAIN.out ? 300 : 200),
+ smokeEnabled: true,
+ packagedOverride: undefined,
+ });
+ expect(verdict.stale).toEqual([]);
+ });
+});
+
+describe('runBuildGuard', () => {
+ it('throws naming the missing artifact and the build command', () => {
+ expect(() =>
+ runBuildGuard({
+ checks: [CLI],
+ exists: () => false,
+ mtimeMs: () => 0,
+ smokeEnabled: true,
+ packagedOverride: undefined,
+ }),
+ ).toThrow(/@inkeep\/open-knowledge CLI/);
+ });
+
+ it('names the CLI build command only when the CLI artifact is the missing one', () => {
+ expect(formatMissingArtifacts([{ name: CLI.name, out: CLI.out }])).toContain(
+ 'pnpm --filter @inkeep/open-knowledge run build',
+ );
+ expect(formatMissingArtifacts([{ name: 'main', out: MAIN.out }])).not.toContain(
+ 'pnpm --filter @inkeep/open-knowledge run build',
+ );
+ });
+
+ it('prefers the missing-artifact error over the staleness error', () => {
+ expect(() =>
+ runBuildGuard({
+ checks: [MAIN, CLI],
+ exists: (p) => p !== CLI.out,
+ mtimeMs: (p) => (p === MAIN.out ? 100 : 200),
+ smokeEnabled: true,
+ packagedOverride: undefined,
+ }),
+ ).toThrow(/Required desktop build artifact missing/);
+ });
+
+ it('reports the staleness error when nothing is missing', () => {
+ expect(() =>
+ runBuildGuard({
+ checks: [MAIN],
+ exists: () => true,
+ mtimeMs: (p) => (p === MAIN.out ? 100 : 200),
+ smokeEnabled: true,
+ packagedOverride: undefined,
+ }),
+ ).toThrow(/Stale desktop build detected/);
+ });
+
+ it('names every stale source and the rebuild command', () => {
+ const message = formatStaleArtifacts([` main: ${MAIN.srcs[0]} is newer than ${MAIN.out}`]);
+ expect(message).toContain(MAIN.srcs[0] ?? '');
+ expect(message).toContain('pnpm run build:desktop');
+ });
+});
+
+describe('the packaged escape hatch answers both branches the same way', () => {
+ it('stays quiet on a stale unpackaged out/ when a packaged app is under test', () => {
+ expect(
+ evaluateBuild({
+ checks: [MAIN],
+ exists: () => true,
+ mtimeMs: (p) => (p === MAIN.out ? 100 : 200),
+ smokeEnabled: true,
+ packagedOverride: '/Applications/OpenKnowledge.app',
+ }),
+ ).toEqual({ missing: [], stale: [] });
+ });
+
+ it('an explicit undefined override means not-packaged, whatever the ambient env says', () => {
+ const previous = process.env.OK_DESKTOP_PACKAGED_APP;
+ process.env.OK_DESKTOP_PACKAGED_APP = '/Applications/OpenKnowledge.app';
+ try {
+ expect(
+ evaluateBuild({
+ checks: [MAIN],
+ exists: () => false,
+ mtimeMs: () => 0,
+ smokeEnabled: true,
+ packagedOverride: undefined,
+ }).missing,
+ ).toHaveLength(1);
+ } finally {
+ if (previous === undefined) delete process.env.OK_DESKTOP_PACKAGED_APP;
+ else process.env.OK_DESKTOP_PACKAGED_APP = previous;
+ }
+ });
+});
+
+describe('the real CHECKS list, not an injected one', () => {
+ it('names the module entry the unpackaged utility process actually loads', () => {
+ const verdict = evaluateBuild({
+ exists: () => false,
+ mtimeMs: () => 0,
+ smokeEnabled: true,
+ packagedOverride: undefined,
+ });
+ const cli = verdict.missing.find((m) => m.name.includes('CLI'));
+ expect(cli?.out).toMatch(/cli[/\\]dist[/\\]index\.mjs$/);
+ expect(verdict.missing.map((m) => m.name)).toEqual([
+ 'main',
+ 'preload',
+ 'renderer',
+ 'utility server entry',
+ '@inkeep/open-knowledge CLI',
+ ]);
+ });
+});
diff --git a/packages/desktop/tests/smoke/_helpers/stale-build-guard.ts b/packages/desktop/tests/smoke/_helpers/stale-build-guard.ts
index 651dd035d..05414d3e9 100644
--- a/packages/desktop/tests/smoke/_helpers/stale-build-guard.ts
+++ b/packages/desktop/tests/smoke/_helpers/stale-build-guard.ts
@@ -5,12 +5,16 @@ import { fileURLToPath } from 'node:url';
const __dirname = dirname(fileURLToPath(import.meta.url));
const DESKTOP_PKG = resolve(__dirname, '..', '..', '..');
-interface BuildArtifactCheck {
+export interface BuildArtifactCheck {
name: string;
out: string;
srcs: string[];
}
+export const BUILD_COMMAND = 'pnpm run build:desktop';
+
+export const CLI_BUILD_COMMAND = 'pnpm --filter @inkeep/open-knowledge run build';
+
const CHECKS: BuildArtifactCheck[] = [
{
name: 'main',
@@ -26,39 +30,101 @@ const CHECKS: BuildArtifactCheck[] = [
out: resolve(DESKTOP_PKG, 'out/preload/index.js'),
srcs: [resolve(DESKTOP_PKG, 'src/preload/index.ts')],
},
+ {
+ name: 'renderer',
+ out: resolve(DESKTOP_PKG, 'out/renderer/index.html'),
+ srcs: [],
+ },
+ {
+ name: 'utility server entry',
+ out: resolve(DESKTOP_PKG, 'out/main/utility/server-entry.js'),
+ srcs: [resolve(DESKTOP_PKG, 'src/utility/server-entry.ts')],
+ },
+ {
+ name: '@inkeep/open-knowledge CLI',
+ out: resolve(DESKTOP_PKG, '..', 'cli', 'dist', 'index.mjs'),
+ srcs: [],
+ },
];
-function mtimeMs(path: string): number {
- return statSync(path).mtimeMs;
+export interface GuardDeps {
+ checks?: readonly BuildArtifactCheck[];
+ exists?: (path: string) => boolean;
+ mtimeMs?: (path: string) => number;
+ smokeEnabled?: boolean;
+ packagedOverride?: string | undefined;
}
-export default function staleBuildGuard(): void {
+export interface GuardVerdict {
+ missing: { name: string; out: string }[];
+ stale: string[];
+}
+
+export function evaluateBuild(deps: GuardDeps = {}): GuardVerdict {
+ const checks = deps.checks ?? CHECKS;
+ const exists = deps.exists ?? existsSync;
+ const mtime = deps.mtimeMs ?? ((p: string) => statSync(p).mtimeMs);
+ const smokeEnabled = deps.smokeEnabled ?? process.env.OK_DESKTOP_E2E_SMOKE === '1';
+ const packagedOverride =
+ 'packagedOverride' in deps ? deps.packagedOverride : process.env.OK_DESKTOP_PACKAGED_APP;
+ const packaged = packagedOverride !== undefined && packagedOverride.length > 0;
+
+ const missing: { name: string; out: string }[] = [];
const stale: string[] = [];
- for (const check of CHECKS) {
- if (!existsSync(check.out)) {
- return;
+
+ if (packaged) return { missing, stale };
+
+ for (const check of checks) {
+ if (!exists(check.out)) {
+ if (smokeEnabled) missing.push({ name: check.name, out: check.out });
+ continue;
}
- const outMtime = mtimeMs(check.out);
+ const outMtime = mtime(check.out);
for (const src of check.srcs) {
- if (!existsSync(src)) continue;
- if (mtimeMs(src) > outMtime) {
- stale.push(` ${check.name}: ${src} is newer than ${check.out}`);
- }
+ if (!exists(src)) continue;
+ if (mtime(src) > outMtime) stale.push(` ${check.name}: ${src} is newer than ${check.out}`);
}
}
- if (stale.length > 0) {
- throw new Error(
- [
- 'Stale desktop build detected — source files modified after last build.',
- '',
- ...stale,
- '',
- 'Run `pnpm run build:desktop` from public/open-knowledge before re-running smoke tests.',
- '',
- 'Why this matters: the smoke harness launches `out/main/index.js` directly.',
- 'If `out/` is older than `src/`, tests run against a phantom version of the app',
- 'and produce confusing failures unrelated to your actual changes.',
- ].join('\n'),
- );
- }
+
+ return { missing, stale };
+}
+
+export function formatMissingArtifacts(missing: readonly { name: string; out: string }[]): string {
+ const cli = missing.some((m) => m.name.includes('CLI'));
+ return [
+ 'Required desktop build artifact missing — the smoke harness cannot launch the app.',
+ '',
+ ...missing.map((m) => ` ${m.name}: ${m.out}`),
+ '',
+ `Run \`${BUILD_COMMAND}\` from public/open-knowledge before running smoke tests.`,
+ ...(cli ? [`The CLI artifact comes from \`${CLI_BUILD_COMMAND}\`.`] : []),
+ '',
+ 'Why this is a hard failure and not a skip: without these, the app never reaches',
+ 'a window and every smoke test reports an anonymous readiness timeout instead of',
+ 'naming the artifact that is actually missing.',
+ ].join('\n');
+}
+
+export function formatStaleArtifacts(stale: readonly string[]): string {
+ return [
+ 'Stale desktop build detected — source files modified after last build.',
+ '',
+ ...stale,
+ '',
+ `Run \`${BUILD_COMMAND}\` from public/open-knowledge before re-running smoke tests.`,
+ '',
+ 'Why this matters: the smoke harness launches `out/main/index.js` directly.',
+ 'If `out/` is older than `src/`, tests run against a phantom version of the app',
+ 'and produce confusing failures unrelated to your actual changes.',
+ ].join('\n');
+}
+
+export function runBuildGuard(deps: GuardDeps = {}): void {
+ const { missing, stale } = evaluateBuild(deps);
+ if (missing.length > 0) throw new Error(formatMissingArtifacts(missing));
+ if (stale.length > 0) throw new Error(formatStaleArtifacts(stale));
+}
+
+export default function staleBuildGuard(): void {
+ runBuildGuard();
}
diff --git a/packages/desktop/tests/smoke/_nav-empty-840x600.e2e.ts b/packages/desktop/tests/smoke/_nav-empty-840x600.e2e.ts
index d44afe89c..f585fe7c9 100644
--- a/packages/desktop/tests/smoke/_nav-empty-840x600.e2e.ts
+++ b/packages/desktop/tests/smoke/_nav-empty-840x600.e2e.ts
@@ -91,7 +91,7 @@ test.describe('Navigator empty-state screenshot (dev-only)', () => {
const tmpHome = seedEmptyHome('shot');
try {
const app = await launchApp(tmpHome);
- captureStderrFor(app);
+ captureStderrFor(app, { home: tmpHome });
const nav = await findNavigator(app);
const winHandle: JSHandle = await app.browserWindow(nav);
diff --git a/packages/desktop/tests/smoke/_nav-size-screenshots.e2e.ts b/packages/desktop/tests/smoke/_nav-size-screenshots.e2e.ts
index f74263efb..73e053b73 100644
--- a/packages/desktop/tests/smoke/_nav-size-screenshots.e2e.ts
+++ b/packages/desktop/tests/smoke/_nav-size-screenshots.e2e.ts
@@ -126,7 +126,7 @@ test.describe('Navigator size screenshots (dev-only)', () => {
const { tmpHome, projectDir } = seedHome('shots');
try {
const app = await launchApp(tmpHome);
- captureStderrFor(app);
+ captureStderrFor(app, { home: tmpHome });
const editor = await findWindow(app, 'editor');
await editor.evaluate(async () => {
diff --git a/packages/desktop/tests/smoke/background-throttle.e2e.ts b/packages/desktop/tests/smoke/background-throttle.e2e.ts
index 1469a8423..d5775412e 100644
--- a/packages/desktop/tests/smoke/background-throttle.e2e.ts
+++ b/packages/desktop/tests/smoke/background-throttle.e2e.ts
@@ -150,7 +150,7 @@ test.describe('background-throttle smoke', () => {
}) => {
const { tmpHome, projectDir } = seedHomeWithLastOpenedProject('happy');
const app = await launchApp(tmpHome);
- captureStderrFor(app, { cleanupDirs: [tmpHome, projectDir] });
+ captureStderrFor(app, { home: tmpHome, cleanupDirs: [tmpHome, projectDir] });
const editor = await findWindow(app, 'editor');
diff --git a/packages/desktop/tests/smoke/consent-dialog.e2e.ts b/packages/desktop/tests/smoke/consent-dialog.e2e.ts
index a0eb5f173..cc91c6f9d 100644
--- a/packages/desktop/tests/smoke/consent-dialog.e2e.ts
+++ b/packages/desktop/tests/smoke/consent-dialog.e2e.ts
@@ -14,6 +14,7 @@ import type { ElectronApplication, Page } from '@playwright/test';
import { _electron as electron } from '@playwright/test';
import { reapDetachedServers } from './_helpers/electron-cleanup';
import { desktopLaunchOptions, resolveDesktopTarget } from './_helpers/launch-desktop';
+import { launchDesktopApp, waitForWindowByMode } from './_helpers/launch-readiness';
import { seedMcpConsentComplete } from './_helpers/mcp-consent';
import { clickNavOpen } from './_helpers/navigator-actions';
import {
@@ -69,7 +70,8 @@ interface LaunchOpts {
async function launchApp(tmpHome: string, opts: LaunchOpts = {}): Promise<ElectronApplication> {
const userDataDir = join(tmpHome, 'Library', 'Application Support', DESKTOP_PRODUCT_NAME);
seedMcpConsentComplete(tmpHome);
- return electron.launch(
+ return launchDesktopApp(
+ electron,
desktopLaunchOptions({
target: TARGET,
args: [`--user-data-dir=${userDataDir}`],
@@ -80,33 +82,19 @@ async function launchApp(tmpHome: string, opts: LaunchOpts = {}): Promise<Electr
...(opts.pickedPath !== undefined ? { OK_DESKTOP_TEST_PICKED_PATH: opts.pickedPath } : {}),
},
}),
+ { home: tmpHome },
);
}
async function findWindowByMode(
app: ElectronApplication,
mode: 'navigator' | 'editor',
- timeoutMs = 20_000,
): Promise<Page> {
- await expect
- .poll(
- async () => {
- for (const page of app.windows()) {
- const m = await page
- .evaluate(() => window.okDesktop?.config?.mode)
- .catch(() => undefined);
- if (m === mode) return true;
- }
- return false;
- },
- { timeout: timeoutMs, message: `${mode} window did not appear within timeout` },
- )
- .toBe(true);
- for (const page of app.windows()) {
- const m = await page.evaluate(() => window.okDesktop?.config?.mode).catch(() => undefined);
- if (m === mode) return page;
- }
- throw new Error(`${mode} window vanished between poll resolution and read`);
+ return waitForWindowByMode(app, mode);
+}
+
+async function findEditorAfterAction(app: ElectronApplication): Promise<Page> {
+ return waitForWindowByMode(app, 'editor', { capMs: 10_000 });
}
async function expandAdvancedSettings(page: Page): Promise<void> {
@@ -147,7 +135,7 @@ test.describe('Consent-dialog smoke', () => {
trackForCleanup(tmpHome, projectDir);
const app = await launchApp(tmpHome, { pickedPath: projectDir });
- captureStderrFor(app);
+ captureStderrFor(app, { home: tmpHome });
const navigator = await findWindowByMode(app, 'navigator');
await clickNavOpen(navigator);
@@ -161,7 +149,7 @@ test.describe('Consent-dialog smoke', () => {
await contentDir.focus();
await contentDir.press('Enter');
- await findWindowByMode(app, 'editor', 30_000);
+ await findEditorAfterAction(app);
await expect
.poll(() => existsSync(join(projectDir, '.ok', 'config.yml')), { timeout: 15_000 })
.toBe(true);
@@ -175,7 +163,7 @@ test.describe('Consent-dialog smoke', () => {
trackForCleanup(tmpHome, projectDir);
const app = await launchApp(tmpHome, { pickedPath: projectDir });
- captureStderrFor(app);
+ captureStderrFor(app, { home: tmpHome });
const navigator = await findWindowByMode(app, 'navigator');
await clickNavOpen(navigator);
@@ -202,7 +190,7 @@ test.describe('Consent-dialog smoke', () => {
trackForCleanup(tmpHome);
const app = await launchApp(tmpHome, { pickedPath: subFolder });
- captureStderrFor(app);
+ captureStderrFor(app, { home: tmpHome });
const navigator = await findWindowByMode(app, 'navigator');
await clickNavOpen(navigator);
@@ -215,7 +203,7 @@ test.describe('Consent-dialog smoke', () => {
const startBtn = navigator.locator('[data-testid="consent-start"]');
await startBtn.click();
- await findWindowByMode(app, 'editor', 30_000);
+ await findEditorAfterAction(app);
await expect
.poll(() => existsSync(join(repoRoot, '.ok', 'config.yml')), { timeout: 15_000 })
.toBe(true);
diff --git a/packages/desktop/tests/smoke/create-new-project.e2e.ts b/packages/desktop/tests/smoke/create-new-project.e2e.ts
index a4f42a0ed..13792ef72 100644
--- a/packages/desktop/tests/smoke/create-new-project.e2e.ts
+++ b/packages/desktop/tests/smoke/create-new-project.e2e.ts
@@ -139,7 +139,7 @@ test.describe('Create-new-project smoke', () => {
trackForCleanup(tmpHome);
const app = await launchApp(tmpHome, { pickedParent: parent });
- captureStderrFor(app);
+ captureStderrFor(app, { home: tmpHome });
const navigator = await findWindowByMode(app, 'navigator');
await clickNavCreateNew(navigator);
@@ -202,7 +202,7 @@ test.describe('Create-new-project smoke', () => {
trackForCleanup(tmpHome);
const app = await launchApp(tmpHome, { pickedParent: subFolder });
- captureStderrFor(app);
+ captureStderrFor(app, { home: tmpHome });
const navigator = await findWindowByMode(app, 'navigator');
await clickNavCreateNew(navigator);
@@ -239,7 +239,7 @@ test.describe('Create-new-project smoke', () => {
trackForCleanup(tmpHome);
const app = await launchApp(tmpHome, { pickedParent });
- captureStderrFor(app);
+ captureStderrFor(app, { home: tmpHome });
const navigator = await findWindowByMode(app, 'navigator');
await clickNavCreateNew(navigator);
@@ -300,7 +300,7 @@ test.describe('Create-new-project smoke', () => {
trackForCleanup(tmpHome);
const app = await launchApp(tmpHome, { pickedParent: `${sub1}\x1f${sub2}` });
- captureStderrFor(app);
+ captureStderrFor(app, { home: tmpHome });
const navigator = await findWindowByMode(app, 'navigator');
await clickNavCreateNew(navigator);
@@ -388,7 +388,7 @@ test.describe('Create-new-project smoke', () => {
trackForCleanup(tmpHome);
const app = await launchApp(tmpHome, { pickedParent });
- captureStderrFor(app);
+ captureStderrFor(app, { home: tmpHome });
const navigator = await findWindowByMode(app, 'navigator');
await clickNavCreateNew(navigator);
diff --git a/packages/desktop/tests/smoke/deep-link.e2e.ts b/packages/desktop/tests/smoke/deep-link.e2e.ts
index 0ad2e8ff4..f9b765f6f 100644
--- a/packages/desktop/tests/smoke/deep-link.e2e.ts
+++ b/packages/desktop/tests/smoke/deep-link.e2e.ts
@@ -39,7 +39,7 @@ test.describe('deep-link warm-start smoke (M4 US-009 / AC7)', () => {
timeout: 30_000,
}),
);
- captureStderrFor(app, { cleanupDirs: [projectDir, tmpHome] });
+ captureStderrFor(app, { home: tmpHome, cleanupDirs: [projectDir, tmpHome] });
const firstWindow = await app.firstWindow({ timeout: 15_000 });
expect(firstWindow).toBeDefined();
@@ -79,7 +79,7 @@ test.describe('deep-link warm-start smoke (M4 US-009 / AC7)', () => {
timeout: 30_000,
}),
);
- captureStderrFor(app, { cleanupDirs: [projectDir, tmpHome] });
+ captureStderrFor(app, { home: tmpHome, cleanupDirs: [projectDir, tmpHome] });
const firstWindow = await app.firstWindow({ timeout: 15_000 });
expect(firstWindow).toBeDefined();
diff --git a/packages/desktop/tests/smoke/mcp-wiring.e2e.ts b/packages/desktop/tests/smoke/mcp-wiring.e2e.ts
index 403abb3ac..1801ff5ea 100644
--- a/packages/desktop/tests/smoke/mcp-wiring.e2e.ts
+++ b/packages/desktop/tests/smoke/mcp-wiring.e2e.ts
@@ -139,7 +139,7 @@ test.describe('M6b first-launch MCP-wiring smoke (US-010)', () => {
seedEditorDetectionDirs(tmpHome, ['.claude']);
try {
const app = await launchApp({ tmpHome });
- captureStderrFor(app);
+ captureStderrFor(app, { home: tmpHome });
const window = await waitForConsentDialog(app);
await window.getByTestId('mcp-consent-add').click();
@@ -183,7 +183,7 @@ test.describe('M6b first-launch MCP-wiring smoke (US-010)', () => {
seedEditorDetectionDirs(tmpHome, ['.claude']);
try {
const app = await launchApp({ tmpHome });
- captureStderrFor(app);
+ captureStderrFor(app, { home: tmpHome });
const window = await waitForConsentDialog(app);
await app.evaluate(
@@ -224,7 +224,7 @@ test.describe('M6b first-launch MCP-wiring smoke (US-010)', () => {
seedEditorDetectionDirs(tmpHome, ['.claude']);
try {
const app = await launchApp({ tmpHome });
- captureStderrFor(app);
+ captureStderrFor(app, { home: tmpHome });
const window = await waitForConsentDialog(app);
await window.keyboard.press('Escape');
@@ -264,7 +264,7 @@ test.describe('M6b first-launch MCP-wiring smoke (US-010)', () => {
try {
const app = await launchApp({ tmpHome });
- captureStderrFor(app);
+ captureStderrFor(app, { home: tmpHome });
const firstWindow = await app.firstWindow({ timeout: 15_000 });
expect(firstWindow).toBeDefined();
@@ -292,7 +292,7 @@ test.describe('M6b first-launch MCP-wiring smoke (US-010)', () => {
try {
const app = await launchApp({ tmpHome });
- captureStderrFor(app);
+ captureStderrFor(app, { home: tmpHome });
const window = await waitForConsentDialog(app);
await window.getByTestId('mcp-consent-add').click();
@@ -351,7 +351,7 @@ test.describe('M6b first-launch MCP-wiring smoke (US-010)', () => {
try {
const app = await launchApp({ tmpHome });
- captureStderrFor(app, { cleanupDirs: [projectDir] });
+ captureStderrFor(app, { home: tmpHome, cleanupDirs: [projectDir] });
const window = await waitForConsentDialog(app);
await window.getByTestId('mcp-consent-add').click();
diff --git a/packages/desktop/tests/smoke/navigator-close-on-open.e2e.ts b/packages/desktop/tests/smoke/navigator-close-on-open.e2e.ts
index f554dcc70..61ca11fe9 100644
--- a/packages/desktop/tests/smoke/navigator-close-on-open.e2e.ts
+++ b/packages/desktop/tests/smoke/navigator-close-on-open.e2e.ts
@@ -136,7 +136,7 @@ test.describe('Project Navigator close-on-project-open smoke', () => {
}) => {
const { tmpHome, projectDir } = seedHomeWithoutLastOpenedProject('happy');
const app = await launchApp(tmpHome);
- captureStderrFor(app, { cleanupDirs: [tmpHome, projectDir] });
+ captureStderrFor(app, { home: tmpHome, cleanupDirs: [tmpHome, projectDir] });
await expect
.poll(() => countWindowsByMode(app, 'navigator'), {
@@ -175,7 +175,7 @@ test.describe('Project Navigator close-on-project-open smoke', () => {
}) => {
const { tmpHome, projectAPath, projectBPath } = seedHomeWithLastOpenedProjectAndExtra('switch');
const app = await launchApp(tmpHome);
- captureStderrFor(app, { cleanupDirs: [tmpHome, projectAPath, projectBPath] });
+ captureStderrFor(app, { home: tmpHome, cleanupDirs: [tmpHome, projectAPath, projectBPath] });
await expect
.poll(() => countWindowsByMode(app, 'editor'), {
@@ -223,7 +223,7 @@ test.describe('Project Navigator close-on-project-open smoke', () => {
const { tmpHome, projectDir } = seedHomeWithoutLastOpenedProject('failure');
const bogusProjectPath = join(tmpHome, 'does-not-exist');
const app = await launchApp(tmpHome);
- captureStderrFor(app, { cleanupDirs: [tmpHome, projectDir] });
+ captureStderrFor(app, { home: tmpHome, cleanupDirs: [tmpHome, projectDir] });
await expect
.poll(() => countWindowsByMode(app, 'navigator'), {
diff --git a/packages/desktop/tests/smoke/navigator-return.e2e.ts b/packages/desktop/tests/smoke/navigator-return.e2e.ts
index dbdf15afb..2a4e1349c 100644
--- a/packages/desktop/tests/smoke/navigator-return.e2e.ts
+++ b/packages/desktop/tests/smoke/navigator-return.e2e.ts
@@ -140,7 +140,7 @@ test.describe('Project Navigator return-affordance smoke', () => {
}) => {
const { tmpHome, projectDir } = seedHomeWithLastOpenedProject('happy');
const app = await launchApp(tmpHome);
- captureStderrFor(app, { cleanupDirs: [tmpHome, projectDir] });
+ captureStderrFor(app, { home: tmpHome, cleanupDirs: [tmpHome, projectDir] });
const editor = await findEditorWindow(app);
await expect.poll(() => countNavigatorWindows(app)).toBe(0);
@@ -176,7 +176,7 @@ test.describe('Project Navigator return-affordance smoke', () => {
}) => {
const { tmpHome, projectDir } = seedHomeWithLastOpenedProject('close');
const app = await launchApp(tmpHome);
- captureStderrFor(app, { cleanupDirs: [tmpHome, projectDir] });
+ captureStderrFor(app, { home: tmpHome, cleanupDirs: [tmpHome, projectDir] });
const editor = await findEditorWindow(app);
await expect.poll(() => countEditorWindows(app)).toBe(1);
diff --git a/packages/desktop/tests/smoke/note-window.e2e.ts b/packages/desktop/tests/smoke/note-window.e2e.ts
index 8bd5e502e..20e47f853 100644
--- a/packages/desktop/tests/smoke/note-window.e2e.ts
+++ b/packages/desktop/tests/smoke/note-window.e2e.ts
@@ -174,7 +174,7 @@ test.describe('Popped-out note window — live Electron', () => {
const s = seed('open');
track(s.tmpHome, s.projectDir);
const app = await launchApp(s);
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const editor = await findWindowByMode(app, 'editor');
await openDocument(editor, 'start');
@@ -227,7 +227,7 @@ test.describe('Popped-out note window — live Electron', () => {
const s = seed('handoff');
track(s.tmpHome, s.projectDir);
const app = await launchApp(s);
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const editor = await findWindowByMode(app, 'editor');
await openDocument(editor, 'start');
@@ -288,7 +288,7 @@ test.describe('Popped-out note window — live Electron', () => {
const s = seed('sync');
track(s.tmpHome, s.projectDir);
const app = await launchApp(s);
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const editor = await findWindowByMode(app, 'editor');
await openDocument(editor, 'start');
@@ -311,7 +311,7 @@ test.describe('Popped-out note window — live Electron', () => {
const s = seed('dedup');
track(s.tmpHome, s.projectDir);
const app = await launchApp(s);
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const editor = await findWindowByMode(app, 'editor');
await openDocument(editor, 'start');
@@ -329,7 +329,7 @@ test.describe('Popped-out note window — live Electron', () => {
const s = seed('menu');
track(s.tmpHome, s.projectDir);
const app = await launchApp(s);
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const editor = await findWindowByMode(app, 'editor');
await openDocument(editor, 'start');
@@ -367,7 +367,7 @@ test.describe('Popped-out note window — live Electron', () => {
const s = seed('cascade');
track(s.tmpHome, s.projectDir);
const app = await launchApp(s);
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const editor = await findWindowByMode(app, 'editor');
await openDocument(editor, 'start');
@@ -392,7 +392,7 @@ test.describe('Popped-out note window — live Electron', () => {
track(s.tmpHome, s.projectDir);
const first = await launchApp(s);
- captureStderrFor(first, { cleanupDirs: [] });
+ captureStderrFor(first, { home: s.tmpHome, cleanupDirs: [] });
const editor = await findWindowByMode(first, 'editor');
await openDocument(editor, 'start');
await popOutFrom(first, editor);
@@ -400,7 +400,7 @@ test.describe('Popped-out note window — live Electron', () => {
await first.close();
const second = await launchApp(s, { deepLink: false });
- captureStderrFor(second, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(second, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const restored = await findWindowByMode(second, 'note', 30_000);
expect(await restored.evaluate(() => window.okDesktop?.config.projectPath)).toBe(s.projectDir);
diff --git a/packages/desktop/tests/smoke/okf-rule-toggle.e2e.ts b/packages/desktop/tests/smoke/okf-rule-toggle.e2e.ts
index 1acd1d74f..a4eb95c8d 100644
--- a/packages/desktop/tests/smoke/okf-rule-toggle.e2e.ts
+++ b/packages/desktop/tests/smoke/okf-rule-toggle.e2e.ts
@@ -41,7 +41,7 @@ test.describe('okf per-rule toggle round-trip', () => {
args: [MAIN_ENTRY, deepLink, `--user-data-dir=${userDataDir}`],
timeout: 30_000,
});
- captureStderrFor(app, { cleanupDirs: [projectDir, tmpHome] });
+ captureStderrFor(app, { home: tmpHome, cleanupDirs: [projectDir, tmpHome] });
await app.firstWindow({ timeout: 15_000 });
const settingsPage = await (async () => {
diff --git a/packages/desktop/tests/smoke/qa-create-new-extended.e2e.ts b/packages/desktop/tests/smoke/qa-create-new-extended.e2e.ts
index cbfa532fb..9fc9d57ba 100644
--- a/packages/desktop/tests/smoke/qa-create-new-extended.e2e.ts
+++ b/packages/desktop/tests/smoke/qa-create-new-extended.e2e.ts
@@ -153,7 +153,7 @@ test.describe('QA extended create-new-project', () => {
trackForCleanup(tmpHome);
const app = await launchApp(tmpHome, { pickedParent: parent });
- captureStderrFor(app);
+ captureStderrFor(app, { home: tmpHome });
const navigator = await findWindowByMode(app, 'navigator');
await clickNavCreateNew(navigator);
await expect(navigator.locator('[data-testid="create-project-dialog"]')).toBeVisible({
@@ -211,7 +211,7 @@ test.describe('QA extended create-new-project', () => {
trackForCleanup(tmpHome);
const app = await launchApp(tmpHome, { pickedParent: parent });
- captureStderrFor(app);
+ captureStderrFor(app, { home: tmpHome });
const navigator = await findWindowByMode(app, 'navigator');
await clickNavCreateNew(navigator);
const dialog = navigator.locator('[data-testid="create-project-dialog"]');
@@ -265,7 +265,7 @@ test.describe('QA extended create-new-project', () => {
trackForCleanup(tmpHome);
const app1 = await launchApp(tmpHome, { pickedParent: parent });
- captureStderrFor(app1);
+ captureStderrFor(app1, { home: tmpHome });
const app1Proc = captureAppProcess(app1);
const navigator = await findWindowByMode(app1, 'navigator');
await clickNavCreateNew(navigator);
@@ -315,7 +315,7 @@ test.describe('QA extended create-new-project', () => {
rmSync(join(userDataDir, 'bug-report-dirty-shutdown.json'), { force: true });
const app2 = await launchApp(tmpHome);
- captureStderrFor(app2);
+ captureStderrFor(app2, { home: tmpHome });
const navigator2 = await findWindowByMode(app2, 'navigator', 30_000);
await clickNavCreateNew(navigator2);
await expect(navigator2.locator('[data-testid="create-project-dialog"]')).toBeVisible({
@@ -350,7 +350,7 @@ test.describe('QA extended create-new-project', () => {
trackForCleanup(tmpHome);
const app = await launchApp(tmpHome, { pickedParent: parent });
- captureStderrFor(app);
+ captureStderrFor(app, { home: tmpHome });
const navigator = await findWindowByMode(app, 'navigator');
await clickNavCreateNew(navigator);
await expect(navigator.locator('[data-testid="create-project-dialog"]')).toBeVisible({
@@ -385,7 +385,7 @@ test.describe('QA extended create-new-project', () => {
trackForCleanup(tmpHome);
const app = await launchApp(tmpHome, { pickedParent: parent });
- captureStderrFor(app);
+ captureStderrFor(app, { home: tmpHome });
const navigator = await findWindowByMode(app, 'navigator');
await clickNavCreateNew(navigator);
await expect(navigator.locator('[data-testid="create-project-dialog"]')).toBeVisible({
@@ -427,7 +427,7 @@ test.describe('QA extended create-new-project', () => {
trackForCleanup(tmpHome);
const app = await launchApp(tmpHome, { pickedParent: subFolder });
- captureStderrFor(app);
+ captureStderrFor(app, { home: tmpHome });
const navigator = await findWindowByMode(app, 'navigator');
await clickNavCreateNew(navigator);
await expect(navigator.locator('[data-testid="create-project-dialog"]')).toBeVisible({
@@ -460,7 +460,7 @@ test.describe('QA extended create-new-project', () => {
trackForCleanup(tmpHome);
const app = await launchApp(tmpHome, { pickedParent });
- captureStderrFor(app);
+ captureStderrFor(app, { home: tmpHome });
const navigator = await findWindowByMode(app, 'navigator');
await clickNavCreateNew(navigator);
await expect(navigator.locator('[data-testid="create-project-dialog"]')).toBeVisible({
@@ -490,7 +490,7 @@ test.describe('QA extended create-new-project', () => {
trackForCleanup(tmpHome);
const app = await launchApp(tmpHome, { pickedParent: parent });
- captureStderrFor(app);
+ captureStderrFor(app, { home: tmpHome });
const navigator = await findWindowByMode(app, 'navigator');
await clickNavCreateNew(navigator);
await expect(navigator.locator('[data-testid="create-project-dialog"]')).toBeVisible({
@@ -529,7 +529,7 @@ test.describe('QA extended create-new-project', () => {
trackForCleanup(tmpHome);
const app = await launchApp(tmpHome, { pickedParent: subFolder });
- captureStderrFor(app);
+ captureStderrFor(app, { home: tmpHome });
const navigator = await findWindowByMode(app, 'navigator');
await clickNavCreateNew(navigator);
await expect(navigator.locator('[data-testid="create-project-dialog"]')).toBeVisible({
@@ -571,7 +571,7 @@ test.describe('QA extended create-new-project', () => {
trackForCleanup(tmpHome);
const app = await launchApp(tmpHome, { pickedParent: parent });
- captureStderrFor(app);
+ captureStderrFor(app, { home: tmpHome });
const navigator = await findWindowByMode(app, 'navigator');
await clickNavCreateNew(navigator);
await expect(navigator.locator('[data-testid="create-project-dialog"]')).toBeVisible({
diff --git a/packages/desktop/tests/smoke/report-bug.e2e.ts b/packages/desktop/tests/smoke/report-bug.e2e.ts
index c35e50957..d5342a549 100644
--- a/packages/desktop/tests/smoke/report-bug.e2e.ts
+++ b/packages/desktop/tests/smoke/report-bug.e2e.ts
@@ -58,7 +58,7 @@ async function bootEditorWindow(
},
}),
);
- captureStderrFor(app, { cleanupDirs: [tmpHome, projectDir] });
+ captureStderrFor(app, { home: tmpHome, cleanupDirs: [tmpHome, projectDir] });
let editorPage: Page | undefined;
await expect(async () => {
diff --git a/packages/desktop/tests/smoke/saved-theme-paint.e2e.ts b/packages/desktop/tests/smoke/saved-theme-paint.e2e.ts
index 010957c2b..e992fe973 100644
--- a/packages/desktop/tests/smoke/saved-theme-paint.e2e.ts
+++ b/packages/desktop/tests/smoke/saved-theme-paint.e2e.ts
@@ -166,7 +166,7 @@ test.describe('saved theme paint smoke', () => {
}) => {
const { tmpHome, projectDir } = seedThemeHome();
const app = await launchApp(tmpHome);
- captureStderrFor(app, { cleanupDirs: [tmpHome, projectDir] });
+ captureStderrFor(app, { home: tmpHome, cleanupDirs: [tmpHome, projectDir] });
const editor = await findEditorWindow(app);
await editor.emulateMedia({ colorScheme: 'light' });
diff --git a/packages/desktop/tests/smoke/share-receive-miss-terminal.e2e.ts b/packages/desktop/tests/smoke/share-receive-miss-terminal.e2e.ts
index 065bc9903..74807dbfa 100644
--- a/packages/desktop/tests/smoke/share-receive-miss-terminal.e2e.ts
+++ b/packages/desktop/tests/smoke/share-receive-miss-terminal.e2e.ts
@@ -167,7 +167,7 @@ async function expectDeletedTargetMiss(
timeout: 30_000,
}),
);
- captureStderrFor(app, { cleanupDirs: [fixture.root, tmpHome] });
+ captureStderrFor(app, { home: tmpHome, cleanupDirs: [fixture.root, tmpHome] });
const firstWindow = await app.firstWindow({ timeout: 15_000 });
expect(firstWindow).toBeDefined();
@@ -259,7 +259,7 @@ test.describe('share-receive miss terminal smoke', () => {
timeout: 30_000,
}),
);
- captureStderrFor(app, { cleanupDirs: [tmpHome] });
+ captureStderrFor(app, { home: tmpHome, cleanupDirs: [tmpHome] });
await app.firstWindow({ timeout: 15_000 });
let dialogText = '';
diff --git a/packages/desktop/tests/smoke/share-receive-multi-worktree.e2e.ts b/packages/desktop/tests/smoke/share-receive-multi-worktree.e2e.ts
index a948f4578..9caa3aded 100644
--- a/packages/desktop/tests/smoke/share-receive-multi-worktree.e2e.ts
+++ b/packages/desktop/tests/smoke/share-receive-multi-worktree.e2e.ts
@@ -110,6 +110,7 @@ test.describe('share-receive multi-worktree smoke (US-014 / J1 silent dispatch)'
}),
);
captureStderrFor(app, {
+ home: tmpHome,
cleanupDirs: [fixture.root, tmpHome],
});
diff --git a/packages/desktop/tests/smoke/sidebar-create-rename-editable.e2e.ts b/packages/desktop/tests/smoke/sidebar-create-rename-editable.e2e.ts
index 3837e0ded..17899bd68 100644
--- a/packages/desktop/tests/smoke/sidebar-create-rename-editable.e2e.ts
+++ b/packages/desktop/tests/smoke/sidebar-create-rename-editable.e2e.ts
@@ -150,7 +150,7 @@ test.describe('Sidebar create and rename editability smoke', () => {
}) => {
const seed = seedProject('editable');
const app = await launchApp(seed);
- captureStderrFor(app, { cleanupDirs: [seed.tmpHome, seed.projectDir] });
+ captureStderrFor(app, { home: seed.tmpHome, cleanupDirs: [seed.tmpHome, seed.projectDir] });
const page = await findEditorWindow(app, 'start');
await expect(
diff --git a/packages/desktop/tests/smoke/skill-scope-roundtrip.e2e.ts b/packages/desktop/tests/smoke/skill-scope-roundtrip.e2e.ts
index 2915dbadf..8af35d54f 100644
--- a/packages/desktop/tests/smoke/skill-scope-roundtrip.e2e.ts
+++ b/packages/desktop/tests/smoke/skill-scope-roundtrip.e2e.ts
@@ -37,7 +37,7 @@ test.describe('Skill scope round-trip', () => {
env: { ...process.env, HOME: tmpHome, OK_M6B_FORCE: '1' },
timeout: 30_000,
});
- captureStderrFor(app, { cleanupDirs: [projectDir, tmpHome] });
+ captureStderrFor(app, { home: tmpHome, cleanupDirs: [projectDir, tmpHome] });
await app.firstWindow({ timeout: 15_000 });
const page = await (async () => {
diff --git a/packages/desktop/tests/smoke/skills-studio.e2e.ts b/packages/desktop/tests/smoke/skills-studio.e2e.ts
index a6d14c92e..5e0284c61 100644
--- a/packages/desktop/tests/smoke/skills-studio.e2e.ts
+++ b/packages/desktop/tests/smoke/skills-studio.e2e.ts
@@ -42,7 +42,7 @@ test.describe('Skills Studio', () => {
env: { ...process.env, HOME: tmpHome, OK_M6B_FORCE: '1' },
timeout: 30_000,
});
- captureStderrFor(app, { cleanupDirs: [projectDir, tmpHome] });
+ captureStderrFor(app, { home: tmpHome, cleanupDirs: [projectDir, tmpHome] });
await app.firstWindow({ timeout: 15_000 });
const page = await (async () => {
diff --git a/packages/desktop/tests/smoke/slidev-render-readiness.e2e.ts b/packages/desktop/tests/smoke/slidev-render-readiness.e2e.ts
index ba8f5b4a5..97d3edef0 100644
--- a/packages/desktop/tests/smoke/slidev-render-readiness.e2e.ts
+++ b/packages/desktop/tests/smoke/slidev-render-readiness.e2e.ts
@@ -125,7 +125,7 @@ test.describe('Slidev renderer readiness smoke', () => {
},
}),
);
- captureStderrFor(app, { cleanupDirs: [tmpHome, projectDir] });
+ captureStderrFor(app, { home: tmpHome, cleanupDirs: [tmpHome, projectDir] });
try {
await expect
.poll(() => findEditor(app), { timeout: 30_000, message: 'editor window did not open' })
@@ -202,7 +202,7 @@ test.describe('Slidev renderer readiness smoke', () => {
},
}),
);
- captureStderrFor(app, { cleanupDirs: [tmpHome, projectDir] });
+ captureStderrFor(app, { home: tmpHome, cleanupDirs: [tmpHome, projectDir] });
try {
await expect
.poll(() => findEditor(app), { timeout: 30_000, message: 'editor window did not open' })
diff --git a/packages/desktop/tests/smoke/terminal-dock.e2e.ts b/packages/desktop/tests/smoke/terminal-dock.e2e.ts
index 34e779981..40ab803bf 100644
--- a/packages/desktop/tests/smoke/terminal-dock.e2e.ts
+++ b/packages/desktop/tests/smoke/terminal-dock.e2e.ts
@@ -12,6 +12,7 @@ import { basename, join } from 'node:path';
import type { ElectronApplication, Locator, Page } from '@playwright/test';
import { _electron as electron } from '@playwright/test';
import { desktopLaunchOptions, resolveDesktopTarget } from './_helpers/launch-desktop';
+import { launchDesktopApp, waitForWindowByMode } from './_helpers/launch-readiness';
import {
PTY_PLATFORM_SKIP_REASON,
PTY_PLATFORM_SUPPORTED,
@@ -111,7 +112,8 @@ interface LaunchOpts {
async function launchApp(s: Seed, opts: LaunchOpts = {}): Promise<ElectronApplication> {
const deepLink = `openknowledge://open?project=${encodeURIComponent(s.projectDir)}&doc=start`;
- return electron.launch(
+ return launchDesktopApp(
+ electron,
desktopLaunchOptions({
target: TARGET,
args: [`--user-data-dir=${s.userDataDir}`, deepLink],
@@ -126,23 +128,12 @@ async function launchApp(s: Seed, opts: LaunchOpts = {}): Promise<ElectronApplic
OK_RECLAIM_DISABLE: '1',
},
}),
+ { home: s.tmpHome },
);
}
-async function findEditorWindow(app: ElectronApplication, timeoutMs = 25_000): Promise<Page> {
- let page: Page | undefined;
- await expect(async () => {
- for (const p of app.windows()) {
- const mode = await p.evaluate(() => window.okDesktop?.config?.mode).catch(() => undefined);
- if (mode === 'editor') {
- page = p;
- return;
- }
- }
- throw new Error('no editor window yet');
- }).toPass({ timeout: timeoutMs });
- if (!page) throw new Error('editor window vanished after readiness poll');
- return page;
+async function findEditorWindow(app: ElectronApplication): Promise<Page> {
+ return waitForWindowByMode(app, 'editor');
}
async function dispatchRendererMenuAction(
@@ -393,7 +384,7 @@ test.describe('Docked terminal — live Electron', () => {
const s = seed('default-on');
track(s.tmpHome, s.projectDir);
const app = await launchApp(s, { restrictPath: true });
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await openTerminal(app, page);
await waitForStatus(page, 'running', 25_000);
@@ -406,7 +397,7 @@ test.describe('Docked terminal — live Electron', () => {
const s = seed('default-on-no-write');
track(s.tmpHome, s.projectDir);
const app = await launchApp(s, { restrictPath: true });
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await openTerminal(app, page);
await waitForStatus(page, 'running', 25_000);
@@ -422,7 +413,7 @@ test.describe('Docked terminal — live Electron', () => {
const s = seed('opt-out', { optOut: true });
track(s.tmpHome, s.projectDir);
const app = await launchApp(s, { restrictPath: true });
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await revealTerminalSurface(app, page.getByRole('region', { name: 'Terminal disabled' }));
@@ -440,7 +431,7 @@ test.describe('Docked terminal — live Electron', () => {
const s = seed('toggle', { consent: true });
track(s.tmpHome, s.projectDir);
const app = await launchApp(s);
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
expect(await viewTerminalLabel(app)).toBe('Show Terminal');
@@ -457,7 +448,7 @@ test.describe('Docked terminal — live Electron', () => {
const s = seed('placement-menu', { consent: true });
track(s.tmpHome, s.projectDir);
const app = await launchApp(s);
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
await findEditorWindow(app);
expect(await terminalPlacementLabel(app)).toBe('Move Terminal to right');
@@ -478,7 +469,7 @@ test.describe('Docked terminal — live Electron', () => {
const s = seed('header-placement', { consent: true });
track(s.tmpHome, s.projectDir);
const app = await launchApp(s);
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await widenEditorWindow(app, page, 1900, 900);
@@ -516,7 +507,7 @@ test.describe('Docked terminal — live Electron', () => {
const s = seed('divider-pointerleave', { consent: true });
track(s.tmpHome, s.projectDir);
const app = await launchApp(s);
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await widenEditorWindow(app, page, 1900, 900);
@@ -583,7 +574,7 @@ test.describe('Docked terminal — live Electron', () => {
const s = seed('rail-admission', { consent: true, skipRestoreState: true });
track(s.tmpHome, s.projectDir);
const app = await launchApp(s);
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await widenEditorWindow(app, page, 1900, 900);
@@ -637,7 +628,7 @@ test.describe('Docked terminal — live Electron', () => {
const s = seed('perf', { consent: true });
track(s.tmpHome, s.projectDir);
const app = await launchApp(s);
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await waitForRendererResponsive(page);
@@ -664,7 +655,7 @@ test.describe('Docked terminal — live Electron', () => {
const s = seed('cmd', { consent: true });
track(s.tmpHome, s.projectDir);
const app = await launchApp(s, { restrictPath: true });
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await openTerminal(app, page);
await waitForStatus(page, 'running', 25_000);
@@ -685,7 +676,7 @@ test.describe('Docked terminal — live Electron', () => {
const s = seed('resize-storm', { consent: true });
track(s.tmpHome, s.projectDir);
const app = await launchApp(s, { restrictPath: true });
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await openTerminal(app, page);
await waitForStatus(page, 'running', 25_000);
@@ -729,7 +720,7 @@ test.describe('Docked terminal — live Electron', () => {
const s = seed('dock-controls', { consent: true });
track(s.tmpHome, s.projectDir);
const app = await launchApp(s, { restrictPath: true });
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await openTerminal(app, page);
await waitForStatus(page, 'running', 25_000);
@@ -746,7 +737,7 @@ test.describe('Docked terminal — live Electron', () => {
const s = seed('dock-edges', { consent: true });
track(s.tmpHome, s.projectDir);
const app = await launchApp(s, { restrictPath: true });
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await openTerminal(app, page);
await waitForStatus(page, 'running', 25_000);
@@ -763,7 +754,7 @@ test.describe('Docked terminal — live Electron', () => {
const s = seed('a11y', { consent: true });
track(s.tmpHome, s.projectDir);
const app = await launchApp(s, { restrictPath: true });
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await openTerminal(app, page);
await waitForStatus(page, 'running', 25_000);
@@ -780,7 +771,7 @@ test.describe('Docked terminal — live Electron', () => {
const s = seed('escape', { consent: true });
track(s.tmpHome, s.projectDir);
const app = await launchApp(s, { restrictPath: true });
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await openTerminal(app, page);
await waitForStatus(page, 'running', 25_000);
@@ -805,7 +796,7 @@ test.describe('Docked terminal — live Electron', () => {
const s = seed('ctrl-backtick', { consent: true });
track(s.tmpHome, s.projectDir);
const app = await launchApp(s, { restrictPath: true });
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await openTerminal(app, page);
await waitForStatus(page, 'running', 25_000);
@@ -834,7 +825,7 @@ test.describe('Docked terminal — live Electron', () => {
const s = seed('inert', { consent: true });
track(s.tmpHome, s.projectDir);
const app = await launchApp(s, { restrictPath: true });
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await openTerminal(app, page);
await waitForStatus(page, 'running', 25_000);
@@ -859,7 +850,7 @@ test.describe('Docked terminal — live Electron', () => {
const s = seed('resize', { consent: true });
track(s.tmpHome, s.projectDir);
const app = await launchApp(s);
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await openTerminal(app, page);
await waitForStatus(page, 'running', 25_000);
@@ -905,7 +896,7 @@ test.describe('Docked terminal — live Electron', () => {
const s = seed('exit', { consent: true });
track(s.tmpHome, s.projectDir);
const app = await launchApp(s, { restrictPath: true });
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await openTerminal(app, page);
await waitForStatus(page, 'running', 25_000);
@@ -929,7 +920,7 @@ test.describe('Docked terminal — live Electron', () => {
const s = seed('claude-missing', { consent: true, pinRestrictedPath: true });
track(s.tmpHome, s.projectDir);
const app = await launchApp(s, { restrictPath: true });
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await openTerminal(app, page);
await waitForStatus(page, 'running', 25_000);
@@ -960,7 +951,7 @@ test.describe('Docked terminal — live Electron', () => {
});
track(s.tmpHome, s.projectDir);
const app = await launchApp(s, { restrictPath: true });
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await openTerminal(app, page);
await waitForStatus(page, 'running', 25_000);
@@ -987,7 +978,7 @@ test.describe('Docked terminal — live Electron', () => {
const s = seed('reload-survival', { consent: true });
track(s.tmpHome, s.projectDir);
const app = await launchApp(s, { restrictPath: true });
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await openTerminal(app, page);
await waitForStatus(page, 'running', 25_000);
@@ -1019,7 +1010,7 @@ test.describe('Docked terminal — live Electron', () => {
const s = seed('stage', { consent: true, fakeClaudeTui: true, skipRestoreState: true });
track(s.tmpHome, s.projectDir);
const app = await launchApp(s, { restrictPath: true });
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await page.evaluate(() => {
diff --git a/packages/desktop/tests/smoke/terminal-links.e2e.ts b/packages/desktop/tests/smoke/terminal-links.e2e.ts
index eb0f4f9ef..7cc58eb19 100644
--- a/packages/desktop/tests/smoke/terminal-links.e2e.ts
+++ b/packages/desktop/tests/smoke/terminal-links.e2e.ts
@@ -183,7 +183,7 @@ test.describe('Terminal clickable links — live Electron', () => {
const s = seed('url');
track(s.tmpHome, s.projectDir);
const app = await launchApp(s);
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await stubOpenExternal(app);
await openRunningTerminal(app, page);
@@ -203,7 +203,7 @@ test.describe('Terminal clickable links — live Electron', () => {
const s = seed('doc');
track(s.tmpHome, s.projectDir);
const app = await launchApp(s);
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await openRunningTerminal(app, page);
diff --git a/packages/desktop/tests/smoke/terminal-movement.e2e.ts b/packages/desktop/tests/smoke/terminal-movement.e2e.ts
index ed1d9634a..1a2360832 100644
--- a/packages/desktop/tests/smoke/terminal-movement.e2e.ts
+++ b/packages/desktop/tests/smoke/terminal-movement.e2e.ts
@@ -452,7 +452,7 @@ test.describe('Terminal placement continuity — live Electron', () => {
test.setTimeout(260_000);
const s = seed();
const app = await launchApp(s);
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await widenEditorWindow(app, page, 1900, 900);
@@ -528,7 +528,7 @@ test.describe('Terminal placement continuity — live Electron', () => {
test.setTimeout(290_000);
const s = seed({ skipRestoreState: true });
const app = await launchApp(s);
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await widenEditorWindow(app, page, 1900, 900);
@@ -633,7 +633,7 @@ test.describe('Terminal placement continuity — live Electron', () => {
}) => {
const s = seed();
const app = await launchApp(s);
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await openTerminal(app, page);
diff --git a/packages/desktop/tests/smoke/terminal-process-restart.e2e.ts b/packages/desktop/tests/smoke/terminal-process-restart.e2e.ts
index 91ef29e39..fc060d3d1 100644
--- a/packages/desktop/tests/smoke/terminal-process-restart.e2e.ts
+++ b/packages/desktop/tests/smoke/terminal-process-restart.e2e.ts
@@ -197,7 +197,7 @@ test.describe('terminal process restart', () => {
test.setTimeout(240_000);
const seed = seedRestartProfile();
const firstApp = await launchRestartProfile(seed);
- captureStderrFor(firstApp);
+ captureStderrFor(firstApp, { home: seed.tmpHome });
const firstProcess = firstApp.process();
const firstPage = await findEditorWindow(firstApp);
await setWindowSize(firstApp, firstPage, 1900, 900);
@@ -234,7 +234,10 @@ test.describe('terminal process restart', () => {
await quitAndWait(firstApp, firstProcess);
const secondApp = await launchRestartProfile(seed);
- captureStderrFor(secondApp, { cleanupDirs: [seed.tmpHome, seed.projectDir] });
+ captureStderrFor(secondApp, {
+ home: seed.tmpHome,
+ cleanupDirs: [seed.tmpHome, seed.projectDir],
+ });
const secondPage = await findEditorWindow(secondApp);
await setWindowSize(secondApp, secondPage, 1900, 900);
await expect(secondPage.locator('#terminal-column')).toBeVisible({ timeout: 25_000 });
diff --git a/packages/desktop/tests/smoke/terminal-tabs.e2e.ts b/packages/desktop/tests/smoke/terminal-tabs.e2e.ts
index 481980c56..d3da9d51b 100644
--- a/packages/desktop/tests/smoke/terminal-tabs.e2e.ts
+++ b/packages/desktop/tests/smoke/terminal-tabs.e2e.ts
@@ -205,7 +205,7 @@ test.describe('Terminal tabs — live Electron', () => {
const s = seed('two-shells');
track(s.tmpHome, s.projectDir);
const app = await launchApp(s);
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await openTerminal(app, page);
@@ -253,7 +253,7 @@ test.describe('Terminal tabs — live Electron', () => {
const s = seed('close-one');
track(s.tmpHome, s.projectDir);
const app = await launchApp(s);
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await openTerminal(app, page);
await openBareTab(page);
@@ -274,7 +274,7 @@ test.describe('Terminal tabs — live Electron', () => {
const s = seed('rename-pin');
track(s.tmpHome, s.projectDir);
const app = await launchApp(s);
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await openTerminal(app, page);
@@ -296,7 +296,7 @@ test.describe('Terminal tabs — live Electron', () => {
const s = seed('reorder-survive');
track(s.tmpHome, s.projectDir);
const app = await launchApp(s);
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await openTerminal(app, page);
@@ -340,7 +340,7 @@ test.describe('Terminal tabs — live Electron', () => {
const s = seed('drag-survive');
track(s.tmpHome, s.projectDir);
const app = await launchApp(s);
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await openTerminal(app, page);
@@ -379,7 +379,7 @@ test.describe('Terminal tabs — live Electron', () => {
const s = seed('reload-preserve');
track(s.tmpHome, s.projectDir);
const app = await launchApp(s);
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const page = await findEditorWindow(app);
await openTerminal(app, page);
diff --git a/packages/desktop/tests/smoke/terminal-window.e2e.ts b/packages/desktop/tests/smoke/terminal-window.e2e.ts
index 93b15799c..b953e04c1 100644
--- a/packages/desktop/tests/smoke/terminal-window.e2e.ts
+++ b/packages/desktop/tests/smoke/terminal-window.e2e.ts
@@ -161,7 +161,7 @@ test.describe('Standalone terminal window — live Electron', () => {
const s = seed('open-close');
track(s.tmpHome, s.projectDir);
const app = await launchApp(s);
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
const editor = await findWindowByMode(app, 'editor');
await waitForRendererResponsive(editor);
const editorWindow = await app.browserWindow(editor);
@@ -206,7 +206,7 @@ test.describe('Standalone terminal window — live Electron', () => {
const s = seed('multi');
track(s.tmpHome, s.projectDir);
const app = await launchApp(s);
- captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
await waitForRendererResponsive(await findWindowByMode(app, 'editor'));
expect(await clickNewTerminalWindow(app)).toBe(true);
diff --git a/packages/desktop/tests/smoke/theme-sync.e2e.ts b/packages/desktop/tests/smoke/theme-sync.e2e.ts
index 6bd8525b0..e5251677c 100644
--- a/packages/desktop/tests/smoke/theme-sync.e2e.ts
+++ b/packages/desktop/tests/smoke/theme-sync.e2e.ts
@@ -48,7 +48,7 @@ test.describe('chrome-modernization theme-sync smoke', () => {
timeout: 30_000,
}),
);
- captureStderrFor(app, { cleanupDirs: [tmpHome, projectDir] });
+ captureStderrFor(app, { home: tmpHome, cleanupDirs: [tmpHome, projectDir] });
const firstWindow = await app.firstWindow({ timeout: 15_000 });
expect(firstWindow).toBeDefined();
@@ -123,7 +123,7 @@ test.describe('chrome-modernization theme-sync smoke', () => {
timeout: 30_000,
}),
);
- captureStderrFor(app, { cleanupDirs: [tmpHome, projectDir] });
+ captureStderrFor(app, { home: tmpHome, cleanupDirs: [tmpHome, projectDir] });
await app.firstWindow({ timeout: 15_000 });
const deepLink = `openknowledge://open?project=${encodeURIComponent(projectDir)}&doc=${encodeURIComponent(docName)}`;
@@ -242,7 +242,7 @@ test.describe('chrome-modernization theme-sync smoke', () => {
timeout: 30_000,
}),
);
- captureStderrFor(app, { cleanupDirs: [tmpHome, projectDir] });
+ captureStderrFor(app, { home: tmpHome, cleanupDirs: [tmpHome, projectDir] });
await app.firstWindow({ timeout: 15_000 });
const deepLink = `openknowledge://open?project=${encodeURIComponent(projectDir)}&doc=${encodeURIComponent(docName)}`;
diff --git a/packages/desktop/tests/smoke/uninstall-ipc-bridge.e2e.ts b/packages/desktop/tests/smoke/uninstall-ipc-bridge.e2e.ts
index b40d6b6eb..671fb458a 100644
--- a/packages/desktop/tests/smoke/uninstall-ipc-bridge.e2e.ts
+++ b/packages/desktop/tests/smoke/uninstall-ipc-bridge.e2e.ts
@@ -47,7 +47,7 @@ test.describe('uninstall renderer IPC bridge smoke', () => {
timeout: 30_000,
}),
);
- captureStderrFor(app, { cleanupDirs: [home] });
+ captureStderrFor(app, { home, cleanupDirs: [home] });
await app.firstWindow({ timeout: 20_000 });
const editorWindow = await findWindowByPath(app, '/index.html');
diff --git a/packages/desktop/tests/smoke/uninstall-notice.e2e.ts b/packages/desktop/tests/smoke/uninstall-notice.e2e.ts
index cccd0977a..690ad5ca0 100644
--- a/packages/desktop/tests/smoke/uninstall-notice.e2e.ts
+++ b/packages/desktop/tests/smoke/uninstall-notice.e2e.ts
@@ -61,7 +61,7 @@ test.describe('uninstall notice smoke', () => {
test('pressing each notice through carries the answer to main', async ({ captureStderrFor }) => {
const { app, home } = await launchNoticePreview('ok-uninstall-notice-');
- captureStderrFor(app, { cleanupDirs: [home] });
+ captureStderrFor(app, { home, cleanupDirs: [home] });
await app.firstWindow({ timeout: 20_000 });
@@ -91,7 +91,7 @@ test.describe('uninstall notice smoke', () => {
captureStderrFor,
}) => {
const { app, home } = await launchNoticePreview('ok-uninstall-notice-close-');
- captureStderrFor(app, { cleanupDirs: [home] });
+ captureStderrFor(app, { home, cleanupDirs: [home] });
await app.firstWindow({ timeout: 20_000 });
diff --git a/packages/desktop/tests/smoke/uninstall-picker.e2e.ts b/packages/desktop/tests/smoke/uninstall-picker.e2e.ts
index 5d43c0570..215c3605a 100644
--- a/packages/desktop/tests/smoke/uninstall-picker.e2e.ts
+++ b/packages/desktop/tests/smoke/uninstall-picker.e2e.ts
@@ -49,7 +49,7 @@ test.describe('uninstall project picker smoke', () => {
timeout: 30_000,
}),
);
- captureStderrFor(app, { cleanupDirs: [home] });
+ captureStderrFor(app, { home, cleanupDirs: [home] });
await app.firstWindow({ timeout: 20_000 });
const picker = await findWindowByPath(app, '/uninstall.html');
@@ -98,7 +98,7 @@ test.describe('uninstall project picker smoke', () => {
timeout: 30_000,
}),
);
- captureStderrFor(app, { cleanupDirs: [home] });
+ captureStderrFor(app, { home, cleanupDirs: [home] });
await app.firstWindow({ timeout: 20_000 });
const picker = await findWindowByPath(app, '/uninstall.html');
diff --git a/packages/desktop/tests/smoke/uninstall-survey.e2e.ts b/packages/desktop/tests/smoke/uninstall-survey.e2e.ts
index 604d7f500..e0dfaea80 100644
--- a/packages/desktop/tests/smoke/uninstall-survey.e2e.ts
+++ b/packages/desktop/tests/smoke/uninstall-survey.e2e.ts
@@ -51,7 +51,7 @@ test.describe('uninstall churn survey smoke', () => {
test('carries a filled-in survey back to main as answers', async ({ captureStderrFor }) => {
const { app, home } = await launchSurveyPreview('ok-uninstall-survey-');
- captureStderrFor(app, { cleanupDirs: [home] });
+ captureStderrFor(app, { home, cleanupDirs: [home] });
await app.firstWindow({ timeout: 20_000 });
const survey = await findWindowByPath(app, '/uninstall.html');
@@ -85,7 +85,7 @@ test.describe('uninstall churn survey smoke', () => {
captureStderrFor,
}) => {
const { app, home } = await launchSurveyPreview('ok-uninstall-survey-close-');
- captureStderrFor(app, { cleanupDirs: [home] });
+ captureStderrFor(app, { home, cleanupDirs: [home] });
await app.firstWindow({ timeout: 20_000 });
const survey = await findWindowByPath(app, '/uninstall.html');
@@ -103,7 +103,7 @@ test.describe('uninstall churn survey smoke', () => {
test('skipping continues with nothing filed', async ({ captureStderrFor }) => {
const { app, home } = await launchSurveyPreview('ok-uninstall-survey-skip-');
- captureStderrFor(app, { cleanupDirs: [home] });
+ captureStderrFor(app, { home, cleanupDirs: [home] });
await app.firstWindow({ timeout: 20_000 });
const survey = await findWindowByPath(app, '/uninstall.html');
diff --git a/packages/desktop/tests/smoke/uninstall-window-chrome.e2e.ts b/packages/desktop/tests/smoke/uninstall-window-chrome.e2e.ts
index 72cda0320..195f692d3 100644
--- a/packages/desktop/tests/smoke/uninstall-window-chrome.e2e.ts
+++ b/packages/desktop/tests/smoke/uninstall-window-chrome.e2e.ts
@@ -49,7 +49,7 @@ test.describe('uninstall renderer chrome smoke', () => {
timeout: 30_000,
}),
);
- captureStderrFor(app, { cleanupDirs: [home] });
+ captureStderrFor(app, { home, cleanupDirs: [home] });
await app.firstWindow({ timeout: 20_000 });
const editorWindow = await findWindowByPath(app, '/index.html');
diff --git a/packages/desktop/tests/smoke/window-chrome.e2e.ts b/packages/desktop/tests/smoke/window-chrome.e2e.ts
index 8a833895c..eed9c929a 100644
--- a/packages/desktop/tests/smoke/window-chrome.e2e.ts
+++ b/packages/desktop/tests/smoke/window-chrome.e2e.ts
@@ -97,7 +97,7 @@ test.describe('Windows/Linux window chrome smoke', () => {
}) => {
const { tmpHome, projectDir } = seedHomeWithLastOpenedProject();
const app = await launchApp(tmpHome);
- captureStderrFor(app, { cleanupDirs: [tmpHome, projectDir] });
+ captureStderrFor(app, { home: tmpHome, cleanupDirs: [tmpHome, projectDir] });
const editor = await findEditorWindow(app);
const winHandle: JSHandle = await app.browserWindow(editor);
@@ -136,7 +136,7 @@ test.describe('Editor header drag-region smoke', () => {
}) => {
const { tmpHome, projectDir } = seedHomeWithLastOpenedProject();
const app = await launchApp(tmpHome);
- captureStderrFor(app, { cleanupDirs: [tmpHome, projectDir] });
+ captureStderrFor(app, { home: tmpHome, cleanupDirs: [tmpHome, projectDir] });
const editor = await findEditorWindow(app);
const filesToggle = editor
diff --git a/packages/desktop/tests/smoke/window-min-size.e2e.ts b/packages/desktop/tests/smoke/window-min-size.e2e.ts
index 47059e45d..5fc5c10d5 100644
--- a/packages/desktop/tests/smoke/window-min-size.e2e.ts
+++ b/packages/desktop/tests/smoke/window-min-size.e2e.ts
@@ -122,7 +122,7 @@ test.describe('BrowserWindow min-size smoke', () => {
}) => {
const { tmpHome, projectDir } = seedHomeWithLastOpenedProject('happy');
const app = await launchApp(tmpHome);
- captureStderrFor(app, { cleanupDirs: [tmpHome, projectDir] });
+ captureStderrFor(app, { home: tmpHome, cleanupDirs: [tmpHome, projectDir] });
const editor = await findWindow(app, 'editor');
const editorProbe = await readMinSizeFor(app, editor);