Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Preserve desktop readiness during renderer activity (#5348)
Nick Gomezc1f792abd5c0
diff --git a/packages/desktop/tests/smoke/_helpers/launch-readiness.test.ts b/packages/desktop/tests/smoke/_helpers/launch-readiness.test.tsindex e4cc7af11..e1615cf4c 100644--- a/packages/desktop/tests/smoke/_helpers/launch-readiness.test.ts+++ b/packages/desktop/tests/smoke/_helpers/launch-readiness.test.ts@@ -2234,21 +2234,21 @@ describe('the recorded ready wait names which wait it measured', () => {JSON.stringify({ event: DESKTOP_BOOT_EVENT, time: '2026-09-04T00:00:00.000Z' }),markLine('appReady', 0, '2026-09-04T00:00:00.100Z'),]);- const editor = { evaluate: async () => 'editor' };- let windowsCalls = 0;- const app = {- windows: () => {- windowsCalls += 1;- if (windowsCalls === 2) {+ let modeReads = 0;+ const editor = {+ evaluate: async () => {+ modeReads += 1;+ if (modeReads === 2) {appendFileSync(join(bootLogDirFor(home), 'desktop.2026-09-03.log'),`${markLine('loadUrlResolved', 900, '2026-09-04T00:00:00.900Z')}\n`,'utf8',);}- return windowsCalls >= 3 ? [editor] : [];+ return modeReads >= 3 ? 'editor' : undefined;},};+ const app = { windows: () => [editor] };rememberLaunchHome(app, home);const requestedCapMs = BOOT_LOG_STALL_MS / 2;try {diff --git a/packages/desktop/tests/smoke/_helpers/launch-readiness.ts b/packages/desktop/tests/smoke/_helpers/launch-readiness.tsindex f35ff936a..b242eed2b 100644--- a/packages/desktop/tests/smoke/_helpers/launch-readiness.ts+++ b/packages/desktop/tests/smoke/_helpers/launch-readiness.ts@@ -497,6 +497,7 @@ export function formatBootGapLine(line: BootGapLine): string {'firstWaitAdvancements=none','firstWaitLastAdvancementMs=none','firstWaitSinceAdvancementMs=none',+ 'firstWaitRendererActivityMs=none',]: [`firstWaitMs=${line.firstWait.elapsedMs}`,@@ -510,6 +511,7 @@ export function formatBootGapLine(line: BootGapLine): string {)}`,`firstWaitLastAdvancementMs=${lastAdvancementMs(line.firstWait) ?? 'none'}`,`firstWaitSinceAdvancementMs=${sinceLastAdvancementMs(line.firstWait) ?? 'none'}`,+ `firstWaitRendererActivityMs=${line.firstWait.rendererActivityMs ?? 'none'}`,]),];if (line.summary === undefined) {@@ -531,6 +533,11 @@ export function formatBootGapLine(line: BootGapLine): string {export type ReadyLiveness = 'boot' | 'none';+interface RendererObservation {+ sequence: number;+ receivedAt: number;+}+export interface ReadySignalOptions<T> {probe: () => Promise<T | undefined>;home: string;@@ -547,7 +554,10 @@ export interface ReadySignalOptions<T> {onCapExtended?: (capMs: number) => void;onDeclaredGrant?: (grantMs: number) => void;onAdvancement?: (advancement: LaunchAdvancement) => void;+ onRendererActivity?: (atMs: number) => void;onNewLaunch?: () => void;+ onDeadlineArmed?: (deadlineAt: number) => void;+ latestRendererObservation?: () => RendererObservation | undefined;}export interface ReadyDeadline {@@ -600,6 +610,7 @@ function describeFailure(snapshot: BootLogSnapshot,probeError: ProbeErrorSummary | undefined,probePending: boolean,+ rendererActivityMs: number | undefined,): string {const phase = snapshot.lastEvent ?? '(no boot event recorded)';const state = classifyBootLog(snapshot);@@ -618,10 +629,17 @@ function describeFailure('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+ : probePending || rendererActivityMs !== undefined? `${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)];+ const lines = [+ head,+ `Last main-process boot event: ${phase}`,+ ...(rendererActivityMs === undefined+ ? []+ : [`Last credited Page console activity: ${rendererActivityMs}ms into the wait.`]),+ describeBootLog(snapshot),+ ];lines.push(probeError === undefined? 'Probe errors: none on any poll.'@@ -682,6 +700,8 @@ export async function waitForReadySignal<T>(options: ReadySignalOptions<T>): Prolet launchBootLine: string | undefined;let lastLegibleReadAt: number | undefined;let lastStageRenewalAt: number | undefined;+ let lastRendererRenewalAt: number | undefined;+ let lastRendererSequence = 0;let snapshot = emptyBootLog(bootLogDirFor(options.home));const explicitLiveness = options.liveness;let lastProbeError: string | undefined;@@ -697,6 +717,7 @@ export async function waitForReadySignal<T>(options: ReadySignalOptions<T>): Prolet deadline = startDeadline(capMs);let capReached = armCapReached(deadline);let armedCapMs = capMs;+ options.onDeadlineArmed?.(startedAt + armedCapMs);let grantedBudget: DeclaredPhaseBudget | undefined;let derivedDeadlineAt: number | undefined;let probePendingAtGiveUp = false;@@ -737,6 +758,7 @@ export async function waitForReadySignal<T>(options: ReadySignalOptions<T>): ProadvancementSeen.clear();grantedBudget = undefined;derivedDeadlineAt = undefined;+ lastRendererRenewalAt = undefined;if (armedCapMs !== capMs) {deadline.cancel();capElapsed = false;@@ -744,6 +766,7 @@ export async function waitForReadySignal<T>(options: ReadySignalOptions<T>): ProarmedCapMs = capMs;deadline = startDeadline(Math.max(startedAt + armedCapMs - now(), 0));capReached = armCapReached(deadline);+ options.onDeadlineArmed?.(startedAt + armedCapMs);}options.onNewLaunch?.();}@@ -770,6 +793,19 @@ export async function waitForReadySignal<T>(options: ReadySignalOptions<T>): Prooptions.onDeclaredGrant?.(derivedDeadlineAt - startedAt);}}+ const rendererObservation =+ explicitLiveness === 'none' ? undefined : options.latestRendererObservation?.();+ if (+ rendererObservation !== undefined &&+ rendererObservation.sequence > lastRendererSequence &&+ rendererObservation.receivedAt >= startedAt &&+ rendererObservation.receivedAt <= startedAt + armedCapMs+ ) {+ lastRendererSequence = rendererObservation.sequence;+ lastRendererRenewalAt = rendererObservation.receivedAt;+ lastProgressAt = Math.max(lastProgressAt, rendererObservation.receivedAt);+ options.onRendererActivity?.(lastRendererRenewalAt - startedAt);+ }const effectiveCapMs = Math.min(readinessWorstCaseMs({ path: 'fork', capMs, stallMs }),Math.max(@@ -781,6 +817,16 @@ export async function waitForReadySignal<T>(options: ReadySignalOptions<T>): ProlastStageRenewalAt - startedAt + stallMs,readinessWorstCaseMs({ path: 'packaged', capMs, stallMs }),),+ lastRendererRenewalAt === undefined+ ? capMs+ : Math.min(+ lastRendererRenewalAt - startedAt + stallMs,+ readinessWorstCaseMs({+ path: grantedBudget === undefined ? 'packaged' : 'fork',+ capMs,+ stallMs,+ }),+ ),),);if (effectiveCapMs > armedCapMs) {@@ -791,10 +837,13 @@ export async function waitForReadySignal<T>(options: ReadySignalOptions<T>): Prooptions.onCapExtended?.(armedCapMs);deadline = startDeadline(Math.max(startedAt + armedCapMs - now(), 0));capReached = armCapReached(deadline);+ options.onDeadlineArmed?.(startedAt + armedCapMs);}const probeError: ProbeErrorSummary | undefined =lastProbeError === undefined ? undefined : { last: lastProbeError, threwPolls, totalPolls };+ const rendererActivityMs =+ lastRendererRenewalAt === undefined ? undefined : lastRendererRenewalAt - startedAt;const elapsed = now() - startedAt;const probePending = probePendingAtGiveUp || options.isProbePending?.() === true;const stallArmed =@@ -813,6 +862,7 @@ export async function waitForReadySignal<T>(options: ReadySignalOptions<T>): Prosnapshot,probeError,probePending,+ rendererActivityMs,),giveUpReason('stall', snapshot),);@@ -827,6 +877,7 @@ export async function waitForReadySignal<T>(options: ReadySignalOptions<T>): Prosnapshot,probeError,probePending,+ rendererActivityMs,),giveUpReason('cap', snapshot),);@@ -840,10 +891,21 @@ export async function waitForReadySignal<T>(options: ReadySignalOptions<T>): Proexport type WindowMode = 'editor' | 'navigator' | 'terminal' | 'note';-interface ModeProbePage {+interface ModeProbePageCore {evaluate(fn: () => string | undefined): Promise<string | undefined>;}+interface ConsoleObservingPage extends ModeProbePageCore {+ on(event: 'console', listener: () => void): unknown;+ off(event: 'console', listener: () => void): unknown;+}++type ModeProbePage = ConsoleObservingPage | (ModeProbePageCore & { on?: never; off?: never });++function observesConsole(page: ModeProbePage): page is ConsoleObservingPage {+ return typeof page.on === 'function';+}+interface ModeProbeApp<TPage> {windows(): TPage[];}@@ -855,6 +917,9 @@ type ModeProbeResult =interface ModeProbeState {pending: boolean;result: ModeProbeResult | undefined;+ lastMode: string | undefined;+ observation: RendererObservation | undefined;+ detachConsole: (() => void) | undefined;}const HOME_BY_APP = new WeakMap<object, string>();@@ -878,6 +943,7 @@ export interface ReadyWaitRecord {elapsedMs: number;capMs: number;declaredGrantMs?: number;+ rendererActivityMs?: number;requestedCapMs: number;gaveUp: boolean;reason: ReadyWaitGiveUpReason;@@ -963,12 +1029,23 @@ export async function waitForWindowByMode<TPage extends ModeProbePage>(const capMs = options.capMs ?? BOOT_LOG_CAP_MS;let decidingCapMs = capMs;let declaredGrantMs: number | undefined;+ let rendererActivityMs: number | undefined;const startedAt = Date.now();- const probeStates = new WeakMap<TPage, ModeProbeState>();+ const probeStates = new Map<TPage, ModeProbeState>();+ let rendererSequence = 0;+ let rendererDeadlineAt = -Infinity;let pendingProbeCount = 0;let succeeded = false;let reason: ReadyWaitGiveUpReason = 'none';const advancements: LaunchAdvancement[] = [];+ const removeMissingPages = (pages: readonly TPage[]) => {+ const present = new Set(pages);+ for (const [page, state] of probeStates) {+ if (present.has(page)) continue;+ state.detachConsole?.();+ probeStates.delete(page);+ }+ };try {const found = await waitForReadySignal<TPage>({home,@@ -981,23 +1058,66 @@ export async function waitForWindowByMode<TPage extends ModeProbePage>(onCapExtended: (extended) => {decidingCapMs = extended;},+ onDeadlineArmed: (deadlineAt) => {+ rendererDeadlineAt = deadlineAt;+ },onDeclaredGrant: (grantMs) => {declaredGrantMs = grantMs;},onAdvancement: (advancement) => {advancements.push(advancement);},+ onRendererActivity: (atMs) => {+ rendererActivityMs = atMs;+ },onNewLaunch: () => {advancements.length = 0;declaredGrantMs = undefined;+ rendererActivityMs = undefined;decidingCapMs = capMs;+ for (const state of probeStates.values()) state.observation = undefined;+ },+ latestRendererObservation: () => {+ removeMissingPages(app.windows());+ let latest: RendererObservation | undefined;+ for (const state of probeStates.values()) {+ if (state.lastMode !== undefined && state.lastMode !== mode) continue;+ if (+ state.observation !== undefined &&+ (latest === undefined || state.observation.sequence > latest.sequence)+ ) {+ latest = state.observation;+ }+ }+ return latest;},probe: async () => {const pages = app.windows();+ removeMissingPages(pages);for (const page of pages) {let state = probeStates.get(page);if (state === undefined) {- state = { pending: false, result: undefined };+ state = {+ pending: false,+ result: undefined,+ lastMode: undefined,+ observation: undefined,+ detachConsole: undefined,+ };+ if (options.liveness !== 'none' && observesConsole(page)) {+ const observedState = state;+ const listener = () => {+ const receivedAt = Date.now();+ if (receivedAt > rendererDeadlineAt) return;+ rendererSequence += 1;+ observedState.observation = {+ sequence: rendererSequence,+ receivedAt,+ };+ };+ page.on('console', listener);+ state.detachConsole = () => page.off('console', listener);+ }probeStates.set(page, state);}if (state.pending || state.result !== undefined) continue;@@ -1008,6 +1128,7 @@ export async function waitForWindowByMode<TPage extends ModeProbePage>((value) => {state.pending = false;pendingProbeCount -= 1;+ if (value !== undefined) state.lastMode = value;state.result = { kind: 'mode', value };},(error: unknown) => {@@ -1054,12 +1175,14 @@ export async function waitForWindowByMode<TPage extends ModeProbePage>(if (error instanceof ReadySignalGiveUp) reason = error.reason;throw error;} finally {+ for (const state of probeStates.values()) state.detachConsole?.();rememberBootLog(app, readBootLogLines(home));rememberReadyWait(app, {what,elapsedMs: Date.now() - startedAt,capMs: decidingCapMs,...(declaredGrantMs === undefined ? {} : { declaredGrantMs }),+ ...(rendererActivityMs === undefined ? {} : { rendererActivityMs }),requestedCapMs: capMs,gaveUp: !succeeded,reason,diff --git a/packages/desktop/tests/smoke/_helpers/renderer-leg-liveness.test.ts b/packages/desktop/tests/smoke/_helpers/renderer-leg-liveness.test.tsnew file mode 100644index 000000000..bcb4ced51--- /dev/null+++ b/packages/desktop/tests/smoke/_helpers/renderer-leg-liveness.test.ts@@ -0,0 +1,758 @@+import { EventEmitter } from 'node:events';+import { appendFileSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, describe, expect, it, vi } from 'vitest';+import {+ BOOT_HEARTBEAT_EVENTS,+ DESKTOP_BOOT_EVENT,+ startupMarkLine,+} from '../../../src/shared/boot-narration.ts';+import {+ BOOT_LOG_CAP_MS,+ BOOT_LOG_HEARTBEAT_MS,+ BOOT_LOG_POLL_MS,+ BOOT_LOG_STALL_MS,+ bootGapLineFor,+ bootLogDirFor,+ bootNarrationFor,+ DECLARED_UTILITY_BUDGET_CEILING_MS,+ formatBootGapLine,+ readBootLog,+ readinessWorstCaseMs,+ readyWaitsFor,+ tryBootLogFor,+ tryFirstWaitFor,+ UTILITY_TIMEOUT_OBSERVATION_MARGIN_MS,+ type WaitForWindowOptions,+ waitForWindowByMode,+} from './launch-readiness.ts';++const homes: string[] = [];++class ConsolePage extends EventEmitter {+ mode = Promise.withResolvers<string | undefined>();+ evaluateCalls = 0;++ evaluate(): Promise<string | undefined> {+ this.evaluateCalls += 1;+ return this.mode.promise;+ }++ reportActivity(): void {+ this.emit('console', { type: () => 'log', text: () => 'renderer active' });+ }++ resetMode(): void {+ this.mode = Promise.withResolvers<string | undefined>();+ }+}++afterEach(() => {+ vi.useRealTimers();+ for (const home of homes.splice(0)) rmSync(home, { recursive: true, force: true });+});++const stageAt = BOOT_LOG_CAP_MS - BOOT_LOG_STALL_MS / 2;+const firstRendererEventAt = stageAt + BOOT_LOG_STALL_MS - BOOT_LOG_POLL_MS;+const lateModeAnswerAt = stageAt + BOOT_LOG_STALL_MS + BOOT_LOG_HEARTBEAT_MS;+const startupMarkAt = { appReady: BOOT_LOG_HEARTBEAT_MS, loadUrlResolved: stageAt } as const;++function launchFixture(+ marks: readonly (keyof typeof startupMarkAt)[] = ['appReady', 'loadUrlResolved'],+) {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-10-01T00:00:00.000Z'));+ const home = mkdtempSync(join(tmpdir(), 'ok-renderer-liveness-'));+ homes.push(home);+ mkdirSync(bootLogDirFor(home), { recursive: true });+ const log = join(bootLogDirFor(home), 'desktop.renderer-leg.log');+ const write = (fields: Record<string, unknown>) =>+ appendFileSync(log, `${JSON.stringify({ time: new Date().toISOString(), ...fields })}\n`);+ const at = (when: number, action: () => void) => setTimeout(action, when);+ write({ event: DESKTOP_BOOT_EVENT });+ for (const mark of marks) {+ at(startupMarkAt[mark], () => write(startupMarkLine(mark, startupMarkAt[mark])));+ }++ let pages: { evaluate(): Promise<string | undefined> }[] = [];+ const app = { windows: () => pages };+ const setPages = (next: typeof pages) => {+ pages = next;+ };+ const wait = (options: Omit<WaitForWindowOptions, 'home'> = {}) =>+ waitForWindowByMode(app, 'editor', { home, ...options }).then(+ (page) => ({ kind: 'ready' as const, page }),+ (error: Error) => ({ kind: 'gave-up' as const, message: error.message }),+ );+ const lastWait = () => readyWaitsFor(app)?.at(-1);+ return { app, at, home, lastWait, setPages, wait, write };+}++type LaunchFixture = ReturnType<typeof launchFixture>;++function gaveUpLines(outcome: Awaited<ReturnType<LaunchFixture['wait']>>): string[] {+ return outcome.kind === 'gave-up' ? outcome.message.split('\n') : [];+}++function triageTokensOf(fixture: LaunchFixture): string[] {+ const firstWait = tryFirstWaitFor(fixture.app);+ return formatBootGapLine(+ bootGapLineFor({+ slot: 0,+ narration: bootNarrationFor(tryBootLogFor(fixture.app), readBootLog(fixture.home)),+ readyWaitCount: readyWaitsFor(fixture.app)?.length ?? 0,+ ...(firstWait === undefined ? {} : { firstWait }),+ homeShared: false,+ }),+ ).split(' ');+}++const utilityGrantAt = BOOT_LOG_HEARTBEAT_MS + BOOT_LOG_POLL_MS * 2;++function scheduleClosedUtilityGrant(fixture: ReturnType<typeof launchFixture>): void {+ fixture.at(BOOT_LOG_HEARTBEAT_MS, () =>+ fixture.write(startupMarkLine('serverSpawned', BOOT_LOG_HEARTBEAT_MS)),+ );+ fixture.at(utilityGrantAt, () =>+ fixture.write({+ event: BOOT_HEARTBEAT_EVENTS.utilityWait,+ elapsedMs: 0,+ initTimeoutMs: DECLARED_UTILITY_BUDGET_CEILING_MS,+ }),+ );+ fixture.at(utilityGrantAt + BOOT_LOG_POLL_MS, () =>+ fixture.write(startupMarkLine('serverLockReady', utilityGrantAt + BOOT_LOG_POLL_MS)),+ );+}++function scheduleMainHeartbeat(fixture: ReturnType<typeof launchFixture>, until: number): void {+ for (let at = BOOT_LOG_HEARTBEAT_MS; at < until; at += BOOT_LOG_HEARTBEAT_MS) {+ fixture.at(at, () =>+ fixture.write({+ event: BOOT_HEARTBEAT_EVENTS.boot,+ lastPhase: at >= stageAt ? 'loadUrlResolved' : 'appReady',+ }),+ );+ }+}++describe('renderer activity during first-window readiness', () => {+ it('keeps the pending mode probe alive while the renderer reports activity', async () => {+ const fixture = launchFixture();+ const editor = new ConsolePage();+ scheduleMainHeartbeat(fixture, lateModeAnswerAt);+ fixture.at(stageAt, () => fixture.setPages([editor]));+ fixture.at(firstRendererEventAt, () => editor.reportActivity());+ fixture.at(firstRendererEventAt + BOOT_LOG_POLL_MS * 2, () => editor.reportActivity());+ fixture.at(lateModeAnswerAt, () => editor.mode.resolve('editor'));++ const pending = fixture.wait();+ await vi.runAllTimersAsync();+ expect(await pending).toEqual({ kind: 'ready', page: editor });+ });++ it('gives up on a pending renderer when only main keeps narrating', async () => {+ const fixture = launchFixture();+ scheduleMainHeartbeat(fixture, lateModeAnswerAt);+ fixture.at(stageAt, () => fixture.setPages([new ConsolePage()]));++ const pending = fixture.wait();+ await vi.runAllTimersAsync();+ expect({ outcome: await pending, record: fixture.lastWait() }).toMatchObject({+ outcome: {+ kind: 'gave-up',+ message: expect.stringContaining('The last probe had not answered'),+ },+ record: { gaveUp: true, reason: 'cap' },+ });+ });++ it('diagnoses a launch that stops producing activity', async () => {+ const fixture = launchFixture([]);+ fixture.at(stageAt, () => fixture.setPages([new ConsolePage()]));++ const pending = fixture.wait();+ await vi.runAllTimersAsync();+ expect({ outcome: await pending, record: fixture.lastWait() }).toMatchObject({+ outcome: { kind: 'gave-up', message: expect.stringContaining('no new boot activity') },+ record: { gaveUp: true, reason: 'stall' },+ });+ });++ it('retains the failed page probe in the give-up diagnosis', async () => {+ const fixture = launchFixture();+ scheduleMainHeartbeat(fixture, lateModeAnswerAt);+ for (const at of [firstRendererEventAt, firstRendererEventAt + BOOT_LOG_POLL_MS * 2]) {+ fixture.at(at, () =>+ fixture.write({+ source: 'renderer-console',+ transport: 'electron',+ event: 'ok-terminal-sessions-host-state',+ attached: true,+ }),+ );+ }+ fixture.at(stageAt, () =>+ fixture.setPages([{ evaluate: () => Promise.reject(new Error('Renderer load failed')) }]),+ );++ const pending = fixture.wait();+ await vi.runAllTimersAsync();+ expect(await pending).toMatchObject({+ kind: 'gave-up',+ message: expect.stringContaining('Renderer load failed'),+ });+ });+});++describe('page-owned renderer activity', () => {+ it('keeps a silent boot wait alive until the pending editor mode is known', async () => {+ const fixture = launchFixture();+ const editor = new ConsolePage();+ fixture.setPages([editor]);+ fixture.at(firstRendererEventAt, () => editor.reportActivity());+ fixture.at(lateModeAnswerAt, () => editor.mode.resolve('editor'));++ const pending = fixture.wait();+ await vi.runAllTimersAsync();+ expect(await pending).toEqual({ kind: 'ready', page: editor });+ });++ it('does not borrow activity from a page already identified as another mode', async () => {+ const fixture = launchFixture();+ const navigator = new ConsolePage();+ const editor = new ConsolePage();+ navigator.mode.resolve('navigator');+ editor.mode.resolve('editor');+ fixture.setPages([navigator]);+ fixture.at(firstRendererEventAt, () => navigator.reportActivity());+ fixture.at(firstRendererEventAt + BOOT_LOG_POLL_MS * 2, () => navigator.reportActivity());+ fixture.at(lateModeAnswerAt, () => fixture.setPages([navigator, editor]));++ const pending = fixture.wait();+ await vi.runAllTimersAsync();+ expect(await pending).toMatchObject({ kind: 'gave-up' });+ expect(fixture.lastWait()).toMatchObject({ gaveUp: true, reason: 'stall' });+ });++ it('keeps two unknown Pages distinct when one later reports another mode', async () => {+ const fixture = launchFixture();+ const editor = new ConsolePage();+ const navigator = new ConsolePage();+ fixture.setPages([editor, navigator]);+ fixture.at(firstRendererEventAt - BOOT_LOG_HEARTBEAT_MS, () =>+ navigator.mode.resolve('navigator'),+ );+ fixture.at(firstRendererEventAt - BOOT_LOG_POLL_MS, () => navigator.reportActivity());+ fixture.at(firstRendererEventAt, () => editor.reportActivity());+ fixture.at(lateModeAnswerAt, () => editor.mode.resolve('editor'));++ const pending = fixture.wait();+ await vi.runAllTimersAsync();+ expect(await pending).toEqual({ kind: 'ready', page: editor });+ expect(editor.evaluateCalls).toBe(1);+ });++ it('does not borrow late activity from an initially unknown Page that classified wrong', async () => {+ const fixture = launchFixture();+ const editor = new ConsolePage();+ const navigator = new ConsolePage();+ fixture.setPages([editor, navigator]);+ fixture.at(firstRendererEventAt - BOOT_LOG_HEARTBEAT_MS, () =>+ navigator.mode.resolve('navigator'),+ );+ fixture.at(firstRendererEventAt, () => navigator.reportActivity());+ fixture.at(lateModeAnswerAt, () => editor.mode.resolve('editor'));++ const pending = fixture.wait();+ await vi.runAllTimersAsync();+ expect(await pending).toMatchObject({ kind: 'gave-up' });+ expect(navigator.evaluateCalls).toBeGreaterThan(0);+ expect(editor.evaluateCalls).toBe(1);+ });++ it('uses an activity receipt once, even when the mode probe stays pending', async () => {+ const fixture = launchFixture();+ const editor = new ConsolePage();+ fixture.setPages([editor]);+ fixture.at(stageAt + BOOT_LOG_POLL_MS, () => editor.reportActivity());+ fixture.at(lateModeAnswerAt, () => editor.mode.resolve('editor'));++ const pending = fixture.wait();+ await vi.runAllTimersAsync();+ expect(await pending).toMatchObject({ kind: 'gave-up' });+ expect(editor.evaluateCalls).toBe(1);+ });++ it('keeps the receipt timestamp when the next poll reads the activity later', async () => {+ const fixture = launchFixture();+ const editor = new ConsolePage();+ fixture.setPages([editor]);+ const pollMs = BOOT_LOG_POLL_MS * 7;+ fixture.at(stageAt + BOOT_LOG_POLL_MS / 2, () => editor.reportActivity());+ fixture.at(stageAt + BOOT_LOG_STALL_MS + (BOOT_LOG_POLL_MS * 3) / 4, () =>+ editor.mode.resolve('editor'),+ );++ const pending = fixture.wait({ pollMs });+ await vi.runAllTimersAsync();+ expect(await pending).toMatchObject({ kind: 'gave-up' });+ });++ it('does not revive an expired wait from an after-deadline Page event', async () => {+ const fixture = launchFixture();+ const editor = new ConsolePage();+ fixture.setPages([editor]);+ const pollMs = BOOT_LOG_POLL_MS * 7;+ let settled = false;+ let eventArrivedWhileWaiting = false;+ fixture.at(stageAt + BOOT_LOG_STALL_MS + pollMs / 4, () => {+ eventArrivedWhileWaiting = !settled;+ editor.reportActivity();+ });+ fixture.at(lateModeAnswerAt, () => editor.mode.resolve('editor'));+ const pending = fixture.wait({ pollMs }).then((outcome) => {+ settled = true;+ return outcome;+ });+ await vi.runAllTimersAsync();+ expect(eventArrivedWhileWaiting).toBe(true);+ expect(await pending).toMatchObject({ kind: 'gave-up' });+ });++ it('retains a before-deadline Page receipt when a later event arrives after the deadline', async () => {+ const fixture = launchFixture();+ const editor = new ConsolePage();+ fixture.setPages([editor]);+ scheduleMainHeartbeat(fixture, lateModeAnswerAt);+ fixture.at(firstRendererEventAt, () => editor.reportActivity());+ fixture.at(stageAt + BOOT_LOG_STALL_MS + BOOT_LOG_POLL_MS, () => editor.reportActivity());+ fixture.at(lateModeAnswerAt, () => editor.mode.resolve('editor'));++ const pending = fixture.wait({ pollMs: BOOT_LOG_POLL_MS * 7 });+ await vi.runAllTimersAsync();+ expect(await pending).toEqual({ kind: 'ready', page: editor });+ });++ it('reaches a late editor from Page activity before the initial cap without a later startup stage', async () => {+ const fixture = launchFixture(['appReady']);+ const editor = new ConsolePage();+ fixture.setPages([editor]);+ const modeAnswersAt = BOOT_LOG_CAP_MS + BOOT_LOG_HEARTBEAT_MS;+ for (let at = BOOT_LOG_HEARTBEAT_MS; at < modeAnswersAt; at += BOOT_LOG_HEARTBEAT_MS) {+ fixture.at(at, () =>+ fixture.write({ event: BOOT_HEARTBEAT_EVENTS.boot, lastPhase: 'appReady' }),+ );+ }+ fixture.at(BOOT_LOG_CAP_MS - BOOT_LOG_POLL_MS, () => editor.reportActivity());+ fixture.at(modeAnswersAt, () => editor.mode.resolve('editor'));++ const pending = fixture.wait();+ await vi.runAllTimersAsync();+ expect(await pending).toEqual({ kind: 'ready', page: editor });+ });++ it('keeps the latest eligible Page receipt after a newer donor leaves', async () => {+ const fixture = launchFixture();+ const editor = new ConsolePage();+ const departing = new ConsolePage();+ fixture.setPages([editor, departing]);+ fixture.at(stageAt + BOOT_LOG_POLL_MS, () => editor.reportActivity());+ fixture.at(firstRendererEventAt, () => departing.reportActivity());+ fixture.at(firstRendererEventAt + BOOT_LOG_POLL_MS / 2, () => fixture.setPages([editor]));+ fixture.at(lateModeAnswerAt, () => editor.mode.resolve('editor'));++ const pending = fixture.wait();+ await vi.runAllTimersAsync();+ expect(await pending).toEqual({ kind: 'ready', page: editor });+ });++ it('keeps a known wrong Page excluded after a later undefined mode result', async () => {+ const fixture = launchFixture();+ const navigator = new ConsolePage();+ const editor = new ConsolePage();+ let evaluations = 0;+ navigator.evaluate = async () => {+ evaluations += 1;+ return evaluations === 1 ? 'navigator' : undefined;+ };+ fixture.setPages([navigator, editor]);+ const modeAnswersAt = stageAt + BOOT_LOG_STALL_MS + BOOT_LOG_POLL_MS * 4;+ scheduleMainHeartbeat(fixture, modeAnswersAt);+ fixture.at(firstRendererEventAt, () => navigator.reportActivity());+ fixture.at(modeAnswersAt, () => editor.mode.resolve('editor'));++ const pending = fixture.wait();+ await vi.runAllTimersAsync();+ expect(evaluations).toBeGreaterThan(1);+ expect(editor.evaluateCalls).toBe(1);+ expect(await pending).toMatchObject({ kind: 'gave-up' });+ });+});++describe('renderer observation bounds and lifetime', () => {+ it('ends recurring renderer activity at the packaged backstop without a utility grant', async () => {+ const fixture = launchFixture();+ const editor = new ConsolePage();+ fixture.setPages([editor]);+ const packagedBound = readinessWorstCaseMs({ path: 'packaged' });+ for (let at = BOOT_LOG_HEARTBEAT_MS; at <= packagedBound; at += BOOT_LOG_HEARTBEAT_MS) {+ fixture.at(at, () => editor.reportActivity());+ }++ const pending = fixture.wait();+ await vi.runAllTimersAsync();+ expect(await pending).toMatchObject({ kind: 'gave-up' });+ expect(fixture.lastWait()).toMatchObject({+ gaveUp: true,+ reason: 'cap',+ capMs: packagedBound,+ });+ });++ it('keeps an accepted utility grant within the fork backstop', async () => {+ const fixture = launchFixture();+ const editor = new ConsolePage();+ fixture.setPages([editor]);+ scheduleClosedUtilityGrant(fixture);+ const forkBound = readinessWorstCaseMs({ path: 'fork' });+ for (let at = BOOT_LOG_HEARTBEAT_MS; at <= forkBound; at += BOOT_LOG_HEARTBEAT_MS) {+ fixture.at(at, () => editor.reportActivity());+ }++ const pending = fixture.wait();+ await vi.runAllTimersAsync();+ expect(await pending).toMatchObject({ kind: 'gave-up' });+ const record = fixture.lastWait();+ expect(record?.declaredGrantMs).toBeDefined();+ expect(record).toMatchObject({ gaveUp: true, reason: 'cap' });+ expect(record?.capMs).toBeGreaterThan(readinessWorstCaseMs({ path: 'packaged' }));+ expect(record?.capMs).toBeLessThanOrEqual(forkBound);+ });++ it('uses fresh Page activity to reach an editor after the utility grant expires', async () => {+ const fixture = launchFixture();+ const editor = new ConsolePage();+ fixture.setPages([editor]);+ scheduleClosedUtilityGrant(fixture);+ const grantExpiresAt =+ utilityGrantAt + DECLARED_UTILITY_BUDGET_CEILING_MS + UTILITY_TIMEOUT_OBSERVATION_MARGIN_MS;+ const modeAnswersAt = grantExpiresAt + BOOT_LOG_HEARTBEAT_MS;+ for (let at = BOOT_LOG_HEARTBEAT_MS; at <= modeAnswersAt; at += BOOT_LOG_HEARTBEAT_MS) {+ fixture.at(at, () => editor.reportActivity());+ }+ for (+ let at = utilityGrantAt + BOOT_LOG_HEARTBEAT_MS;+ at <= modeAnswersAt;+ at += BOOT_LOG_HEARTBEAT_MS+ ) {+ fixture.at(at, () =>+ fixture.write({ event: BOOT_HEARTBEAT_EVENTS.boot, lastPhase: 'loadUrlResolved' }),+ );+ }+ fixture.at(grantExpiresAt - BOOT_LOG_POLL_MS * 2, () => editor.reportActivity());+ fixture.at(modeAnswersAt, () => editor.mode.resolve('editor'));++ const pending = fixture.wait();+ await vi.runAllTimersAsync();+ expect(fixture.lastWait()?.declaredGrantMs).toBeDefined();+ expect(await pending).toEqual({ kind: 'ready', page: editor });+ });++ it('does not credit Page activity when liveness is none', async () => {+ const fixture = launchFixture();+ const editor = new ConsolePage();+ fixture.setPages([editor]);+ let listenersDuringWait = -1;+ fixture.at(firstRendererEventAt, () => {+ listenersDuringWait = editor.listenerCount('console');+ editor.reportActivity();+ });+ fixture.at(lateModeAnswerAt, () => editor.mode.resolve('editor'));++ const pending = fixture.wait({ liveness: 'none' });+ await vi.runAllTimersAsync();+ expect(await pending).toMatchObject({ kind: 'gave-up' });+ expect(editor.evaluateCalls).toBe(1);+ expect(listenersDuringWait).toBe(0);+ });++ it('removes Page listeners after success and does not inherit old activity on a later wait', async () => {+ const fixture = launchFixture();+ const editor = new ConsolePage();+ fixture.setPages([editor]);+ let registered = 0;+ fixture.at(BOOT_LOG_POLL_MS * 2, () => {+ registered = editor.listenerCount('console');+ });+ fixture.at(firstRendererEventAt, () => editor.reportActivity());+ fixture.at(lateModeAnswerAt, () => editor.mode.resolve('editor'));++ const first = fixture.wait();+ await vi.runAllTimersAsync();+ expect(await first).toEqual({ kind: 'ready', page: editor });+ expect(registered).toBeGreaterThan(0);+ expect(editor.listenerCount('console')).toBe(0);++ editor.resetMode();+ const second = fixture.wait();+ setTimeout(() => editor.mode.resolve('editor'), BOOT_LOG_CAP_MS + BOOT_LOG_HEARTBEAT_MS);+ await vi.runAllTimersAsync();+ expect(await second).toMatchObject({ kind: 'gave-up' });+ expect(editor.listenerCount('console')).toBe(0);+ });++ it('removes listeners after give-up and after a Page leaves the app', async () => {+ const fixture = launchFixture();+ const removed = new ConsolePage();+ const remaining = new ConsolePage();+ fixture.setPages([removed, remaining]);+ let registered = 0;+ let removedAfterPoll = -1;+ fixture.at(BOOT_LOG_POLL_MS * 2, () => {+ registered = removed.listenerCount('console');+ });+ const removedEventAt = firstRendererEventAt - BOOT_LOG_POLL_MS / 2;+ fixture.at(removedEventAt, () => removed.reportActivity());+ fixture.at(removedEventAt + BOOT_LOG_POLL_MS / 4, () => fixture.setPages([remaining]));+ fixture.at(firstRendererEventAt + BOOT_LOG_POLL_MS / 2, () => {+ removedAfterPoll = removed.listenerCount('console');+ });+ fixture.at(lateModeAnswerAt, () => remaining.mode.resolve('editor'));++ const pending = fixture.wait();+ await vi.runAllTimersAsync();+ expect(await pending).toMatchObject({ kind: 'gave-up' });+ expect(registered).toBeGreaterThan(0);+ expect(removedAfterPoll).toBe(0);+ expect(remaining.listenerCount('console')).toBe(0);+ });++ it('does not credit a Page removed before the cap decision reads its activity', async () => {+ const fixture = launchFixture();+ const removed = new ConsolePage();+ const later = new ConsolePage();+ fixture.setPages([removed]);+ const modeAnswersAt = stageAt + BOOT_LOG_STALL_MS + BOOT_LOG_POLL_MS * 20;+ scheduleMainHeartbeat(fixture, modeAnswersAt);+ let settled = false;+ let listenerAtEvent = 0;+ let removedWhileWaiting = false;+ fixture.at(firstRendererEventAt, () => {+ listenerAtEvent = removed.listenerCount('console');+ removed.reportActivity();+ });+ fixture.at(firstRendererEventAt + BOOT_LOG_POLL_MS / 2, () => {+ removedWhileWaiting = !settled;+ fixture.setPages([]);+ });+ fixture.at(stageAt + BOOT_LOG_STALL_MS + BOOT_LOG_POLL_MS * 6, () => fixture.setPages([later]));+ fixture.at(modeAnswersAt, () => later.mode.resolve('editor'));++ const pending = fixture.wait({ pollMs: BOOT_LOG_POLL_MS * 7 }).then((outcome) => {+ settled = true;+ return outcome;+ });+ await vi.runAllTimersAsync();+ expect(listenerAtEvent).toBeGreaterThan(0);+ expect(removedWhileWaiting).toBe(true);+ expect(await pending).toMatchObject({ kind: 'gave-up' });+ expect(removed.listenerCount('console')).toBe(0);+ });++ it('does not credit a Page classified wrong before the cap decision reads its activity', async () => {+ const fixture = launchFixture();+ const navigator = new ConsolePage();+ const later = new ConsolePage();+ fixture.setPages([navigator]);+ const modeAnswersAt = stageAt + BOOT_LOG_STALL_MS + BOOT_LOG_POLL_MS * 20;+ scheduleMainHeartbeat(fixture, modeAnswersAt);+ let settled = false;+ let listenerAtEvent = 0;+ let classifiedWhileWaiting = false;+ fixture.at(firstRendererEventAt, () => {+ listenerAtEvent = navigator.listenerCount('console');+ navigator.reportActivity();+ });+ fixture.at(firstRendererEventAt + BOOT_LOG_POLL_MS / 2, () => {+ classifiedWhileWaiting = !settled;+ navigator.mode.resolve('navigator');+ });+ fixture.at(stageAt + BOOT_LOG_STALL_MS + BOOT_LOG_POLL_MS * 6, () =>+ fixture.setPages([navigator, later]),+ );+ fixture.at(modeAnswersAt, () => later.mode.resolve('editor'));++ const pending = fixture.wait({ pollMs: BOOT_LOG_POLL_MS * 7 }).then((outcome) => {+ settled = true;+ return outcome;+ });+ await vi.runAllTimersAsync();+ expect(listenerAtEvent).toBeGreaterThan(0);+ expect(classifiedWhileWaiting).toBe(true);+ expect(navigator.evaluateCalls).toBeGreaterThan(0);+ expect(await pending).toMatchObject({ kind: 'gave-up' });+ });++ it('drops old-launch credit without starting another evaluation on a pending Page', async () => {+ const fixture = launchFixture();+ const editor = new ConsolePage();+ fixture.setPages([editor]);+ let registered = 0;+ fixture.at(BOOT_LOG_POLL_MS * 2, () => {+ registered = editor.listenerCount('console');+ });+ fixture.at(firstRendererEventAt, () => editor.reportActivity());+ fixture.at(firstRendererEventAt + BOOT_LOG_POLL_MS, () =>+ fixture.write({ event: DESKTOP_BOOT_EVENT }),+ );+ fixture.at(lateModeAnswerAt, () => editor.mode.resolve('editor'));++ const pending = fixture.wait();+ await vi.runAllTimersAsync();+ expect(await pending).toMatchObject({ kind: 'gave-up' });+ expect(registered).toBeGreaterThan(0);+ expect(editor.evaluateCalls).toBe(1);+ expect(fixture.lastWait()).not.toHaveProperty('rendererActivityMs');+ });++ it('drops Page activity received just before a new launch is first read', async () => {+ const fixture = launchFixture();+ const editor = new ConsolePage();+ fixture.setPages([editor]);+ fixture.at(BOOT_LOG_CAP_MS - BOOT_LOG_POLL_MS / 2, () => editor.reportActivity());+ fixture.at(BOOT_LOG_CAP_MS - BOOT_LOG_POLL_MS / 4, () =>+ fixture.write({ event: DESKTOP_BOOT_EVENT }),+ );+ fixture.at(lateModeAnswerAt, () => editor.mode.resolve('editor'));++ const pending = fixture.wait();+ await vi.runAllTimersAsync();+ expect(await pending).toMatchObject({ kind: 'gave-up' });+ expect(editor.evaluateCalls).toBe(1);+ });++ it('leaves an evaluate-only Page without renderer observation credit', async () => {+ const fixture = launchFixture();+ const mode = Promise.withResolvers<string | undefined>();+ const editor = { evaluate: () => mode.promise };+ fixture.setPages([editor]);+ fixture.at(firstRendererEventAt, () =>+ fixture.write({ source: 'renderer-console', event: 'renderer activity' }),+ );+ fixture.at(lateModeAnswerAt, () => mode.resolve('editor'));++ const pending = fixture.wait();+ await vi.runAllTimersAsync();+ expect(await pending).toMatchObject({ kind: 'gave-up' });+ });+});++describe('renderer activity attribution in the ready-wait record', () => {+ it('records the credited Page receipt when the cap fires with the mode probe pending', async () => {+ const fixture = launchFixture();+ const editor = new ConsolePage();+ fixture.setPages([editor]);+ fixture.at(firstRendererEventAt, () => editor.reportActivity());++ const pending = fixture.wait();+ await vi.runAllTimersAsync();+ const outcome = await pending;+ expect({ outcome, record: fixture.lastWait() }).toMatchObject({+ outcome: {+ kind: 'gave-up',+ message: expect.stringContaining('The last probe had not answered'),+ },+ record: { gaveUp: true, reason: 'cap' },+ });+ expect({+ record: fixture.lastWait(),+ lines: gaveUpLines(outcome),+ triage: triageTokensOf(fixture),+ }).toMatchObject({+ record: { rendererActivityMs: firstRendererEventAt },+ lines: expect.arrayContaining([+ `Last credited Page console activity: ${firstRendererEventAt}ms into the wait.`,+ ]),+ triage: expect.arrayContaining([`firstWaitRendererActivityMs=${firstRendererEventAt}`]),+ });+ });++ it('records the credited Page receipt when the launch stalls after it', async () => {+ const fixture = launchFixture([]);+ const editor = new ConsolePage();+ fixture.setPages([editor]);+ fixture.at(BOOT_LOG_HEARTBEAT_MS, () => editor.reportActivity());++ const pending = fixture.wait();+ await vi.runAllTimersAsync();+ const outcome = await pending;+ expect({ record: fixture.lastWait(), lines: gaveUpLines(outcome) }).toMatchObject({+ record: { gaveUp: true, reason: 'stall', rendererActivityMs: BOOT_LOG_HEARTBEAT_MS },+ lines: expect.arrayContaining([+ `Last credited Page console activity: ${BOOT_LOG_HEARTBEAT_MS}ms into the wait.`,+ ]),+ });+ });++ it('does not credit the boot log for a cap that only Page activity renewed', async () => {+ const fixture = launchFixture();+ const editor = new ConsolePage();+ editor.mode.resolve(undefined);+ fixture.setPages([editor]);+ const packagedBound = readinessWorstCaseMs({ path: 'packaged' });+ let lastActivityAt = 0;+ for (let at = BOOT_LOG_HEARTBEAT_MS; at < packagedBound; at += BOOT_LOG_HEARTBEAT_MS) {+ fixture.at(at, () => editor.reportActivity());+ lastActivityAt = at;+ }++ const pending = fixture.wait();+ await vi.runAllTimersAsync();+ const outcome = await pending;+ expect({ outcome, record: fixture.lastWait() }).toMatchObject({+ outcome: {+ kind: 'gave-up',+ message: expect.not.stringContaining('The last probe had not answered'),+ },+ record: { gaveUp: true, reason: 'cap' },+ });+ expect(editor.evaluateCalls).toBeGreaterThan(1);+ const lines = gaveUpLines(outcome);+ expect({ record: fixture.lastWait(), head: lines[0], lines }).toMatchObject({+ record: { rendererActivityMs: lastActivityAt },+ head: expect.stringMatching(/^editor window did not arrive within \d+ms\.$/),+ lines: expect.arrayContaining([+ `Last credited Page console activity: ${lastActivityAt}ms into the wait.`,+ ]),+ });+ expect(lines.join('\n')).not.toContain('though the app kept logging boot activity');+ });++ it('leaves a wait without credited Page activity unattributed', async () => {+ const fixture = launchFixture();+ const editor = new ConsolePage();+ fixture.setPages([editor]);+ let settled = false;+ let reportedWhileWaiting = false;+ fixture.at(firstRendererEventAt, () => {+ reportedWhileWaiting = !settled;+ editor.reportActivity();+ });++ const pending = fixture.wait({ liveness: 'none' }).then((outcome) => {+ settled = true;+ return outcome;+ });+ await vi.runAllTimersAsync();+ const outcome = await pending;+ expect(reportedWhileWaiting).toBe(true);+ expect({ outcome, record: fixture.lastWait() }).toMatchObject({+ outcome: { kind: 'gave-up', message: expect.not.stringContaining('Page console activity') },+ record: { gaveUp: true, reason: 'cap' },+ });+ expect(fixture.lastWait()).not.toHaveProperty('rendererActivityMs');+ expect(triageTokensOf(fixture)).toContain('firstWaitRendererActivityMs=none');+ });+});