Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Fix two unsound oracles in the terminal restart smoke test (#4920)

Nick Gomez0fef87974099
diff --git a/packages/desktop/tests/smoke/_helpers/rail-column.test.ts b/packages/desktop/tests/smoke/_helpers/rail-column.test.ts
new file mode 100644
index 000000000..f245625b9
--- /dev/null
+++ b/packages/desktop/tests/smoke/_helpers/rail-column.test.ts
@@ -0,0 +1,130 @@
+import { stripVTControlCharacters } from 'node:util';
+import type { Page } from '@playwright/test';
+import { describe, expect, test } from 'vitest';
+import { readRailColumnWidth, waitForCollapsedWidth } from './rail-column';
+
+const COLUMN = '#agents-column';
+const PLAYWRIGHT_INHERITED_EXPECT_TIMEOUT_MS = 5_000;
+const CI_ATTEMPT_ZERO_READ_MS = 5_260;
+const DECLARED_BOUND_MS = 300;
+const UNCOLLAPSED_WIDTH_PX = 320;
+const DESTROYED = 'Execution context was destroyed, most likely because of a navigation';
+
+const answerAfter = <T>(ms: number, value: T): Promise<T> =>
+ new Promise((resolve) => {
+ setTimeout(() => resolve(value), ms);
+ });
+
+const neverAnswers = (): Promise<number> => new Promise<number>(() => {});
+
+async function rejectionOf(run: Promise<unknown>): Promise<string> {
+ return run.then(
+ () => {
+ throw new Error('the settle wait resolved where it had to reject');
+ },
+ (error: unknown) =>
+ stripVTControlCharacters(error instanceof Error ? error.message : String(error)),
+ );
+}
+
+type FakeRailElement = { getBoundingClientRect: () => { width: number } };
+
+function pageMatching(widths: readonly number[]): Page {
+ const elements: FakeRailElement[] = widths.map((width) => ({
+ getBoundingClientRect: () => ({ width }),
+ }));
+ return {
+ locator: () => ({
+ evaluateAll: async (read: (nodes: FakeRailElement[]) => number[]) => read(elements),
+ }),
+ } as unknown as Page;
+}
+
+describe('collapsed rail column settle', () => {
+ test('replays CI attempt 0: a read that answers zero after the inherited expect default still settles the column', async () => {
+ expect(CI_ATTEMPT_ZERO_READ_MS).toBeGreaterThan(PLAYWRIGHT_INHERITED_EXPECT_TIMEOUT_MS);
+ let reads = 0;
+
+ await waitForCollapsedWidth(
+ () => {
+ reads += 1;
+ return answerAfter(CI_ATTEMPT_ZERO_READ_MS, 0);
+ },
+ { column: COLUMN },
+ );
+
+ expect(reads).toBeGreaterThan(0);
+ });
+
+ test('reports a read that never answers inside the declared bound as no reading, naming the column and the bound', async () => {
+ const message = await rejectionOf(
+ waitForCollapsedWidth(neverAnswers, { column: COLUMN, timeout: DECLARED_BOUND_MS }),
+ );
+
+ expect(message).toContain(COLUMN);
+ expect(message).toMatch(new RegExp(`\\b${DECLARED_BOUND_MS} ms\\b`, 'u'));
+ expect(message).toMatch(/no width reading completed/u);
+ expect(message).not.toMatch(/Received/u);
+ });
+
+ test('reports a column that answered a non-zero width as that width, never as a missing reading', async () => {
+ const message = await rejectionOf(
+ waitForCollapsedWidth(() => Promise.resolve(UNCOLLAPSED_WIDTH_PX), {
+ column: COLUMN,
+ timeout: DECLARED_BOUND_MS,
+ }),
+ );
+
+ expect(message).toMatch(new RegExp(`\\b${UNCOLLAPSED_WIDTH_PX}\\b`, 'u'));
+ expect(message).not.toMatch(/no width reading completed/u);
+ });
+
+ test('settles once the column reaches zero after wider readings', async () => {
+ const widths = [UNCOLLAPSED_WIDTH_PX, UNCOLLAPSED_WIDTH_PX, 0];
+ let reads = 0;
+
+ await waitForCollapsedWidth(
+ () => {
+ const width = widths[Math.min(reads, widths.length - 1)] ?? 0;
+ reads += 1;
+ return Promise.resolve(width);
+ },
+ { column: COLUMN },
+ );
+
+ expect(reads).toBeGreaterThanOrEqual(widths.length);
+ });
+
+ test('surfaces a read that keeps failing as the read failure, never as a width', async () => {
+ const message = await rejectionOf(
+ waitForCollapsedWidth(() => Promise.reject(new Error(DESTROYED)), {
+ column: COLUMN,
+ timeout: DECLARED_BOUND_MS,
+ }),
+ );
+
+ expect(message).toContain(DESTROYED);
+ expect(message).not.toMatch(/Received/u);
+ });
+});
+describe('rail column cardinality', () => {
+ test('reads the width when exactly one element matches', async () => {
+ await expect(readRailColumnWidth(pageMatching([UNCOLLAPSED_WIDTH_PX]), COLUMN)).resolves.toBe(
+ UNCOLLAPSED_WIDTH_PX,
+ );
+ });
+
+ test('refuses a selector that matches no element, naming the selector and the count', async () => {
+ const message = await rejectionOf(readRailColumnWidth(pageMatching([]), COLUMN));
+
+ expect(message).toContain(COLUMN);
+ expect(message).toMatch(/found 0\b/u);
+ });
+
+ test('refuses a selector that matches more than one collapsed element, naming the selector and the count', async () => {
+ const message = await rejectionOf(readRailColumnWidth(pageMatching([0, 0]), COLUMN));
+
+ expect(message).toContain(COLUMN);
+ expect(message).toMatch(/found 2\b/u);
+ });
+});
diff --git a/packages/desktop/tests/smoke/_helpers/rail-column.ts b/packages/desktop/tests/smoke/_helpers/rail-column.ts
new file mode 100644
index 000000000..0a28cefc0
--- /dev/null
+++ b/packages/desktop/tests/smoke/_helpers/rail-column.ts
@@ -0,0 +1,47 @@
+import { expect, type Page } from '@playwright/test';
+import {
+ expectSettledReading,
+ RAIL_LAYOUT_SETTLE_TIMEOUT_MS,
+ type SettleBudget,
+} from './settled-reading';
+
+export type RailSettleBound =
+ | { timeout?: number; budget?: undefined }
+ | { budget: SettleBudget; timeout?: undefined };
+
+export type CollapsedWidthOptions = { column: string } & RailSettleBound;
+
+export async function waitForCollapsedWidth(
+ readWidth: () => Promise<number>,
+ { column, timeout = RAIL_LAYOUT_SETTLE_TIMEOUT_MS, budget }: CollapsedWidthOptions,
+): Promise<void> {
+ await expectSettledReading(
+ readWidth,
+ (width) => expect(width).toBe(0),
+ budget === undefined
+ ? { reading: 'width', of: column, timeout }
+ : { reading: 'width', of: column, budget },
+ );
+}
+
+export async function readRailColumnWidth(page: Page, selector: string): Promise<number> {
+ const widths = await page
+ .locator(selector)
+ .evaluateAll((elements) => elements.map((element) => element.getBoundingClientRect().width));
+ const [width] = widths;
+ if (widths.length !== 1 || width === undefined) {
+ throw new Error(`expected exactly one ${selector}, found ${widths.length}`);
+ }
+ return width;
+}
+
+export async function expectCollapsedRailColumn(
+ page: Page,
+ selector: string,
+ bound: RailSettleBound = {},
+): Promise<void> {
+ await waitForCollapsedWidth(() => readRailColumnWidth(page, selector), {
+ column: selector,
+ ...bound,
+ });
+}
diff --git a/packages/desktop/tests/smoke/_helpers/settled-reading.test.ts b/packages/desktop/tests/smoke/_helpers/settled-reading.test.ts
new file mode 100644
index 000000000..181f90f70
--- /dev/null
+++ b/packages/desktop/tests/smoke/_helpers/settled-reading.test.ts
@@ -0,0 +1,210 @@
+import { stripVTControlCharacters } from 'node:util';
+import { expect as playwrightExpect } from '@playwright/test';
+import { describe, expect, test } from 'vitest';
+import { waitForCollapsedWidth } from './rail-column';
+import { expectSettledReading, settleBudget } from './settled-reading';
+
+const LABEL = 'rail admission after the window narrows to 900 px';
+const TOTAL_MS = 10_000;
+const CLOCK_ORIGIN_MS = 50_000;
+const COLUMN = '#agents-column';
+const UNCOLLAPSED_WIDTH_PX = 320;
+const LIVENESS_BOUND_MS = 500;
+const REMAINING_MS = 300;
+const DESTROYED = 'Execution context was destroyed, most likely because of a navigation';
+
+function budgetOnClock(timeout: number) {
+ const clock = { now: CLOCK_ORIGIN_MS };
+ const budget = settleBudget(LABEL, { timeout, now: () => clock.now });
+ return {
+ budget,
+ advance(ms: number): void {
+ clock.now += ms;
+ },
+ };
+}
+
+async function outcomeWithinLiveness(
+ start: (raceOver: () => boolean) => Promise<unknown>,
+): Promise<string> {
+ let over = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const outcome = await Promise.race([
+ start(() => over).then(
+ () => 'resolved',
+ (error: unknown) =>
+ stripVTControlCharacters(error instanceof Error ? error.message : String(error)),
+ ),
+ new Promise<string>((resolve) => {
+ timer = setTimeout(() => resolve('still waiting'), LIVENESS_BOUND_MS);
+ }),
+ ]);
+ over = true;
+ clearTimeout(timer);
+ return outcome;
+}
+
+const uncollapsedUntil = (raceOver: () => boolean) => (): Promise<number> =>
+ raceOver()
+ ? Promise.reject(new Error('the liveness race is over'))
+ : Promise.resolve(UNCOLLAPSED_WIDTH_PX);
+
+const neverAnswers = (): Promise<number> => new Promise<number>(() => {});
+
+async function rejectionOf(run: Promise<unknown>): Promise<string> {
+ return run.then(
+ () => {
+ throw new Error('the settled reading resolved where it had to reject');
+ },
+ (error: unknown) =>
+ stripVTControlCharacters(error instanceof Error ? error.message : String(error)),
+ );
+}
+
+function budgetWithRemainder() {
+ const { budget, advance } = budgetOnClock(TOTAL_MS);
+ advance(TOTAL_MS - REMAINING_MS);
+ return budget;
+}
+
+describe('settle budget shared by the waits on one layout transition', () => {
+ test('spends the time elapsed on its clock from the remaining budget', () => {
+ const { budget, advance } = budgetOnClock(TOTAL_MS);
+
+ expect(budget.remainingMs()).toBe(TOTAL_MS);
+ advance(4_000);
+ expect(budget.remainingMs()).toBe(TOTAL_MS - 4_000);
+ advance(5_000);
+ expect(budget.remainingMs()).toBe(TOTAL_MS - 9_000);
+ });
+
+ test.each([
+ ['exactly spent', TOTAL_MS],
+ ['overspent', TOTAL_MS + 1],
+ ])(
+ 'throws naming the label and the total once %s, instead of handing out a remainder Playwright would misread',
+ (_label, elapsedMs) => {
+ const { budget, advance } = budgetOnClock(TOTAL_MS);
+
+ advance(elapsedMs);
+
+ expect(() => budget.remainingMs()).toThrow(LABEL);
+ expect(() => budget.remainingMs()).toThrow(new RegExp(`\\b${TOTAL_MS} ms\\b`, 'u'));
+ },
+ );
+
+ test.each([
+ ['a zero total', 0],
+ ['a negative total', -1],
+ ['a NaN total', Number.NaN],
+ ['an infinite total', Number.POSITIVE_INFINITY],
+ ])('refuses %s by naming the positive-bound contract', (_label, total) => {
+ expect(() => budgetOnClock(total)).toThrow(/positive/u);
+ });
+});
+
+describe('declared bound of a settled reading', () => {
+ const entryPoints = [
+ [
+ 'expectSettledReading',
+ (raceOver: () => boolean, timeout: number) =>
+ expectSettledReading(uncollapsedUntil(raceOver), (width) => expect(width).toBe(0), {
+ reading: 'width',
+ of: COLUMN,
+ timeout,
+ }),
+ ],
+ [
+ 'waitForCollapsedWidth',
+ (raceOver: () => boolean, timeout: number) =>
+ waitForCollapsedWidth(uncollapsedUntil(raceOver), { column: COLUMN, timeout }),
+ ],
+ ] as const;
+ const bounds = [
+ ['a zero bound', 0],
+ ['a NaN bound', Number.NaN],
+ ['a negative bound', -1],
+ ] as const;
+
+ test.each(
+ entryPoints.flatMap(([entry, wait]) =>
+ bounds.map(([bound, timeout]) => [entry, bound, wait, timeout] as const),
+ ),
+ )(
+ '%s rejects %s promptly by naming the positive-bound contract',
+ async (_entry, _bound, wait, timeout) => {
+ const outcome = await outcomeWithinLiveness((raceOver) => wait(raceOver, timeout));
+
+ expect(outcome).toMatch(/positive/u);
+ },
+ );
+});
+
+describe('settled reading bounded by a shared settle budget', () => {
+ const entryPoints = [
+ [
+ 'expectSettledReading',
+ (read: () => Promise<number>) =>
+ expectSettledReading(read, (width) => playwrightExpect(width).toBe(0), {
+ reading: 'width',
+ of: COLUMN,
+ budget: budgetWithRemainder(),
+ }),
+ ],
+ [
+ 'waitForCollapsedWidth',
+ (read: () => Promise<number>) =>
+ waitForCollapsedWidth(read, { column: COLUMN, budget: budgetWithRemainder() }),
+ ],
+ ] as const;
+ const failingReads = [
+ ['rejects', (): Promise<number> => Promise.reject(new Error(DESTROYED))],
+ [
+ 'throws before it returns a promise',
+ (): Promise<number> => {
+ throw new Error(DESTROYED);
+ },
+ ],
+ ] as const;
+
+ test.each(entryPoints)(
+ '%s reports a read that never answers as no reading within the time the budget has left, naming its label and total',
+ async (_entry, wait) => {
+ const message = await rejectionOf(wait(neverAnswers));
+
+ expect(message).toMatch(/no width reading completed/u);
+ expect(message).toContain(LABEL);
+ expect(message).toMatch(new RegExp(`\\b${REMAINING_MS} ms\\b`, 'u'));
+ expect(message).toMatch(new RegExp(`\\b${TOTAL_MS} ms\\b`, 'u'));
+ },
+ );
+
+ test.each(entryPoints)(
+ '%s reports a width that never settles within the time the budget has left and keeps its Expected/Received reason',
+ async (_entry, wait) => {
+ const message = await rejectionOf(wait(() => Promise.resolve(UNCOLLAPSED_WIDTH_PX)));
+
+ expect(message).toMatch(/never settled/u);
+ expect(message).toContain(COLUMN);
+ expect(message).toContain(LABEL);
+ expect(message).toMatch(new RegExp(`\\b${REMAINING_MS} ms\\b`, 'u'));
+ expect(message).toMatch(new RegExp(`\\b${TOTAL_MS} ms\\b`, 'u'));
+ expect(message).toMatch(/Expected: 0\b/u);
+ expect(message).toMatch(new RegExp(`Received: ${UNCOLLAPSED_WIDTH_PX}\\b`, 'u'));
+ },
+ );
+
+ test.each(
+ entryPoints.flatMap(([entry, wait]) =>
+ failingReads.map(([how, read]) => [entry, how, wait, read] as const),
+ ),
+ )(
+ '%s surfaces a read that %s as that failure, never as a missing or unsettled reading',
+ async (_entry, _how, wait, read) => {
+ const message = await rejectionOf(wait(read));
+
+ expect(message).toContain(DESTROYED);
+ expect(message).not.toMatch(/no width reading completed|never settled|Received/u);
+ },
+ );
+});
diff --git a/packages/desktop/tests/smoke/_helpers/settled-reading.ts b/packages/desktop/tests/smoke/_helpers/settled-reading.ts
new file mode 100644
index 000000000..72cb571b9
--- /dev/null
+++ b/packages/desktop/tests/smoke/_helpers/settled-reading.ts
@@ -0,0 +1,101 @@
+import { expect } from '@playwright/test';
+
+export const RAIL_LAYOUT_SETTLE_TIMEOUT_MS = 10_000;
+
+export interface SettleBudget {
+ readonly label: string;
+ readonly totalMs: number;
+ remainingMs(): number;
+}
+
+export interface SettleBudgetOptions {
+ timeout: number;
+ now?: () => number;
+}
+
+export function requirePositiveTimeout(owner: string, timeout: number): void {
+ if (!(timeout > 0) || !Number.isFinite(timeout)) {
+ throw new Error(
+ `${owner} needs a positive, finite timeout; received ${timeout}. ` +
+ 'Playwright reads 0 and NaN as no deadline.',
+ );
+ }
+}
+
+export function settleBudget(
+ label: string,
+ { timeout, now = () => performance.now() }: SettleBudgetOptions,
+): SettleBudget {
+ requirePositiveTimeout(`settle budget "${label}"`, timeout);
+ const startedAt = now();
+ return {
+ label,
+ totalMs: timeout,
+ remainingMs() {
+ const remaining = timeout - (now() - startedAt);
+ if (!(remaining > 0)) {
+ throw new Error(
+ `settle budget "${label}" spent its ${timeout} ms before the next wait on it began`,
+ );
+ }
+ return remaining;
+ },
+ };
+}
+
+export type SettleBound =
+ | { timeout: number; budget?: undefined }
+ | { budget: SettleBudget; timeout?: undefined };
+
+export type SettledReadingOptions = { reading: string; of: string } & SettleBound;
+
+type SettleAttempt =
+ | { readonly kind: 'none' }
+ | { readonly kind: 'read' }
+ | { readonly kind: 'read-failed'; readonly error: unknown };
+
+function resolveBound(bound: SettleBound): { timeout: number; within: string } {
+ if (bound.budget !== undefined) {
+ const { label, totalMs } = bound.budget;
+ const timeout = bound.budget.remainingMs();
+ return {
+ timeout,
+ within: `within the ${Math.round(timeout)} ms left of settle budget "${label}" (${totalMs} ms)`,
+ };
+ }
+ requirePositiveTimeout('expectSettledReading', bound.timeout);
+ return { timeout: bound.timeout, within: `within ${bound.timeout} ms` };
+}
+
+export async function expectSettledReading<T>(
+ read: () => Promise<T>,
+ accept: (value: T) => void,
+ options: SettledReadingOptions,
+): Promise<void> {
+ const { timeout, within } = resolveBound(options);
+ const latest: { attempt: SettleAttempt } = { attempt: { kind: 'none' } };
+ try {
+ await expect(async () => {
+ const attempt = await new Promise<T>((resolve) => {
+ resolve(read());
+ }).then(
+ (value) => ({ kind: 'read', value }) as const,
+ (error: unknown) => ({ kind: 'read-failed', error }) as const,
+ );
+ latest.attempt = attempt.kind === 'read' ? { kind: 'read' } : attempt;
+ if (attempt.kind === 'read-failed') throw attempt.error;
+ accept(attempt.value);
+ }).toPass({ timeout });
+ } catch (settleFailure) {
+ const { attempt } = latest;
+ if (attempt.kind === 'read-failed') throw attempt.error;
+ if (attempt.kind === 'none') {
+ throw new Error(`no ${options.reading} reading completed for ${options.of} ${within}`);
+ }
+ if (options.budget === undefined) throw settleFailure;
+ const reason = settleFailure instanceof Error ? settleFailure.message : String(settleFailure);
+ throw new Error(`${options.reading} of ${options.of} never settled ${within}: ${reason}`, {
+ cause: settleFailure,
+ });
+ }
+}
diff --git a/packages/desktop/tests/smoke/_helpers/transient-notice.test.ts b/packages/desktop/tests/smoke/_helpers/transient-notice.test.ts
new file mode 100644
index 000000000..f9bb373bd
--- /dev/null
+++ b/packages/desktop/tests/smoke/_helpers/transient-notice.test.ts
@@ -0,0 +1,558 @@
+import { stripVTControlCharacters } from 'node:util';
+import { describe, expect, test, vi } from 'vitest';
+import {
+ expectNoticeFromTrigger,
+ type TransientNoticeObservation,
+ type TransientNoticeRecorder,
+ transientNoticeObservation,
+} from './transient-notice';
+
+const NOTICE = 'Agent panel closed to keep Terminal readable.';
+const OTHER_NOTICE = 'Terminal closed to make room for the agent panel.';
+const OBSERVE_BOUND_MS = 300;
+
+function noticeSurface() {
+ let observing = false;
+ const observed: string[] = [];
+ return {
+ show(text: string): void {
+ if (observing) observed.push(text);
+ },
+ observation(
+ trigger: () => Promise<void>,
+ startObserving: () => Promise<void> = () => {
+ observing = true;
+ return Promise.resolve();
+ },
+ ): TransientNoticeObservation {
+ return {
+ startObserving,
+ trigger,
+ readObserved: () => Promise.resolve([...observed]),
+ };
+ },
+ };
+}
+
+async function rejectionOf(run: Promise<unknown>): Promise<string> {
+ return run.then(
+ () => {
+ throw new Error('the notice oracle resolved where it had to reject');
+ },
+ (error: unknown) =>
+ stripVTControlCharacters(error instanceof Error ? error.message : String(error)),
+ );
+}
+
+describe('transient notice caused by a trigger', () => {
+ test('replays CI retry 1: observes a notice shown and dismissed before the trigger returned', async () => {
+ const surface = noticeSurface();
+
+ await expectNoticeFromTrigger(
+ NOTICE,
+ surface.observation(() => {
+ surface.show(NOTICE);
+ return Promise.resolve();
+ }),
+ { timeout: OBSERVE_BOUND_MS },
+ );
+ });
+
+ test('observes a notice that fires after the trigger returns', async () => {
+ const surface = noticeSurface();
+
+ await expectNoticeFromTrigger(
+ NOTICE,
+ surface.observation(() => {
+ setTimeout(() => surface.show(NOTICE), 0);
+ return Promise.resolve();
+ }),
+ { timeout: OBSERVE_BOUND_MS },
+ );
+ });
+
+ test('fails naming the notice when the trigger shows none', async () => {
+ const surface = noticeSurface();
+
+ const message = await rejectionOf(
+ expectNoticeFromTrigger(
+ NOTICE,
+ surface.observation(() => Promise.resolve()),
+ { timeout: OBSERVE_BOUND_MS },
+ ),
+ );
+
+ expect(message).toContain(NOTICE);
+ });
+
+ test('is not satisfied by a different notice the trigger showed', async () => {
+ const surface = noticeSurface();
+
+ const message = await rejectionOf(
+ expectNoticeFromTrigger(
+ NOTICE,
+ surface.observation(() => {
+ surface.show(OTHER_NOTICE);
+ return Promise.resolve();
+ }),
+ { timeout: OBSERVE_BOUND_MS },
+ ),
+ );
+
+ expect(message).toContain(NOTICE);
+ });
+
+ test('surfaces an observer that cannot start as that failure, not as a missing notice', async () => {
+ const OBSERVER_FAILURE = 'the recorder could not be installed in the renderer';
+ const surface = noticeSurface();
+
+ const message = await rejectionOf(
+ expectNoticeFromTrigger(
+ NOTICE,
+ surface.observation(
+ () => {
+ surface.show(NOTICE);
+ return Promise.resolve();
+ },
+ () => Promise.reject(new Error(OBSERVER_FAILURE)),
+ ),
+ { timeout: OBSERVE_BOUND_MS },
+ ),
+ );
+
+ expect(message).toContain(OBSERVER_FAILURE);
+ expect(message).not.toMatch(/Received/u);
+ });
+});
+
+const STOP_FAILURE = 'the notice recorder could not be disconnected';
+const LIVENESS_BOUND_MS = 500;
+
+function stoppable(
+ observation: TransientNoticeObservation,
+ stop: () => Promise<void> = () => Promise.resolve(),
+) {
+ let stops = 0;
+ const stoppableObservation: TransientNoticeObservation = {
+ ...observation,
+ readObserved: () =>
+ stops > 0
+ ? Promise.reject(new Error('the notice record was read after the observer stopped'))
+ : observation.readObserved(),
+ stopObserving: () => {
+ stops += 1;
+ return stop();
+ },
+ };
+ return { observation: stoppableObservation, stops: () => stops };
+}
+
+describe('transient notice observer teardown', () => {
+ test('stops the observer once, after the notice was observed', async () => {
+ const surface = noticeSurface();
+ const observer = stoppable(
+ surface.observation(() => {
+ surface.show(NOTICE);
+ return Promise.resolve();
+ }),
+ );
+
+ await expectNoticeFromTrigger(NOTICE, observer.observation, { timeout: OBSERVE_BOUND_MS });
+
+ expect(observer.stops()).toBe(1);
+ });
+
+ test('keeps the missing-notice verdict when stopping the observer also fails', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ try {
+ const surface = noticeSurface();
+ const observer = stoppable(
+ surface.observation(() => Promise.resolve()),
+ () => Promise.reject(new Error(STOP_FAILURE)),
+ );
+
+ const message = await rejectionOf(
+ expectNoticeFromTrigger(NOTICE, observer.observation, { timeout: OBSERVE_BOUND_MS }),
+ );
+
+ expect(observer.stops()).toBe(1);
+ expect(message).toContain(NOTICE);
+ expect(message).not.toContain(STOP_FAILURE);
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining(STOP_FAILURE));
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
+ test('surfaces a failure to stop the observer as itself once the notice was observed', async () => {
+ const surface = noticeSurface();
+ const observer = stoppable(
+ surface.observation(() => {
+ surface.show(NOTICE);
+ return Promise.resolve();
+ }),
+ () => Promise.reject(new Error(STOP_FAILURE)),
+ );
+
+ const message = await rejectionOf(
+ expectNoticeFromTrigger(NOTICE, observer.observation, { timeout: OBSERVE_BOUND_MS }),
+ );
+
+ expect(message).toContain(STOP_FAILURE);
+ expect(message).not.toMatch(/Received/u);
+ });
+});
+
+describe('transient notice observation bound', () => {
+ test.each([
+ ['a zero bound', 0],
+ ['a NaN bound', Number.NaN],
+ ['a negative bound', -1],
+ ])(
+ 'rejects %s promptly by naming the positive-bound contract, before it arms or triggers anything',
+ async (_label, timeout) => {
+ let starts = 0;
+ let triggers = 0;
+ let raceOver = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+
+ const outcome = await Promise.race([
+ expectNoticeFromTrigger(
+ NOTICE,
+ {
+ startObserving: () => {
+ starts += 1;
+ return Promise.resolve();
+ },
+ trigger: () => {
+ triggers += 1;
+ return Promise.resolve();
+ },
+ readObserved: () =>
+ raceOver
+ ? Promise.reject(new Error('the liveness race is over'))
+ : Promise.resolve([]),
+ },
+ { timeout },
+ ).then(
+ () => 'resolved',
+ (error: unknown) =>
+ stripVTControlCharacters(error instanceof Error ? error.message : String(error)),
+ ),
+ new Promise<string>((resolve) => {
+ timer = setTimeout(() => resolve('still waiting'), LIVENESS_BOUND_MS);
+ }),
+ ]);
+ raceOver = true;
+ clearTimeout(timer);
+
+ expect(outcome).toMatch(/positive/u);
+ expect([starts, triggers]).toEqual([0, 0]);
+ },
+ );
+});
+
+type NoticeListener = (text: string) => void;
+
+interface FakeRealm {
+ readonly noticeRegion: { subscribe(listener: NoticeListener): () => void };
+ readonly sessionStorage: Pick<Storage, 'getItem' | 'setItem'>;
+ [key: string]: unknown;
+}
+
+interface FakeDocument {
+ readonly window: FakeRealm;
+ readonly document: { readonly body: { readonly innerText: string } };
+ show(text: string): void;
+ dismiss(text: string): void;
+ subscriptionsOpened(): number;
+ activeSubscriptions(): number;
+}
+
+function fakeDocument(pageSessionStorage: Map<string, string>): FakeDocument {
+ const visible: string[] = [];
+ const listeners = new Set<NoticeListener>();
+ let opened = 0;
+ return {
+ window: {
+ noticeRegion: {
+ subscribe(listener) {
+ listeners.add(listener);
+ opened += 1;
+ return () => {
+ listeners.delete(listener);
+ };
+ },
+ },
+ sessionStorage: {
+ getItem: (key) => pageSessionStorage.get(key) ?? null,
+ setItem: (key, value) => {
+ pageSessionStorage.set(key, value);
+ },
+ },
+ },
+ document: {
+ body: {
+ get innerText() {
+ return visible.join('\n');
+ },
+ },
+ },
+ show(text) {
+ visible.push(text);
+ for (const listener of listeners) listener(text);
+ },
+ dismiss(text) {
+ const at = visible.indexOf(text);
+ if (at >= 0) visible.splice(at, 1);
+ },
+ subscriptionsOpened: () => opened,
+ activeSubscriptions: () => listeners.size,
+ };
+}
+
+function runInDocument<A, R>(target: FakeDocument, pageFunction: (arg: A) => R, arg: A): R {
+ vi.stubGlobal('window', target.window);
+ vi.stubGlobal('document', target.document);
+ vi.stubGlobal('sessionStorage', target.window.sessionStorage);
+ try {
+ return structuredClone(pageFunction(structuredClone(arg)));
+ } finally {
+ vi.unstubAllGlobals();
+ }
+}
+
+function documentAwarePage({ honoursInitScripts = true }: { honoursInitScripts?: boolean } = {}) {
+ const pageSessionStorage = new Map<string, string>();
+ const initScripts = new Set<(target: FakeDocument) => void>();
+ let current = fakeDocument(pageSessionStorage);
+ let bootApp: (booted: FakeDocument) => void = () => {};
+
+ const page = {
+ addInitScript<A>(script: (arg: A) => unknown, arg: A) {
+ const registeredArg = structuredClone(arg);
+ const runOnNewDocument = (target: FakeDocument): void => {
+ runInDocument(target, script, registeredArg);
+ };
+ initScripts.add(runOnNewDocument);
+ const dispose = (): Promise<void> => {
+ initScripts.delete(runOnNewDocument);
+ return Promise.resolve();
+ };
+ return Promise.resolve({ dispose, [Symbol.asyncDispose]: dispose });
+ },
+ evaluate<A, R>(pageFunction: (arg: A) => R, arg: A): Promise<R> {
+ return Promise.resolve().then(() => runInDocument(current, pageFunction, arg));
+ },
+ };
+
+ return {
+ page: page as unknown as Parameters<typeof transientNoticeObservation>[0],
+ current: () => current,
+ whenBooted(boot: (booted: FakeDocument) => void): void {
+ bootApp = boot;
+ },
+ reload(): Promise<void> {
+ const reloaded = fakeDocument(pageSessionStorage);
+ if (honoursInitScripts)
+ for (const runOnNewDocument of initScripts) runOnNewDocument(reloaded);
+ current = reloaded;
+ bootApp(reloaded);
+ return Promise.resolve();
+ },
+ activeInitScripts: () => initScripts.size,
+ };
+}
+
+interface FakeRecord {
+ readonly seen: string[];
+ readonly release: () => void;
+}
+
+const realmRecorder: TransientNoticeRecorder = {
+ record({ key, notices }) {
+ const realm = window as unknown as FakeRealm;
+ if (realm[key] !== undefined) return;
+ const seen: string[] = [];
+ const release = realm.noticeRegion.subscribe((text) => {
+ if (notices.includes(text) && !seen.includes(text)) seen.push(text);
+ });
+ const record: FakeRecord = { seen, release };
+ Object.defineProperty(realm, key, { value: record });
+ },
+ read(key) {
+ const record = (window as unknown as FakeRealm)[key] as FakeRecord | undefined;
+ return record === undefined ? null : [...record.seen];
+ },
+ stop(key) {
+ ((window as unknown as FakeRealm)[key] as FakeRecord | undefined)?.release();
+ },
+};
+
+const showsAndRemoves = (target: FakeDocument, text: string): void => {
+ target.show(text);
+ target.dismiss(text);
+};
+
+describe('transient notice observed in the document its trigger produced', () => {
+ test('replays CI retry 1: next-document arming observes a notice the reloaded document shows and removes before the reload resolves', async () => {
+ const tab = documentAwarePage();
+ tab.whenBooted((reloaded) => showsAndRemoves(reloaded, NOTICE));
+
+ await expectNoticeFromTrigger(
+ NOTICE,
+ transientNoticeObservation(tab.page, {
+ document: 'next',
+ trigger: () => tab.reload(),
+ recorder: realmRecorder,
+ }),
+ { timeout: OBSERVE_BOUND_MS },
+ );
+ });
+
+ test('is never satisfied by a notice the pre-reload document was showing when observation armed', async () => {
+ const tab = documentAwarePage();
+ tab.current().show(NOTICE);
+
+ const message = await rejectionOf(
+ expectNoticeFromTrigger(
+ NOTICE,
+ transientNoticeObservation(tab.page, {
+ document: 'next',
+ trigger: () => tab.reload(),
+ recorder: realmRecorder,
+ }),
+ { timeout: OBSERVE_BOUND_MS },
+ ),
+ );
+
+ expect(tab.current().subscriptionsOpened()).toBeGreaterThan(0);
+ expect(message).toContain(NOTICE);
+ expect(message).not.toMatch(/not installed/u);
+ });
+
+ test('reports a reloaded document the recorder never reached as a missing recorder, never as a missing notice', async () => {
+ const tab = documentAwarePage({ honoursInitScripts: false });
+ tab.whenBooted((reloaded) => showsAndRemoves(reloaded, NOTICE));
+
+ const message = await rejectionOf(
+ expectNoticeFromTrigger(
+ NOTICE,
+ transientNoticeObservation(tab.page, {
+ document: 'next',
+ trigger: () => tab.reload(),
+ recorder: realmRecorder,
+ }),
+ { timeout: OBSERVE_BOUND_MS },
+ ),
+ );
+
+ expect(message).toMatch(/recorder\b.*\bnot installed/u);
+ expect(message).not.toMatch(/Received/u);
+ });
+
+ test('current-document arming ignores a notice already on screen when it armed', async () => {
+ const tab = documentAwarePage();
+ tab.current().show(NOTICE);
+
+ const message = await rejectionOf(
+ expectNoticeFromTrigger(
+ NOTICE,
+ transientNoticeObservation(tab.page, {
+ document: 'current',
+ trigger: () => Promise.resolve(),
+ recorder: realmRecorder,
+ }),
+ { timeout: OBSERVE_BOUND_MS },
+ ),
+ );
+
+ expect(tab.current().subscriptionsOpened()).toBeGreaterThan(0);
+ expect(message).toContain(NOTICE);
+ expect(message).not.toMatch(/not installed/u);
+ });
+
+ test('current-document arming records a notice the trigger shows and removes', async () => {
+ const tab = documentAwarePage();
+
+ await expectNoticeFromTrigger(
+ NOTICE,
+ transientNoticeObservation(tab.page, {
+ document: 'current',
+ trigger: () => {
+ showsAndRemoves(tab.current(), NOTICE);
+ return Promise.resolve();
+ },
+ recorder: realmRecorder,
+ }),
+ { timeout: OBSERVE_BOUND_MS },
+ );
+ });
+
+ test('gives each observation its own record, so a notice an earlier observation recorded never satisfies a later one', async () => {
+ const tab = documentAwarePage();
+ const observeCurrent = (trigger: () => Promise<void>) =>
+ transientNoticeObservation(tab.page, {
+ document: 'current',
+ trigger,
+ recorder: realmRecorder,
+ });
+
+ await expectNoticeFromTrigger(
+ NOTICE,
+ observeCurrent(() => {
+ showsAndRemoves(tab.current(), NOTICE);
+ return Promise.resolve();
+ }),
+ { timeout: OBSERVE_BOUND_MS },
+ );
+ const message = await rejectionOf(
+ expectNoticeFromTrigger(
+ NOTICE,
+ observeCurrent(() => Promise.resolve()),
+ { timeout: OBSERVE_BOUND_MS },
+ ),
+ );
+
+ expect(message).toContain(NOTICE);
+ expect(message).not.toMatch(/not installed/u);
+ });
+
+ test('disposes the init script and disconnects the recorder once the reload notice is judged', async () => {
+ const tab = documentAwarePage();
+ tab.whenBooted((reloaded) => showsAndRemoves(reloaded, NOTICE));
+
+ await expectNoticeFromTrigger(
+ NOTICE,
+ transientNoticeObservation(tab.page, {
+ document: 'next',
+ trigger: () => tab.reload(),
+ recorder: realmRecorder,
+ }),
+ { timeout: OBSERVE_BOUND_MS },
+ );
+
+ expect(tab.activeInitScripts()).toBe(0);
+ expect(tab.current().activeSubscriptions()).toBe(0);
+ });
+
+ test('disconnects the recorder once an in-document notice is judged', async () => {
+ const tab = documentAwarePage();
+
+ await expectNoticeFromTrigger(
+ NOTICE,
+ transientNoticeObservation(tab.page, {
+ document: 'current',
+ trigger: () => {
+ showsAndRemoves(tab.current(), NOTICE);
+ return Promise.resolve();
+ },
+ recorder: realmRecorder,
+ }),
+ { timeout: OBSERVE_BOUND_MS },
+ );
+
+ expect(tab.current().activeSubscriptions()).toBe(0);
+ });
+});
diff --git a/packages/desktop/tests/smoke/_helpers/transient-notice.ts b/packages/desktop/tests/smoke/_helpers/transient-notice.ts
new file mode 100644
index 000000000..2724084d1
--- /dev/null
+++ b/packages/desktop/tests/smoke/_helpers/transient-notice.ts
@@ -0,0 +1,169 @@
+import { randomUUID } from 'node:crypto';
+import { expect, type Page } from '@playwright/test';
+import { requirePositiveTimeout } from './settled-reading';
+
+export interface TransientNoticeObservation {
+ startObserving: (notice: string) => Promise<void>;
+ trigger: () => Promise<void>;
+ readObserved: () => Promise<readonly string[]>;
+ stopObserving?: () => Promise<void>;
+}
+
+export interface TransientNoticeOptions {
+ timeout: number;
+}
+
+export interface TransientNoticeRecorder {
+ record: (args: { key: string; notices: readonly string[] }) => void;
+ read: (key: string) => string[] | null;
+ stop: (key: string) => void;
+}
+
+export interface TransientNoticePageOptions {
+ trigger: () => Promise<void>;
+ document: 'next' | 'current';
+ recorder?: TransientNoticeRecorder;
+}
+
+export async function expectNoticeFromTrigger(
+ notice: string,
+ { startObserving, trigger, readObserved, stopObserving }: TransientNoticeObservation,
+ { timeout }: TransientNoticeOptions,
+): Promise<void> {
+ requirePositiveTimeout('expectNoticeFromTrigger', timeout);
+ await startObserving(notice);
+ try {
+ await trigger();
+ await expect.poll(readObserved, { timeout }).toContain(notice);
+ } catch (verdict) {
+ await stopObserving?.().catch((stopFailure: unknown) => {
+ const reason = stopFailure instanceof Error ? stopFailure.message : String(stopFailure);
+ console.warn(
+ `[transient-notice] could not stop observing "${notice}" after its verdict failed: ${reason}`,
+ );
+ });
+ throw verdict;
+ }
+ await stopObserving?.();
+}
+
+export function transientNoticeObservation(
+ page: Page,
+ { trigger, document: arming, recorder = pageRecorder }: TransientNoticePageOptions,
+): TransientNoticeObservation {
+ const key = `__okTransientNotices:${randomUUID()}`;
+ let observed = '';
+ let initScript: { dispose: () => Promise<void> } | undefined;
+ return {
+ async startObserving(notice) {
+ observed = notice;
+ const args = { key, notices: [notice] };
+ if (arming === 'next') {
+ initScript = await page.addInitScript(recorder.record, args);
+ } else {
+ await page.evaluate(recorder.record, args);
+ }
+ },
+ trigger,
+ async readObserved() {
+ const seen = await page.evaluate(recorder.read, key);
+ if (seen === null) {
+ throw new Error(
+ `the transient-notice recorder is not installed in the current document, so "${observed}" could not be observed there`,
+ );
+ }
+ return seen;
+ },
+ async stopObserving() {
+ try {
+ await page.evaluate(recorder.stop, key);
+ } finally {
+ await initScript?.dispose();
+ }
+ },
+ };
+}
+
+interface TransientNoticeRecord {
+ readonly seen: string[];
+ readonly flush: () => void;
+ readonly observer: MutationObserver;
+}
+
+function recordTransientNotices({ key, notices }: { key: string; notices: readonly string[] }) {
+ const realm = window as unknown as Record<string, unknown>;
+ if (realm[key] !== undefined) return;
+ const normalize = (text: string | null): string => (text ?? '').replace(/\s+/gu, ' ').trim();
+ const watched = notices.map((notice) => ({ notice, text: normalize(notice) }));
+ const seen: string[] = [];
+ const pending = new Map<Element, string>();
+ const carries = (element: Element, text: string): boolean =>
+ normalize(element.textContent).includes(text);
+ const innermost = (root: Element, text: string): Element[] => {
+ const inner = [...root.children].filter((child) => carries(child, text));
+ return inner.length === 0 ? [root] : inner.flatMap((child) => innermost(child, text));
+ };
+ const consider = (root: Element, wholeSubtreeIsNew: boolean): void => {
+ for (const { notice, text } of watched) {
+ if (!carries(root, text)) continue;
+ for (const candidate of innermost(root, text)) {
+ if (wholeSubtreeIsNew || candidate === root) pending.set(candidate, notice);
+ }
+ }
+ };
+ const isVisible = (element: Element): boolean => {
+ const box = element.getBoundingClientRect();
+ return box.width > 0 && box.height > 0 && getComputedStyle(element).visibility !== 'hidden';
+ };
+ const flush = (): void => {
+ for (const [candidate, notice] of pending) {
+ if (!candidate.isConnected) {
+ pending.delete(candidate);
+ } else if (isVisible(candidate)) {
+ if (!seen.includes(notice)) seen.push(notice);
+ pending.delete(candidate);
+ }
+ }
+ };
+ const observer = new MutationObserver((mutations) => {
+ for (const mutation of mutations) {
+ if (mutation.type === 'childList') {
+ for (const node of mutation.addedNodes) {
+ if (node instanceof Element) consider(node, true);
+ else if (node.parentElement !== null) consider(node.parentElement, false);
+ }
+ } else if (mutation.type === 'characterData' && mutation.target.parentElement !== null) {
+ consider(mutation.target.parentElement, false);
+ }
+ }
+ flush();
+ });
+ observer.observe(document, {
+ childList: true,
+ subtree: true,
+ characterData: true,
+ attributes: true,
+ attributeFilter: ['class', 'style', 'hidden'],
+ });
+ const record: TransientNoticeRecord = { seen, flush, observer };
+ Object.defineProperty(realm, key, { value: record });
+}
+
+function readTransientNotices(key: string): string[] | null {
+ const record = (window as unknown as Record<string, TransientNoticeRecord | undefined>)[key];
+ if (record === undefined) return null;
+ record.flush();
+ return [...record.seen];
+}
+
+function stopTransientNotices(key: string): void {
+ (window as unknown as Record<string, TransientNoticeRecord | undefined>)[
+ key
+ ]?.observer.disconnect();
+}
+
+const pageRecorder: TransientNoticeRecorder = {
+ record: recordTransientNotices,
+ read: readTransientNotices,
+ stop: stopTransientNotices,
+};
diff --git a/packages/desktop/tests/smoke/terminal-dock.e2e.ts b/packages/desktop/tests/smoke/terminal-dock.e2e.ts
index 8b045faed..7a8860eb8 100644
--- a/packages/desktop/tests/smoke/terminal-dock.e2e.ts
+++ b/packages/desktop/tests/smoke/terminal-dock.e2e.ts
@@ -25,6 +25,12 @@ import {
PTY_PLATFORM_SUPPORTED,
userDataDirFor,
} from './_helpers/platform-gate';
+import { expectCollapsedRailColumn } from './_helpers/rail-column';
+import {
+ expectSettledReading,
+ RAIL_LAYOUT_SETTLE_TIMEOUT_MS,
+ settleBudget,
+} from './_helpers/settled-reading';
import { expect, test } from './_helpers/smoke-test';
import { waitForShellReady } from './_helpers/terminal-ready';
import {
@@ -34,6 +40,7 @@ import {
terminalSmokeShellCommands,
writeFakeClaudeShim,
} from './_helpers/terminal-smoke-shell';
+import { expectNoticeFromTrigger, transientNoticeObservation } from './_helpers/transient-notice';
const TARGET = resolveDesktopTarget();
@@ -323,14 +330,6 @@ async function revealTerminalSurface(app: ElectronApplication, target: Locator):
}).toPass({ timeout: 15_000 });
}
-async function expectCollapsedRailColumn(page: Page, selector: string): Promise<void> {
- const column = page.locator(selector);
- await expect(column).toHaveCount(1);
- await expect
- .poll(() => column.evaluate((element) => element.getBoundingClientRect().width))
- .toBe(0);
-}
-
async function openTerminal(app: ElectronApplication, page: Page): Promise<void> {
await revealTerminalSurface(app, terminalSection(page));
}
@@ -625,21 +624,40 @@ test.describe('Docked terminal — live Electron', () => {
expect(Number(columns)).toBeGreaterThanOrEqual(92);
const editorWindow = await app.browserWindow(page);
- await editorWindow.evaluate((win: unknown) => {
- const target = win as { setSize: (width: number, height: number, animate: boolean) => void };
- target.setSize(900, 900, false);
+ const shrink = settleBudget('rail admission after the window narrows to 900 px', {
+ timeout: RAIL_LAYOUT_SETTLE_TIMEOUT_MS,
});
- // STOP: this notice auto-dismisses 4s after firing (sonner TOAST_LIFETIME; <Toaster> sets no duration), so assert it before slower waits.
- await expect(page.getByText('Agent panel closed to keep Terminal readable.')).toBeVisible();
- await expect.poll(() => page.evaluate(() => window.innerWidth)).toBeLessThan(1000);
- await expectCollapsedRailColumn(page, '#agents-column');
+ await expectNoticeFromTrigger(
+ 'Agent panel closed to keep Terminal readable.',
+ transientNoticeObservation(page, {
+ document: 'current',
+ trigger: async () => {
+ await editorWindow.evaluate((win: unknown) => {
+ const target = win as {
+ setSize: (width: number, height: number, animate: boolean) => void;
+ };
+ target.setSize(900, 900, false);
+ });
+ },
+ }),
+ { timeout: shrink.remainingMs() },
+ );
+ await expectSettledReading(
+ () => page.evaluate(() => window.innerWidth),
+ (width) => expect(width).toBeLessThan(1000),
+ { reading: 'innerWidth', of: 'the editor window', budget: shrink },
+ );
+ await expectCollapsedRailColumn(page, '#agents-column', { budget: shrink });
await expect(page.locator('#terminal-column section[aria-label="Terminal"]')).toBeVisible();
- await clickViewAgentsItem(app);
- // STOP: this notice auto-dismisses 4s after firing (sonner TOAST_LIFETIME; <Toaster> sets no duration), so assert it before slower waits.
- await expect(page.getByText('Terminal closed to make room for the agent panel.')).toBeVisible({
- timeout: 10_000,
- });
+ await expectNoticeFromTrigger(
+ 'Terminal closed to make room for the agent panel.',
+ transientNoticeObservation(page, {
+ document: 'current',
+ trigger: () => clickViewAgentsItem(app),
+ }),
+ { timeout: 10_000 },
+ );
await expect(page.locator('#agents-column')).toBeVisible({ timeout: 10_000 });
await expectCollapsedRailColumn(page, '#terminal-column');
diff --git a/packages/desktop/tests/smoke/terminal-movement.e2e.ts b/packages/desktop/tests/smoke/terminal-movement.e2e.ts
index d2ce2766d..86222f95e 100644
--- a/packages/desktop/tests/smoke/terminal-movement.e2e.ts
+++ b/packages/desktop/tests/smoke/terminal-movement.e2e.ts
@@ -10,6 +10,13 @@ import {
PTY_PLATFORM_SUPPORTED,
userDataDirFor,
} from './_helpers/platform-gate';
+import { expectCollapsedRailColumn, readRailColumnWidth } from './_helpers/rail-column';
+import {
+ expectSettledReading,
+ RAIL_LAYOUT_SETTLE_TIMEOUT_MS,
+ type SettleBudget,
+ settleBudget,
+} from './_helpers/settled-reading';
import { expect, test } from './_helpers/smoke-test';
import { waitForShellReady } from './_helpers/terminal-ready';
import {
@@ -25,6 +32,7 @@ import {
terminalTabIds,
terminalTabs,
} from './_helpers/terminal-tabs.test-helper';
+import { expectNoticeFromTrigger, transientNoticeObservation } from './_helpers/transient-notice';
const TARGET = resolveDesktopTarget();
const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';
@@ -410,7 +418,10 @@ async function readShellPid(page: Page, marker: string): Promise<number> {
return processId;
}
-async function growRightTerminal(page: Page, deltaPx: number): Promise<number> {
+async function growRightTerminal(
+ page: Page,
+ deltaPx: number,
+): Promise<{ width: number; settle: SettleBudget }> {
const column = page.locator('#terminal-column');
const before = await column.evaluate((element) => element.getBoundingClientRect().width);
const handle = await column.evaluate((element) => {
@@ -422,18 +433,16 @@ async function growRightTerminal(page: Page, deltaPx: number): Promise<number> {
await page.mouse.down();
await page.mouse.move(handle.x - deltaPx, handle.y + handle.height / 2, { steps: 12 });
await page.mouse.up();
- await expect
- .poll(() => column.evaluate((element) => element.getBoundingClientRect().width))
- .toBeGreaterThan(before + deltaPx / 2);
- return column.evaluate((element) => element.getBoundingClientRect().width);
-}
-
-async function expectCollapsedRailColumn(page: Page, selector: string): Promise<void> {
- const column = page.locator(selector);
- await expect(column).toHaveCount(1);
- await expect
- .poll(() => column.evaluate((element) => element.getBoundingClientRect().width))
- .toBe(0);
+ const settle = settleBudget('right Terminal resize and its persisted layout', {
+ timeout: RAIL_LAYOUT_SETTLE_TIMEOUT_MS,
+ });
+ await expectSettledReading(
+ () => readRailColumnWidth(page, '#terminal-column'),
+ (width) => expect(width).toBeGreaterThan(before + deltaPx / 2),
+ { reading: 'width', of: '#terminal-column', budget: settle },
+ );
+ const width = await column.evaluate((element) => element.getBoundingClientRect().width);
+ return { width, settle };
}
async function expectStillScrolledBack(page: Page, newestLine: string): Promise<void> {
@@ -557,21 +566,18 @@ test.describe('Terminal placement continuity — live Electron', () => {
await expectTerminalTabOrder(page, [secondTabId, firstTabId]);
await expect(terminalTabById(page, secondTabId)).toHaveAttribute('aria-selected', 'true');
await moveTerminal(app, page, 'right');
- const restoredWidth = await growRightTerminal(page, 120);
+ const { width: restoredWidth, settle: railResize } = await growRightTerminal(page, 120);
- await expect
- .poll(async () => {
- return page.evaluate(() => localStorage.getItem('ok-terminal-placement-v1'));
- })
- .toBe('right');
- await expect
- .poll(async () => {
- const retainedWidth = await page.evaluate(() =>
- Number(localStorage.getItem('ok-terminal-right-width-v1')),
- );
- return Math.abs(retainedWidth - restoredWidth);
- })
- .toBeLessThan(20);
+ await expectSettledReading(
+ () => page.evaluate(() => localStorage.getItem('ok-terminal-placement-v1')),
+ (placement) => expect(placement).toBe('right'),
+ { reading: 'placement', of: 'localStorage ok-terminal-placement-v1', budget: railResize },
+ );
+ await expectSettledReading(
+ () => page.evaluate(() => Number(localStorage.getItem('ok-terminal-right-width-v1'))),
+ (retainedWidth) => expect(Math.abs(retainedWidth - restoredWidth)).toBeLessThan(20),
+ { reading: 'width', of: 'localStorage ok-terminal-right-width-v1', budget: railResize },
+ );
await page.reload({ waitUntil: 'domcontentloaded' });
await expect(page.locator('#terminal-column')).toBeVisible({ timeout: 20_000 });
@@ -579,18 +585,19 @@ test.describe('Terminal placement continuity — live Electron', () => {
await expect(terminalTabs(page)).toHaveText([secondLabel, 'restart first'], {
timeout: 25_000,
});
+ const restoredTail = settleBudget('restored active tab and right Terminal width', {
+ timeout: RAIL_LAYOUT_SETTLE_TIMEOUT_MS,
+ });
await expect(page.getByRole('tab', { name: secondLabel })).toHaveAttribute(
'aria-selected',
'true',
+ { timeout: restoredTail.remainingMs() },
+ );
+ await expectSettledReading(
+ () => readRailColumnWidth(page, '#terminal-column'),
+ (width) => expect(Math.abs(width - restoredWidth)).toBeLessThan(20),
+ { reading: 'width', of: '#terminal-column', budget: restoredTail },
);
- await expect
- .poll(async () => {
- const width = await page
- .locator('#terminal-column')
- .evaluate((element) => element.getBoundingClientRect().width);
- return Math.abs(width - restoredWidth);
- })
- .toBeLessThan(20);
expect(await readShellPid(page, processMarker)).toBe(processId);
const afterRestart = `AFTER_RESTART_${token}`;
await typeInActiveTerminal(page, `${SHELL_COMMANDS.output(afterRestart)}\r`);
@@ -605,8 +612,15 @@ test.describe('Terminal placement continuity — live Electron', () => {
};
target.setSize(900, 900, false);
});
- await expect.poll(() => page.evaluate(() => window.innerWidth)).toBeLessThan(1000);
- await expectCollapsedRailColumn(page, '#agents-column');
+ const shrink = settleBudget('rail admission after the window narrows to 900 px', {
+ timeout: RAIL_LAYOUT_SETTLE_TIMEOUT_MS,
+ });
+ await expectSettledReading(
+ () => page.evaluate(() => window.innerWidth),
+ (width) => expect(width).toBeLessThan(1000),
+ { reading: 'innerWidth', of: 'the editor window', budget: shrink },
+ );
+ await expectCollapsedRailColumn(page, '#agents-column', { budget: shrink });
await page.evaluate(() => {
window.okDesktop?.editor.notifyViewMenuStateChanged({ agentPanelVisible: true });
});
@@ -619,12 +633,16 @@ test.describe('Terminal placement continuity — live Electron', () => {
{ timeout: 10_000 },
)
.toBe(true);
- await page.reload({ waitUntil: 'domcontentloaded' });
-
- // STOP: this notice auto-dismisses 4s after firing (sonner TOAST_LIFETIME; <Toaster> sets no duration), so assert it before slower waits.
- await expect(page.getByText('Agent panel closed to keep Terminal readable.')).toBeVisible({
- timeout: 20_000,
- });
+ await expectNoticeFromTrigger(
+ 'Agent panel closed to keep Terminal readable.',
+ transientNoticeObservation(page, {
+ document: 'next',
+ trigger: async () => {
+ await page.reload({ waitUntil: 'domcontentloaded' });
+ },
+ }),
+ { timeout: 20_000 },
+ );
await expect(page.locator('#terminal-column')).toBeVisible({ timeout: 10_000 });
await expectCollapsedRailColumn(page, '#agents-column');
await editorWindow.evaluate((windowHandle: unknown) => {
diff --git a/packages/desktop/tests/smoke/terminal-process-restart.e2e.ts b/packages/desktop/tests/smoke/terminal-process-restart.e2e.ts
index 45884426c..92db69a98 100644
--- a/packages/desktop/tests/smoke/terminal-process-restart.e2e.ts
+++ b/packages/desktop/tests/smoke/terminal-process-restart.e2e.ts
@@ -10,6 +10,12 @@ import {
PTY_PLATFORM_SUPPORTED,
userDataDirFor,
} from './_helpers/platform-gate';
+import { readRailColumnWidth } from './_helpers/rail-column';
+import {
+ expectSettledReading,
+ RAIL_LAYOUT_SETTLE_TIMEOUT_MS,
+ settleBudget,
+} from './_helpers/settled-reading';
import { expect, test } from './_helpers/smoke-test';
import {
seedTerminalShellProfiles,
@@ -157,16 +163,14 @@ async function applyPersistedRightTerminalWidth(page: Page, width: number): Prom
localStorage.setItem('ok-terminal-right-width-v1', String(nextWidth));
}, width);
await page.reload({ waitUntil: 'domcontentloaded' });
+ const restore = settleBudget('restored right Terminal width', { timeout: 20_000 });
const column = page.locator('#terminal-column');
- await expect(column).toBeVisible({ timeout: 20_000 });
- await expect
- .poll(async () => {
- const renderedWidth = await column.evaluate(
- (element) => element.getBoundingClientRect().width,
- );
- return Math.abs(renderedWidth - width);
- })
- .toBeLessThan(20);
+ await expect(column).toBeVisible({ timeout: restore.remainingMs() });
+ await expectSettledReading(
+ () => readRailColumnWidth(page, '#terminal-column'),
+ (renderedWidth) => expect(Math.abs(renderedWidth - width)).toBeLessThan(20),
+ { reading: 'width', of: '#terminal-column', budget: restore },
+ );
return column.evaluate((element) => element.getBoundingClientRect().width);
}
@@ -245,17 +249,18 @@ test.describe('terminal process restart', () => {
await expect(terminalTabs(secondPage)).toHaveText([secondLabel, 'process first'], {
timeout: 25_000,
});
+ const restoredTail = settleBudget('restored active tab and right Terminal width', {
+ timeout: RAIL_LAYOUT_SETTLE_TIMEOUT_MS,
+ });
await expect(secondPage.getByRole('tab', { name: secondLabel })).toHaveAttribute(
'aria-selected',
'true',
+ { timeout: restoredTail.remainingMs() },
+ );
+ await expectSettledReading(
+ () => readRailColumnWidth(secondPage, '#terminal-column'),
+ (width) => expect(Math.abs(width - retainedWidth)).toBeLessThan(20),
+ { reading: 'width', of: '#terminal-column', budget: restoredTail },
);
- await expect
- .poll(async () => {
- const width = await secondPage
- .locator('#terminal-column')
- .evaluate((element) => element.getBoundingClientRect().width);
- return Math.abs(width - retainedWidth);
- })
- .toBeLessThan(20);
});
});