Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Order the smoke readiness give-up against the app's own deadline (#4813)

Nick Gomez9b92f897f39e
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 16b2ebbfd..aac7bbbef 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -133,6 +133,7 @@ import {
BOOT_HEARTBEAT_EVENTS,
BOOT_HEARTBEAT_MAX_BEATS,
DESKTOP_BOOT_EVENT,
+ DESKTOP_OPEN_PROJECT_FAILED_EVENT,
startupMarkLine,
} from '../shared/boot-narration.ts';
import type {
@@ -2092,7 +2093,7 @@ async function openProjectOrFallbackToNavigator(
(err as Error & { holderIsOwnChild?: boolean }).holderIsOwnChild === true;
getLogger('project').error(
{
- event: 'desktop-open-project-failed',
+ event: DESKTOP_OPEN_PROJECT_FAILED_EVENT,
projectPath,
entryPoint,
kind,
diff --git a/packages/desktop/src/shared/boot-narration.ts b/packages/desktop/src/shared/boot-narration.ts
index 1713fc8c9..19afbef47 100644
--- a/packages/desktop/src/shared/boot-narration.ts
+++ b/packages/desktop/src/shared/boot-narration.ts
@@ -12,6 +12,8 @@ export const BOOT_HEARTBEAT_MAX_BEATS = 24;
export const DESKTOP_BOOT_EVENT = 'desktop.boot';
+export const DESKTOP_OPEN_PROJECT_FAILED_EVENT = 'desktop-open-project-failed';
+
export const BOOT_HEARTBEAT_EVENTS = {
boot: 'desktop-boot-progress',
utilityWait: 'desktop-utility-wait-progress',
@@ -24,7 +26,6 @@ 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)
@@ -34,6 +35,10 @@ export function isBootHeartbeatEvent(event: string): boolean {
const STARTUP_MARK_EVENT_PREFIX = 'desktop.startup.';
+export function isStartupMarkEvent(event: string): boolean {
+ return event.startsWith(STARTUP_MARK_EVENT_PREFIX);
+}
+
export interface StartupMarkLine extends Record<string, unknown> {
readonly event: `${typeof STARTUP_MARK_EVENT_PREFIX}${WaterfallPhase}`;
readonly phase: WaterfallPhase;
diff --git a/packages/desktop/tests/smoke/_helpers/launch-readiness.test.ts b/packages/desktop/tests/smoke/_helpers/launch-readiness.test.ts
index 97a83c2eb..ec7fac0a5 100644
--- a/packages/desktop/tests/smoke/_helpers/launch-readiness.test.ts
+++ b/packages/desktop/tests/smoke/_helpers/launch-readiness.test.ts
@@ -8,6 +8,7 @@ import {
BOOT_HEARTBEAT_EVENTS,
BOOT_HEARTBEAT_MAX_BEATS,
DESKTOP_BOOT_EVENT,
+ DESKTOP_OPEN_PROJECT_FAILED_EVENT,
SPAWN_STARTUP_DEADLINE_MS,
SPAWN_WAIT_EXTENSION_FACTOR,
SPAWN_WAIT_HEARTBEAT_MS,
@@ -17,6 +18,7 @@ import {
import {
BOOT_LOG_CAP_MS,
BOOT_LOG_HEARTBEAT_MS,
+ BOOT_LOG_POLL_MS,
BOOT_LOG_STALL_MS,
type BootLogSnapshot,
bootGapLineFor,
@@ -33,6 +35,7 @@ import {
launchDesktopApp,
launchHomeFor,
READY_WAIT_GIVE_UP_REASONS,
+ type ReadyDeadline,
readBootLog,
readBootLogLines,
readyWaitsFor,
@@ -173,6 +176,25 @@ describe('waitForReadySignal — progress gating', () => {
expect(clock).toBeLessThanOrEqual(BOOT_LOG_STALL_MS + 1_000);
});
+ it('still names the first window as the end of narration when no window has been shown', async () => {
+ let clock = 0;
+ const message = await waitForReadySignal<string>({
+ probe: async () => undefined,
+ home: '/unused',
+ what: 'editor window',
+ now: () => clock,
+ sleep: async () => {
+ clock += 1_000;
+ },
+ readLog: () => snapshot({ lineCount: 3, lastEvent: 'desktop.boot' }),
+ }).then(
+ () => 'the wait resolved instead of giving up',
+ (error: unknown) => (error as Error).message,
+ );
+ expect(message).toContain('until the first window is shown');
+ expect(message).not.toContain('while a startup phase it declared is still open');
+ });
+
it('names the boot phase and the log tail when it gives up', async () => {
let clock = 0;
await expect(
@@ -785,12 +807,6 @@ describe('the cap is a livelock backstop, deliberately tighter than the app can
expect(BOOT_LOG_STALL_MS).toBeLessThan(BOOT_LOG_CAP_MS);
});
- it("clears the unpackaged app's own utility-fork deadline by the observation margin", () => {
- expect(BOOT_LOG_CAP_MS - UTILITY_INIT_TIMEOUT_MS).toBeGreaterThanOrEqual(
- UTILITY_TIMEOUT_OBSERVATION_MARGIN_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);
});
@@ -800,6 +816,441 @@ describe('the cap is a livelock backstop, deliberately tighter than the app can
});
});
+const DEEP_LINK_APP_T0 = Date.parse('2026-09-22T14:28:32.504Z');
+
+const LAUNCH_RESOLVED_AT_MS = 400;
+
+const MEASURED_FORK_OFFSETS = [861, 3919, 6210, 10423] as const;
+
+const UTILITY_TIMEOUT_VERDICT = `utility init timed out after ${UTILITY_INIT_TIMEOUT_MS}ms`;
+
+const LATE_WINDOW_FORK_MS = 3_514;
+
+interface NarrationLine {
+ at: number;
+ text: string;
+}
+
+function isoAt(atMs: number): string {
+ return new Date(DEEP_LINK_APP_T0 + atMs).toISOString();
+}
+
+function markAt(phase: string, atMs: number): NarrationLine {
+ return { at: atMs, text: markLine(phase, atMs, isoAt(atMs)) };
+}
+
+function eventAt(atMs: number, body: Record<string, unknown>): NarrationLine {
+ return { at: atMs, text: JSON.stringify({ time: isoAt(atMs), ...body }) };
+}
+
+function deepLinkNarration(forkAtMs: number): NarrationLine[] {
+ const beats: NarrationLine[] = [];
+ for (
+ let beat = SPAWN_WAIT_HEARTBEAT_MS;
+ beat < UTILITY_INIT_TIMEOUT_MS;
+ beat += SPAWN_WAIT_HEARTBEAT_MS
+ ) {
+ beats.push(
+ eventAt(forkAtMs + beat, {
+ event: BOOT_HEARTBEAT_EVENTS.utilityWait,
+ elapsedMs: beat,
+ initTimeoutMs: UTILITY_INIT_TIMEOUT_MS,
+ }),
+ );
+ }
+ return [
+ eventAt(0, { event: DESKTOP_BOOT_EVENT }),
+ markAt('serverSpawned', forkAtMs),
+ eventAt(forkAtMs + 900, { event: 'desktop-navigator-load-resolved' }),
+ markAt('windowShown', forkAtMs + 1_300),
+ ...beats,
+ eventAt(forkAtMs + UTILITY_INIT_TIMEOUT_MS, {
+ event: DESKTOP_OPEN_PROJECT_FAILED_EVENT,
+ entryPoint: 'deep-link',
+ err: { message: UTILITY_TIMEOUT_VERDICT },
+ }),
+ ];
+}
+
+function lateWindowNarration(): NarrationLine[] {
+ return [
+ ...deepLinkNarration(LATE_WINDOW_FORK_MS).slice(0, -1),
+ markAt('serverLockReady', 22_213),
+ markAt('windowCreated', 22_231),
+ markAt('loadUrlResolved', 23_445),
+ eventAt(23_474, { subsystem: 'project', msg: 'project window created' }),
+ ];
+}
+
+interface VirtualClock {
+ now: () => number;
+ sleep: (ms: number) => Promise<void>;
+ startDeadline: (ms: number) => ReadyDeadline;
+ readLog: (home: string) => BootLogSnapshot;
+}
+
+function virtualClock(home: string, narration: readonly NarrationLine[]): VirtualClock {
+ let clock = 0;
+ const pending: { at: number; resolve: () => void }[] = [];
+ const logFile = join(bootLogDirFor(home), 'desktop.0.log');
+ const publish = (): void => {
+ const appElapsed = LAUNCH_RESOLVED_AT_MS + clock;
+ const visible = narration.filter((entry) => entry.at <= appElapsed).map((entry) => entry.text);
+ writeFileSync(logFile, visible.length === 0 ? '' : `${visible.join('\n')}\n`, 'utf8');
+ };
+ publish();
+ return {
+ now: () => clock,
+ sleep: async (ms: number) => {
+ clock += ms;
+ for (let i = pending.length - 1; i >= 0; i -= 1) {
+ const entry = pending[i];
+ if (entry !== undefined && entry.at <= clock) {
+ pending.splice(i, 1);
+ entry.resolve();
+ }
+ }
+ await new Promise((resolve) => setImmediate(resolve));
+ },
+ startDeadline: (ms: number) => {
+ const reached = Promise.withResolvers<void>();
+ const entry = { at: clock + ms, resolve: reached.resolve };
+ pending.push(entry);
+ return {
+ expired: reached.promise,
+ cancel: () => {
+ const index = pending.indexOf(entry);
+ if (index >= 0) pending.splice(index, 1);
+ },
+ };
+ },
+ readLog: (readFrom: string) => {
+ publish();
+ return readBootLog(readFrom);
+ },
+ };
+}
+
+interface WaitOutcome {
+ gaveUp: boolean;
+ message: string;
+ elapsedMs: number;
+}
+
+async function waitWithoutEditorWindow(narration: readonly NarrationLine[]): Promise<WaitOutcome> {
+ const home = seedHome();
+ mkdirSync(bootLogDirFor(home), { recursive: true });
+ const clock = virtualClock(home, narration);
+ const settled = await waitForReadySignal<string>({
+ home,
+ what: 'editor window',
+ probe: async () => undefined,
+ now: clock.now,
+ sleep: clock.sleep,
+ readLog: clock.readLog,
+ startDeadline: clock.startDeadline,
+ }).then(
+ () => ({ gaveUp: false, message: '' }),
+ (error: unknown) => ({ gaveUp: true, message: (error as Error).message }),
+ );
+ return { ...settled, elapsedMs: clock.now() };
+}
+
+function verdictReadableAtMs(forkAtMs: number): number {
+ return forkAtMs + UTILITY_INIT_TIMEOUT_MS - LAUNCH_RESOLVED_AT_MS;
+}
+
+const FORKS_THE_STATIC_CAP_CUTS_SHORT = MEASURED_FORK_OFFSETS.filter(
+ (forkAtMs) => verdictReadableAtMs(forkAtMs) > BOOT_LOG_CAP_MS,
+);
+
+describe("the wait outlives the app's own deadline for the phase the window is gated behind", () => {
+ it('runs exactly the measured forks whose verdict lands past the static cap', () => {
+ expect(FORKS_THE_STATIC_CAP_CUTS_SHORT).toEqual([6210, 10423]);
+ });
+
+ it.each(FORKS_THE_STATIC_CAP_CUTS_SHORT)(
+ "reports the app's own open-project verdict when the utility fork landed at %ims",
+ async (forkAtMs) => {
+ const outcome = await waitWithoutEditorWindow(deepLinkNarration(forkAtMs));
+ expect(outcome.gaveUp).toBe(true);
+ expect(outcome.elapsedMs).toBeGreaterThan(BOOT_LOG_CAP_MS);
+ expect(outcome.message).toContain(DESKTOP_OPEN_PROJECT_FAILED_EVENT);
+ expect(outcome.message).toContain(UTILITY_TIMEOUT_VERDICT);
+ expect(outcome.message).not.toContain(
+ `Last main-process boot event: ${BOOT_HEARTBEAT_EVENTS.utilityWait}`,
+ );
+ },
+ );
+
+ it("stays inside the app's own declared budget when the app never publishes a verdict", async () => {
+ const forkAtMs = MEASURED_FORK_OFFSETS[2];
+ const outcome = await waitWithoutEditorWindow(deepLinkNarration(forkAtMs).slice(0, -1));
+ expect(outcome.gaveUp).toBe(true);
+ expect(outcome.elapsedMs).toBeLessThanOrEqual(
+ forkAtMs -
+ LAUNCH_RESOLVED_AT_MS +
+ UTILITY_INIT_TIMEOUT_MS +
+ UTILITY_TIMEOUT_OBSERVATION_MARGIN_MS,
+ );
+ });
+});
+
+describe('the give-up describes the narration the wait actually read', () => {
+ it('does not report activity across a silence that ran through the whole open phase', async () => {
+ const silentAfterFirstWindow = deepLinkNarration(MEASURED_FORK_OFFSETS[0]).slice(0, 4);
+ const outcome = await waitWithoutEditorWindow(silentAfterFirstWindow);
+ expect(outcome.gaveUp).toBe(true);
+ expect(outcome.message).not.toContain('kept logging boot activity');
+ expect(outcome.message).toContain('logged no new boot activity');
+ });
+
+ it('treats the app going quiet after its own verdict as a closed phase, not a stall', async () => {
+ const verdictThenQuiet: NarrationLine[] = [
+ eventAt(0, { event: DESKTOP_BOOT_EVENT }),
+ markAt('serverSpawned', 500),
+ markAt('windowShown', 1_800),
+ eventAt(5_500, {
+ event: BOOT_HEARTBEAT_EVENTS.utilityWait,
+ elapsedMs: 5_000,
+ initTimeoutMs: UTILITY_INIT_TIMEOUT_MS,
+ }),
+ eventAt(7_000, {
+ event: DESKTOP_OPEN_PROJECT_FAILED_EVENT,
+ entryPoint: 'deep-link',
+ err: { message: UTILITY_TIMEOUT_VERDICT },
+ }),
+ ];
+ const outcome = await waitWithoutEditorWindow(verdictThenQuiet);
+ expect(outcome.gaveUp).toBe(true);
+ expect(outcome.elapsedMs).toBe(BOOT_LOG_CAP_MS);
+ expect(outcome.message).not.toContain('logged no new boot activity');
+ expect(outcome.message).toContain('kept logging boot activity');
+ });
+});
+
+describe('the boot-gap line covers the phase the wait gave up in', () => {
+ const narration = lateWindowNarration();
+ const lines = narration.map((entry) => entry.text);
+ const launchSpanMs = (narration.at(-1)?.at ?? 0) - (narration[0]?.at ?? 0);
+ const heartbeatsEmitted = narration.filter((entry) =>
+ entry.text.includes(BOOT_HEARTBEAT_EVENTS.utilityWait),
+ ).length;
+
+ it('spans the whole launch the harness read, not the prefix that ends at the first window', () => {
+ expect(launchSpanMs).toBeGreaterThan(0);
+ expect(bootLogGapSummary(lines).totalBootMs).toBe(launchSpanMs);
+ });
+
+ it('counts the heartbeats the app emitted after it showed its first window', () => {
+ expect(heartbeatsEmitted).toBeGreaterThan(0);
+ expect(bootLogGapSummary(lines).beatsSeen).toBe(heartbeatsEmitted);
+ });
+
+ it('renders that span into the [boot-gap] triage line', () => {
+ const line = bootGapLineFor({
+ slot: 0,
+ narration: bootNarrationFor(lines, snapshot({ lines, lineCount: lines.length })),
+ readyWaitCount: 1,
+ homeShared: false,
+ });
+ expect(formatBootGapLine(line)).toContain(`totalBootMs=${launchSpanMs}`);
+ });
+});
+
+function withUtilityBeats(
+ narration: readonly NarrationLine[],
+ rewrite: (beat: Record<string, unknown>) => string,
+): NarrationLine[] {
+ return narration.map((entry) => {
+ const parsed = JSON.parse(entry.text) as Record<string, unknown>;
+ return parsed.event === BOOT_HEARTBEAT_EVENTS.utilityWait
+ ? { at: entry.at, text: rewrite(parsed) }
+ : entry;
+ });
+}
+
+describe('a budget the app did not declare cleanly buys the wait no extra time', () => {
+ const granting = deepLinkNarration(MEASURED_FORK_OFFSETS[2]);
+
+ it('outlives the static cap when every beat declares a well-formed budget', async () => {
+ const outcome = await waitWithoutEditorWindow(granting);
+ expect(outcome.gaveUp).toBe(true);
+ expect(outcome.elapsedMs).toBeGreaterThan(BOOT_LOG_CAP_MS);
+ expect(outcome.message).toContain(UTILITY_TIMEOUT_VERDICT);
+ });
+
+ it.each([
+ [
+ 'an initTimeoutMs that is not a number',
+ (beat: Record<string, unknown>) =>
+ JSON.stringify({ ...beat, initTimeoutMs: String(beat.initTimeoutMs) }),
+ ],
+ [
+ 'an initTimeoutMs the JSON parse overflowed to Infinity',
+ (beat: Record<string, unknown>) =>
+ JSON.stringify(beat).replace(
+ `"initTimeoutMs":${UTILITY_INIT_TIMEOUT_MS}`,
+ '"initTimeoutMs":1e999',
+ ),
+ ],
+ [
+ 'a negative elapsedMs',
+ (beat: Record<string, unknown>) =>
+ JSON.stringify({ ...beat, elapsedMs: -(beat.elapsedMs as number) }),
+ ],
+ [
+ 'a beat line that does not parse',
+ (beat: Record<string, unknown>) => `${JSON.stringify(beat)}{`,
+ ],
+ [
+ 'an initTimeoutMs larger than the budget the app can declare',
+ (beat: Record<string, unknown>) =>
+ JSON.stringify({ ...beat, initTimeoutMs: UTILITY_INIT_TIMEOUT_MS * 2 }),
+ ],
+ [
+ 'the budget on a heartbeat that does not own the open phase',
+ (beat: Record<string, unknown>) =>
+ JSON.stringify({ ...beat, event: BOOT_HEARTBEAT_EVENTS.spawnWait }),
+ ],
+ ])('stops at the static cap when the app published %s', async (_label, rewrite) => {
+ const outcome = await waitWithoutEditorWindow(withUtilityBeats(granting, rewrite));
+ expect(outcome.gaveUp).toBe(true);
+ expect(outcome.elapsedMs).toBe(BOOT_LOG_CAP_MS);
+ expect(outcome.message).not.toContain(UTILITY_TIMEOUT_VERDICT);
+ });
+
+ it('stops granting once the app overruns the budget it kept declaring', async () => {
+ const forkAtMs = MEASURED_FORK_OFFSETS[2];
+ const overrunBeats: NarrationLine[] = [];
+ for (
+ let elapsedMs = UTILITY_INIT_TIMEOUT_MS;
+ elapsedMs <= UTILITY_INIT_TIMEOUT_MS * 2;
+ elapsedMs += SPAWN_WAIT_HEARTBEAT_MS
+ ) {
+ overrunBeats.push(
+ eventAt(forkAtMs + elapsedMs, {
+ event: BOOT_HEARTBEAT_EVENTS.utilityWait,
+ elapsedMs,
+ initTimeoutMs: UTILITY_INIT_TIMEOUT_MS,
+ }),
+ );
+ }
+ const lastBeatReadableAt = (overrunBeats.at(-1)?.at ?? 0) - LAUNCH_RESOLVED_AT_MS;
+ expect(overrunBeats.length).toBeGreaterThan(1);
+ expect(lastBeatReadableAt).toBeGreaterThan(BOOT_LOG_CAP_MS);
+ const outcome = await waitWithoutEditorWindow([
+ ...deepLinkNarration(forkAtMs).slice(0, -1),
+ ...overrunBeats,
+ ]);
+ expect(outcome.gaveUp).toBe(true);
+ expect(outcome.elapsedMs).toBeLessThan(lastBeatReadableAt);
+ });
+
+ it('still takes a beat that reports it is exactly at the budget it declares', async () => {
+ const forkAtMs = MEASURED_FORK_OFFSETS[0];
+ const atBudget = [
+ ...deepLinkNarration(forkAtMs).slice(0, -1),
+ eventAt(forkAtMs + UTILITY_INIT_TIMEOUT_MS, {
+ event: BOOT_HEARTBEAT_EVENTS.utilityWait,
+ elapsedMs: UTILITY_INIT_TIMEOUT_MS,
+ initTimeoutMs: UTILITY_INIT_TIMEOUT_MS,
+ }),
+ ];
+ const outcome = await waitWithoutEditorWindow(atBudget);
+ expect(outcome.gaveUp).toBe(true);
+ expect(outcome.elapsedMs).toBeGreaterThan(BOOT_LOG_CAP_MS);
+ });
+});
+
+function slowForkNarration(): NarrationLine[] {
+ const forkAtMs = BOOT_LOG_CAP_MS + LAUNCH_RESOLVED_AT_MS - SPAWN_WAIT_HEARTBEAT_MS;
+ const lines: NarrationLine[] = [eventAt(0, { event: DESKTOP_BOOT_EVENT })];
+ for (let at = SPAWN_WAIT_HEARTBEAT_MS; at < forkAtMs; at += SPAWN_WAIT_HEARTBEAT_MS) {
+ lines.push(eventAt(at, { event: BOOT_HEARTBEAT_EVENTS.navigatorLoad, elapsedMs: at }));
+ }
+ lines.push(markAt('serverSpawned', forkAtMs), markAt('windowShown', forkAtMs + 1_300));
+ for (
+ let elapsedMs = SPAWN_WAIT_HEARTBEAT_MS;
+ elapsedMs < UTILITY_INIT_TIMEOUT_MS;
+ elapsedMs += SPAWN_WAIT_HEARTBEAT_MS
+ ) {
+ lines.push(
+ eventAt(forkAtMs + elapsedMs, {
+ event: BOOT_HEARTBEAT_EVENTS.utilityWait,
+ elapsedMs,
+ initTimeoutMs: UTILITY_INIT_TIMEOUT_MS,
+ }),
+ );
+ }
+ return lines;
+}
+
+describe('the extension keeps the probe running rather than only deferring the verdict', () => {
+ it('finds a window that arrives after the static cap but inside the declared budget', async () => {
+ const home = seedHome();
+ mkdirSync(bootLogDirFor(home), { recursive: true });
+ const clock = virtualClock(home, deepLinkNarration(MEASURED_FORK_OFFSETS[2]));
+ const found = await waitForReadySignal<string>({
+ home,
+ what: 'editor window',
+ probe: async () => (clock.now() > BOOT_LOG_CAP_MS ? 'late-editor-page' : undefined),
+ now: clock.now,
+ sleep: clock.sleep,
+ readLog: clock.readLog,
+ startDeadline: clock.startDeadline,
+ });
+ expect(found).toBe('late-editor-page');
+ expect(clock.now()).toBeGreaterThan(BOOT_LOG_CAP_MS);
+ });
+
+ it('keeps probing when the first declared budget lands on the poll the static cap fires', async () => {
+ const home = seedHome();
+ mkdirSync(bootLogDirFor(home), { recursive: true });
+ const clock = virtualClock(home, slowForkNarration());
+ const found = await waitForReadySignal<string>({
+ home,
+ what: 'editor window',
+ probe: async () => (clock.now() > BOOT_LOG_CAP_MS ? 'post-cap-editor-page' : undefined),
+ now: clock.now,
+ sleep: clock.sleep,
+ readLog: clock.readLog,
+ startDeadline: clock.startDeadline,
+ });
+ expect(found).toBe('post-cap-editor-page');
+ expect(clock.now()).toBeGreaterThan(BOOT_LOG_CAP_MS);
+ });
+
+ it('stops blaming a probe that was outstanding when the cap it outlived fired', async () => {
+ const home = seedHome();
+ mkdirSync(bootLogDirFor(home), { recursive: true });
+ const clock = virtualClock(home, slowForkNarration());
+ let overranTheCap = false;
+ const outcome = await waitForReadySignal<string>({
+ home,
+ what: 'editor window',
+ probe: async () => {
+ if (!overranTheCap && clock.now() >= BOOT_LOG_CAP_MS - BOOT_LOG_POLL_MS) {
+ overranTheCap = true;
+ await clock.sleep(BOOT_LOG_POLL_MS * 2);
+ }
+ return undefined;
+ },
+ now: clock.now,
+ sleep: clock.sleep,
+ readLog: clock.readLog,
+ startDeadline: clock.startDeadline,
+ }).then(
+ () => ({ gaveUp: false, message: '' }),
+ (error: unknown) => ({ gaveUp: true, message: (error as Error).message }),
+ );
+ expect(overranTheCap).toBe(true);
+ expect(outcome.gaveUp).toBe(true);
+ expect(clock.now()).toBeGreaterThan(BOOT_LOG_CAP_MS);
+ expect(outcome.message).not.toContain('The last probe had not answered when the cap fired.');
+ });
+});
+
describe('the stall rule applies only while boot narration is live', () => {
const late = (mode: string) => {
let polls = 0;
@@ -838,25 +1289,56 @@ describe('the stall rule applies only while boot narration is live', () => {
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 () => {
+ const MID_WAIT_CAP_MS = 20_000;
+
+ const BOOT_ONLY_SEED = [
+ JSON.stringify({ event: DESKTOP_BOOT_EVENT, time: '2026-09-04T00:00:00.000Z' }),
+ ];
+
+ const windowShownMidWait = (seed: readonly string[]) => {
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);
+ const lines = [...seed];
+ const settled = waitForReadySignal<string>({
+ probe: async () => undefined,
+ home: '/unused',
+ what: 'editor window',
+ capMs: MID_WAIT_CAP_MS,
+ 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' }),
+ });
+ return { settled, gaveUpAt: () => clock };
+ };
+
+ it('disarms mid-wait when nothing the app declared is still open, so the cap decides', async () => {
+ const run = windowShownMidWait(BOOT_ONLY_SEED);
+ await expect(run.settled).rejects.toThrow(/kept logging boot activity/);
+ expect(run.gaveUpAt()).toBeGreaterThan(BOOT_LOG_STALL_MS);
+ });
+
+ it('keeps it armed over that same narration plus one line the app never closed', async () => {
+ const run = windowShownMidWait([
+ ...BOOT_ONLY_SEED,
+ markLine('serverSpawned', 500, '2026-09-04T00:00:00.500Z'),
+ ]);
+ await expect(run.settled).rejects.toThrow(/logged no new boot activity/);
+ expect(run.gaveUpAt()).toBeLessThan(MID_WAIT_CAP_MS);
+ });
+
+ it('blames the open phase it stalled in, not a window it had already shown', async () => {
+ const run = windowShownMidWait([
+ ...BOOT_ONLY_SEED,
+ markLine('serverSpawned', 500, '2026-09-04T00:00:00.500Z'),
+ ]);
+ const message = await run.settled.then(
+ () => 'the wait resolved instead of giving up',
+ (error: unknown) => (error as Error).message,
+ );
+ expect(message).not.toContain('until the first window is shown');
+ expect(message).toContain('while a startup phase it declared is still open');
});
it('reads boot completion off the app mark, not off a mode list', () => {
@@ -1103,6 +1585,25 @@ describe('the recorded ready wait names which wait it measured', () => {
expect(wait?.elapsedMs).toBeGreaterThanOrEqual(50);
});
+ it('carries the deadline the app bought it, beside the cap its caller asked for', async () => {
+ const home = seedHome([
+ JSON.stringify({ event: DESKTOP_BOOT_EVENT, time: '2026-09-04T00:00:00.000Z' }),
+ markLine('serverSpawned', 500, '2026-09-04T00:00:00.500Z'),
+ JSON.stringify({
+ time: '2026-09-04T00:00:05.500Z',
+ event: BOOT_HEARTBEAT_EVENTS.utilityWait,
+ elapsedMs: SPAWN_WAIT_HEARTBEAT_MS,
+ initTimeoutMs: UTILITY_INIT_TIMEOUT_MS,
+ }),
+ ]);
+ const app = slowFirstPoll();
+ rememberLaunchHome(app, home);
+ await waitForWindowByMode(app, 'editor', { pollMs: 20, capMs: 300 });
+ const wait = tryFirstWaitFor(app);
+ expect(wait?.requestedCapMs).toBe(300);
+ expect(wait?.capMs).toBeGreaterThan(300);
+ });
+
it('reports the first wait, not a later re-find of an already-open window', async () => {
const app = slowFirstPoll();
rememberLaunchHome(app, seedHome());
@@ -1321,6 +1822,7 @@ describe('formatBootGapLine', () => {
what: 'editor window',
elapsedMs: 2_100,
capMs: 9_000,
+ requestedCapMs: 9_000,
gaveUp: false,
reason: 'none',
},
@@ -1337,6 +1839,7 @@ describe('formatBootGapLine', () => {
expect(line).toContain('maxGapMs=1600');
expect(line).toContain('firstWaitMs=2100');
expect(line).toContain('firstWaitCapMs=9000');
+ expect(line).toContain('firstWaitRequestedCapMs=9000');
expect(line).not.toContain(`firstWaitCapMs=${BOOT_LOG_CAP_MS}`);
expect(line).toContain('firstWaitWhat="editor window"');
expect(line).toContain('firstWaitGaveUp=false');
@@ -1345,6 +1848,27 @@ describe('formatBootGapLine', () => {
expect(line).toContain('bootComplete=true');
});
+ it('separates the deadline the wait ran to from the one its caller asked for', () => {
+ const line = formatBootGapLine({
+ slot: 0,
+ source: 'wait-snapshot',
+ readyWaitCount: 1,
+ firstWait: {
+ ordinal: 0,
+ what: 'editor window',
+ elapsedMs: 30_100,
+ capMs: 30_000,
+ requestedCapMs: BOOT_LOG_CAP_MS,
+ gaveUp: true,
+ reason: 'cap',
+ },
+ summary: undefined,
+ reason: 'no summary',
+ });
+ expect(line).toContain('firstWaitCapMs=30000');
+ expect(line).toContain(`firstWaitRequestedCapMs=${BOOT_LOG_CAP_MS}`);
+ });
+
it('says why there is no measurement rather than printing a zero', () => {
const line = formatBootGapLine({
slot: 1,
@@ -1357,6 +1881,7 @@ describe('formatBootGapLine', () => {
expect(line).toContain('reason="log dir gone at teardown"');
expect(line).toContain('firstWaitMs=none');
expect(line).toContain('firstWaitCapMs=none');
+ expect(line).toContain('firstWaitRequestedCapMs=none');
expect(line).toContain('firstWaitWhat=none');
expect(line).toContain('firstWaitGaveUp=none');
expect(line).toContain('firstWaitReason=none');
@@ -1383,6 +1908,7 @@ describe('formatBootGapLine', () => {
what: 'editor window',
elapsedMs: 25_000,
capMs: BOOT_LOG_CAP_MS,
+ requestedCapMs: BOOT_LOG_CAP_MS,
gaveUp: reason !== 'none',
reason,
},
diff --git a/packages/desktop/tests/smoke/_helpers/launch-readiness.ts b/packages/desktop/tests/smoke/_helpers/launch-readiness.ts
index 1fc0fbed9..656ded5f0 100644
--- a/packages/desktop/tests/smoke/_helpers/launch-readiness.ts
+++ b/packages/desktop/tests/smoke/_helpers/launch-readiness.ts
@@ -1,10 +1,14 @@
import { readdirSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import {
+ BOOT_HEARTBEAT_EVENTS,
DESKTOP_BOOT_EVENT,
+ DESKTOP_OPEN_PROJECT_FAILED_EVENT,
isBootHeartbeatEvent,
+ isStartupMarkEvent,
SPAWN_WAIT_HEARTBEAT_MS,
startupMarkLine,
+ UTILITY_INIT_TIMEOUT_MS,
} from '../../../src/shared/boot-narration.ts';
export const BOOT_LOG_HEARTBEAT_MS = SPAWN_WAIT_HEARTBEAT_MS;
@@ -138,16 +142,91 @@ function currentLaunch(lines: readonly string[]): string[] {
return lastBoot === -1 ? [...lines] : lines.slice(lastBoot);
}
+function isLaunchNarrationLine(line: string): boolean {
+ const event = parseEvent(line);
+ return event !== undefined && (isStartupMarkEvent(event) || isBootHeartbeatEvent(event));
+}
+
+function lastLaunchNarrationIndex(launch: readonly string[]): number {
+ for (let i = launch.length - 1; i >= 0; i -= 1) {
+ const line = launch[i];
+ if (line !== undefined && isLaunchNarrationLine(line)) return i;
+ }
+ return -1;
+}
+
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);
+ if (end === -1) return launch;
+ return lastLaunchNarrationIndex(launch) > end ? launch : launch.slice(0, end + 1);
}
export function hasBootCompleted(all: readonly string[]): boolean {
return currentLaunch(all).some((line) => parseEvent(line) === BOOT_COMPLETE_EVENT);
}
+const DECLARED_PHASE_OPEN_EVENT = startupMarkLine('serverSpawned', 0).event;
+
+const DECLARED_PHASE_CLOSED_EVENT = startupMarkLine('serverLockReady', 0).event;
+
+function openDeclaredPhaseStart(launch: readonly string[]): number {
+ const openedAt = launch.map(parseEvent).lastIndexOf(DECLARED_PHASE_OPEN_EVENT);
+ if (openedAt === -1) return -1;
+ for (let i = openedAt + 1; i < launch.length; i += 1) {
+ const line = launch[i];
+ if (line === undefined) continue;
+ const event = parseEvent(line);
+ if (event === DECLARED_PHASE_CLOSED_EVENT || event === DESKTOP_OPEN_PROJECT_FAILED_EVENT)
+ return -1;
+ }
+ return openedAt;
+}
+
+export function hasOpenDeclaredPhase(all: readonly string[]): boolean {
+ return openDeclaredPhaseStart(currentLaunch(all)) !== -1;
+}
+
+function isUsableDurationField(value: unknown): value is number {
+ return typeof value === 'number' && Number.isFinite(value);
+}
+
+export interface DeclaredPhaseBudget {
+ elapsedMs: number;
+ initTimeoutMs: number;
+}
+
+export function parseDeclaredPhaseBudget(line: string): DeclaredPhaseBudget | undefined {
+ try {
+ const parsed = JSON.parse(line) as {
+ event?: unknown;
+ elapsedMs?: unknown;
+ initTimeoutMs?: unknown;
+ };
+ if (parsed.event !== BOOT_HEARTBEAT_EVENTS.utilityWait) return undefined;
+ const { elapsedMs, initTimeoutMs } = parsed;
+ if (!isUsableDurationField(elapsedMs) || !isUsableDurationField(initTimeoutMs))
+ return undefined;
+ if (initTimeoutMs > UTILITY_INIT_TIMEOUT_MS) return undefined;
+ if (elapsedMs < 0 || elapsedMs > initTimeoutMs) return undefined;
+ return { elapsedMs, initTimeoutMs };
+ } catch {}
+ return undefined;
+}
+
+function newestDeclaredPhaseBudget(all: readonly string[]): DeclaredPhaseBudget | undefined {
+ const launch = currentLaunch(all);
+ const openedAt = openDeclaredPhaseStart(launch);
+ if (openedAt === -1) return undefined;
+ for (let i = launch.length - 1; i > openedAt; i -= 1) {
+ const line = launch[i];
+ if (line === undefined) continue;
+ const budget = parseDeclaredPhaseBudget(line);
+ if (budget !== undefined) return budget;
+ }
+ return undefined;
+}
+
function parseLastPhase(line: string): string | undefined {
try {
const parsed = JSON.parse(line) as { lastPhase?: unknown };
@@ -308,6 +387,7 @@ export function formatBootGapLine(line: BootGapLine): string {
? [
'firstWaitMs=none',
'firstWaitCapMs=none',
+ 'firstWaitRequestedCapMs=none',
'firstWaitWhat=none',
'firstWaitGaveUp=none',
'firstWaitReason=none',
@@ -315,6 +395,7 @@ export function formatBootGapLine(line: BootGapLine): string {
: [
`firstWaitMs=${line.firstWait.elapsedMs}`,
`firstWaitCapMs=${line.firstWait.capMs}`,
+ `firstWaitRequestedCapMs=${line.firstWait.requestedCapMs}`,
`firstWaitWhat=${JSON.stringify(line.firstWait.what)}`,
`firstWaitGaveUp=${line.firstWait.gaveUp}`,
`firstWaitReason=${line.firstWait.reason}`,
@@ -352,6 +433,7 @@ export interface ReadySignalOptions<T> {
readLog?: (home: string) => BootLogSnapshot;
startDeadline?: (ms: number) => ReadyDeadline;
isProbePending?: () => boolean;
+ onCapExtended?: (capMs: number) => void;
}
export interface ReadyDeadline {
@@ -397,7 +479,7 @@ function describeBootLog(snapshot: BootLogSnapshot): string {
}
function describeFailure(
- reason: 'stalled' | 'cap',
+ reason: 'stalled' | 'stalled-in-declared-phase' | 'cap',
what: string,
elapsedMs: number,
stallMs: number,
@@ -407,17 +489,24 @@ function describeFailure(
): string {
const phase = snapshot.lastEvent ?? '(no boot event recorded)';
const state = classifyBootLog(snapshot);
+ const silence =
+ `${what} did not arrive, and the app logged no new boot activity for ${stallMs}ms ` +
+ `(gave up after ${elapsedMs}ms). `;
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 ` +
+ ? `${silence}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.`
- : probePending
- ? `${what} did not arrive within ${elapsedMs}ms.`
- : `${what} did not arrive within ${elapsedMs}ms, though the app kept logging boot activity.`;
+ : reason === 'stalled-in-declared-phase'
+ ? `${silence}Main beats every ${BOOT_LOG_HEARTBEAT_MS}ms while a startup phase it ` +
+ 'declared is still open, and it had shown a window before this silence, so this ' +
+ `silence after phase ${phase} means the app stopped making progress inside that ` +
+ 'open phase rather than before its first window.'
+ : probePending
+ ? `${what} did not arrive within ${elapsedMs}ms.`
+ : `${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
@@ -481,11 +570,16 @@ export async function waitForReadySignal<T>(options: ReadySignalOptions<T>): Pro
let totalPolls = 0;
let capElapsed = false;
- const deadline = startDeadline(capMs);
- const capReached = deadline.expired.then((): typeof DEADLINE_PASSED => {
- capElapsed = true;
- return DEADLINE_PASSED;
- });
+ const armCapReached = (armed: ReadyDeadline): Promise<typeof DEADLINE_PASSED> =>
+ armed.expired.then((): typeof DEADLINE_PASSED => {
+ capElapsed = true;
+ return DEADLINE_PASSED;
+ });
+ let deadline = startDeadline(capMs);
+ let capReached = armCapReached(deadline);
+ let armedCapMs = capMs;
+ let grantedElapsedMs = Number.NEGATIVE_INFINITY;
+ let derivedDeadlineAt: number | undefined;
let probePendingAtGiveUp = false;
try {
@@ -511,6 +605,30 @@ export async function waitForReadySignal<T>(options: ReadySignalOptions<T>): Pro
lastProgressAt = now();
}
+ const declaredPhaseOpen = hasOpenDeclaredPhase(snapshot.lines);
+ if (declaredPhaseOpen) {
+ const budget = newestDeclaredPhaseBudget(snapshot.lines);
+ if (budget !== undefined && budget.elapsedMs > grantedElapsedMs) {
+ grantedElapsedMs = budget.elapsedMs;
+ const remaining = Math.max(
+ budget.initTimeoutMs - budget.elapsedMs,
+ UTILITY_TIMEOUT_OBSERVATION_MARGIN_MS,
+ );
+ derivedDeadlineAt = Math.max(derivedDeadlineAt ?? 0, now() + remaining);
+ }
+ }
+ const effectiveCapMs =
+ derivedDeadlineAt === undefined ? capMs : Math.max(capMs, derivedDeadlineAt - startedAt);
+ if (effectiveCapMs > armedCapMs) {
+ deadline.cancel();
+ capElapsed = false;
+ probePendingAtGiveUp = false;
+ armedCapMs = effectiveCapMs;
+ options.onCapExtended?.(armedCapMs);
+ deadline = startDeadline(Math.max(startedAt + armedCapMs - now(), 0));
+ capReached = armCapReached(deadline);
+ }
+
const probeError: ProbeErrorSummary | undefined =
lastProbeError === undefined ? undefined : { last: lastProbeError, threwPolls, totalPolls };
const elapsed = now() - startedAt;
@@ -518,11 +636,13 @@ export async function waitForReadySignal<T>(options: ReadySignalOptions<T>): Pro
const stallArmed =
explicitLiveness !== undefined
? explicitLiveness === 'boot'
- : !hasBootCompleted(snapshot.lines);
+ : !hasBootCompleted(snapshot.lines) || declaredPhaseOpen;
if (stallArmed && now() - lastProgressAt >= stallMs) {
throw new ReadySignalGiveUp(
describeFailure(
- 'stalled',
+ declaredPhaseOpen && hasBootCompleted(snapshot.lines)
+ ? 'stalled-in-declared-phase'
+ : 'stalled',
options.what,
elapsed,
stallMs,
@@ -533,7 +653,7 @@ export async function waitForReadySignal<T>(options: ReadySignalOptions<T>): Pro
giveUpReason('stall', snapshot),
);
}
- if (capElapsed || elapsed >= capMs) {
+ if (capElapsed || elapsed >= effectiveCapMs) {
throw new ReadySignalGiveUp(
describeFailure(
'cap',
@@ -593,6 +713,7 @@ export interface ReadyWaitRecord {
what: string;
elapsedMs: number;
capMs: number;
+ requestedCapMs: number;
gaveUp: boolean;
reason: ReadyWaitGiveUpReason;
}
@@ -674,6 +795,7 @@ export async function waitForWindowByMode<TPage extends ModeProbePage>(
const home = options.home ?? launchHomeFor(app);
const what = `${mode} window`;
const capMs = options.capMs ?? BOOT_LOG_CAP_MS;
+ let decidingCapMs = capMs;
const startedAt = Date.now();
const probeStates = new WeakMap<TPage, ModeProbeState>();
let pendingProbeCount = 0;
@@ -688,6 +810,9 @@ export async function waitForWindowByMode<TPage extends ModeProbePage>(
capMs,
...(options.pollMs !== undefined ? { pollMs: options.pollMs } : {}),
isProbePending: () => pendingProbeCount > 0,
+ onCapExtended: (extended) => {
+ decidingCapMs = extended;
+ },
probe: async () => {
const pages = app.windows();
for (const page of pages) {
@@ -754,7 +879,8 @@ export async function waitForWindowByMode<TPage extends ModeProbePage>(
rememberReadyWait(app, {
what,
elapsedMs: Date.now() - startedAt,
- capMs,
+ capMs: decidingCapMs,
+ requestedCapMs: capMs,
gaveUp: !succeeded,
reason,
});