Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Settle three read-before-wait races in the OK stress e2e helpers (#4164)
Nick Gomezb07417f1f3ac
diff --git a/packages/app/tests/dom/select-all-probe.dom.test.ts b/packages/app/tests/dom/select-all-probe.dom.test.tsnew file mode 100644index 000000000..14c3572fc--- /dev/null+++ b/packages/app/tests/dom/select-all-probe.dom.test.ts@@ -0,0 +1,134 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { repairFocusAndReadProbe } from '../stress/_helpers/editor-state';++const SOURCE_CONTENT_SELECTOR = '.source-editor .cm-content';+const WYSIWYG_SELECTOR = '.ProseMirror:not(.composer-prosemirror)';+const SOURCE_MARKUP =+ '<div class="source-editor"><div class="cm-content" contenteditable="true"></div></div>';+const WYSIWYG_MARKUP = '<div class="ProseMirror" contenteditable="true"></div>';++type Reading = { from: number | undefined; to: number | undefined };++function mount(html: string, selector: string): HTMLElement {+ document.body.innerHTML = html;+ const el = document.querySelector(selector);+ if (!(el instanceof HTMLElement)) throw new Error(`mount: "${selector}" did not mount`);+ return el;+}++function mountCodeMirror(+ main: Reading,+ length: number,+ via: 'cmTile' | 'cmView' = 'cmTile',+): HTMLElement {+ const el = mount(SOURCE_MARKUP, SOURCE_CONTENT_SELECTOR);+ const view = { state: { doc: { length }, selection: { main } } };+ if (via === 'cmTile') Object.assign(el, { cmTile: { root: { view } } });+ else Object.assign(el, { cmView: { rootView: { view } } });+ return el;+}++function mountProseMirror(selection: Reading, size: number): HTMLElement {+ const el = mount(WYSIWYG_MARKUP, WYSIWYG_SELECTOR);+ vi.stubGlobal('__activeEditor', {+ editorView: { dom: el, state: { selection, doc: { content: { size } } } },+ });+ return el;+}++afterEach(() => {+ vi.unstubAllGlobals();+ document.body.innerHTML = '';+});++describe('select-all probe view classification', () => {+ test.each([+ { outcome: 'covers-document', from: 0, to: 12, length: 12 },+ { outcome: 'covers-document', from: 0, to: 0, length: 0 },+ { outcome: 'partial', from: 2, to: 5, length: 12 },+ { outcome: 'partial', from: 0, to: 5, length: 12 },+ { outcome: 'partial', from: 3, to: 12, length: 12 },+ { outcome: 'empty', from: 4, to: 4, length: 12 },+ { outcome: 'unreadable', from: 0, to: undefined, length: 12 },+ ])('CodeMirror $from-$to over a $length-character document reads $outcome', ({+ outcome,+ from,+ to,+ length,+ }) => {+ mountCodeMirror({ from, to }, length);+ expect(repairFocusAndReadProbe(SOURCE_CONTENT_SELECTOR).viewSelection).toBe(outcome);+ });++ test('CodeMirror is reached through the cmView handle when cmTile is absent', () => {+ mountCodeMirror({ from: 0, to: 9 }, 9, 'cmView');+ expect(repairFocusAndReadProbe(SOURCE_CONTENT_SELECTOR).viewSelection).toBe('covers-document');+ });++ test('a mounted source editor carrying neither handle reads unreadable', () => {+ mount(SOURCE_MARKUP, SOURCE_CONTENT_SELECTOR);+ expect(repairFocusAndReadProbe(SOURCE_CONTENT_SELECTOR).viewSelection).toBe('unreadable');+ });++ test.each([+ { outcome: 'covers-document', from: 0, to: 14, size: 14 },+ { outcome: 'covers-document', from: 0, to: 2, size: 2 },+ { outcome: 'partial', from: 1, to: 6, size: 14 },+ { outcome: 'partial', from: 4, to: 14, size: 14 },+ { outcome: 'empty', from: 3, to: 3, size: 14 },+ { outcome: 'unreadable', from: 0, to: undefined, size: 14 },+ ])('ProseMirror $from-$to over a size-$size document reads $outcome', ({+ outcome,+ from,+ to,+ size,+ }) => {+ mountProseMirror({ from, to }, size);+ expect(repairFocusAndReadProbe(WYSIWYG_SELECTOR).viewSelection).toBe(outcome);+ });++ test('a ProseMirror view whose dom is a different element falls through to the CodeMirror branch', () => {+ mountProseMirror({ from: 0, to: 14 }, 14);+ mountCodeMirror({ from: 3, to: 7 }, 12);+ expect(repairFocusAndReadProbe(SOURCE_CONTENT_SELECTOR).viewSelection).toBe('partial');+ });++ test('a selector that matches no element reads unreadable', () => {+ document.body.innerHTML = '<div class="unrelated"></div>';+ const probe = repairFocusAndReadProbe(SOURCE_CONTENT_SELECTOR);+ expect(probe.viewSelection).toBe('unreadable');+ expect(probe.matches).toBe(0);+ });+});++describe('select-all probe focus repair', () => {+ test('the probe takes focus for an editor that does not own it on entry', () => {+ mountCodeMirror({ from: 0, to: 12 }, 12);+ const probe = repairFocusAndReadProbe(SOURCE_CONTENT_SELECTOR);+ expect(probe.focusOwnedOnEntry).toBe(false);+ expect(probe.focusOwnedByEditor).toBe(true);+ expect(probe.activeElement).toBe('div.cm-content');+ });++ test('an editor that already owns focus is reported as owning it on entry', () => {+ const el = mountCodeMirror({ from: 0, to: 12 }, 12);+ el.focus({ preventScroll: true });+ const probe = repairFocusAndReadProbe(SOURCE_CONTENT_SELECTOR);+ expect(probe.focusOwnedOnEntry).toBe(true);+ expect(probe.focusOwnedByEditor).toBe(true);+ });++ test('focus stolen by another element is reported as not owned', () => {+ document.body.innerHTML = `${SOURCE_MARKUP}<input class="thief" />`;+ const thief = document.querySelector('.thief');+ const editor = document.querySelector(SOURCE_CONTENT_SELECTOR);+ if (!(thief instanceof HTMLElement) || !(editor instanceof HTMLElement)) {+ throw new Error('focus-thief fixture did not mount');+ }+ editor.addEventListener('focus', () => thief.focus());+ const probe = repairFocusAndReadProbe(SOURCE_CONTENT_SELECTOR);+ expect(probe.focusOwnedOnEntry).toBe(false);+ expect(probe.focusOwnedByEditor).toBe(false);+ expect(probe.activeElement).toBe('input.thief');+ });+});diff --git a/packages/app/tests/meta/select-all-wait-band.test.ts b/packages/app/tests/meta/select-all-wait-band.test.tsnew file mode 100644index 000000000..346edd8b3--- /dev/null+++ b/packages/app/tests/meta/select-all-wait-band.test.ts@@ -0,0 +1,35 @@+import { describe, expect, test, vi } from 'vitest';++async function loadBand(ci: string | undefined) {+ vi.stubEnv('CI', ci);+ vi.resetModules();+ try {+ const config = (await import('../../playwright.config')).default;+ const helper = await import('../stress/_helpers/editor-state');+ return {+ configured: config.expect?.timeout,+ helper: helper.SELECT_ALL_SETTLE_TIMEOUT_MS,+ };+ } finally {+ vi.unstubAllEnvs();+ vi.resetModules();+ }+}++describe('select-all barrier wait band', () => {+ test('matches the configured expect budget on CI', async () => {+ const { configured, helper } = await loadBand('1');+ expect(helper).toBe(configured);+ });++ test('matches the configured expect budget locally', async () => {+ const { configured, helper } = await loadBand(undefined);+ expect(helper).toBe(configured);+ });++ test('the CI band and the local band stay distinct, so neither regime can go vacuous', async () => {+ const ci = await loadBand('1');+ const local = await loadBand(undefined);+ expect(ci.helper).toBeGreaterThan(local.helper);+ });+});diff --git a/packages/app/tests/stress/_helpers/clipboard.ts b/packages/app/tests/stress/_helpers/clipboard.tsindex ee1c5493e..843cebe15 100644--- a/packages/app/tests/stress/_helpers/clipboard.ts+++ b/packages/app/tests/stress/_helpers/clipboard.ts@@ -17,11 +17,14 @@import type { Page } from '@playwright/test';import { selectAllAndWaitForSelection } from './editor-state';+const SOURCE_CONTENT_SELECTOR = '.source-editor .cm-content';+export async function simulateCopyAndRead(page: Page,view: 'wysiwyg' | 'source' = 'wysiwyg',): Promise<{ plain: string; html: string }> {- const selector = view === 'source' ? '.cm-content' : '.ProseMirror:not(.composer-prosemirror)';+ const selector =+ view === 'source' ? SOURCE_CONTENT_SELECTOR : '.ProseMirror:not(.composer-prosemirror)';await selectAllAndWaitForSelection(page, selector);return page.evaluate((sel) => {const editor = document.querySelector(sel) as HTMLElement | null;@@ -58,7 +61,8 @@ export async function simulateCutAndRead(page: Page,view: 'wysiwyg' | 'source' = 'wysiwyg',): Promise<{ plain: string; html: string; contentAfter: string }> {- const selector = view === 'source' ? '.cm-content' : '.ProseMirror:not(.composer-prosemirror)';+ const selector =+ view === 'source' ? SOURCE_CONTENT_SELECTOR : '.ProseMirror:not(.composer-prosemirror)';await selectAllAndWaitForSelection(page, selector);return page.evaluate((sel) => {const editor = document.querySelector(sel) as HTMLElement | null;diff --git a/packages/app/tests/stress/_helpers/editor-state.ts b/packages/app/tests/stress/_helpers/editor-state.tsindex 02e6fbaa8..b64267946 100644--- a/packages/app/tests/stress/_helpers/editor-state.ts+++ b/packages/app/tests/stress/_helpers/editor-state.ts@@ -1,14 +1,140 @@import { expect, type Page } from '@playwright/test';-export async function selectAllAndWaitForSelection(page: Page, selector: string): Promise<void> {+export const SELECT_ALL_SETTLE_TIMEOUT_MS = process.env.CI ? 15_000 : 5_000;++type ViewSelectionState = 'covers-document' | 'partial' | 'empty' | 'unreadable';++interface SelectAllProbe {+ matches: number;+ focusOwnedOnEntry: boolean;+ focusOwnedByEditor: boolean;+ activeElement: string;+ viewSelection: ViewSelectionState;+}++export function repairFocusAndReadProbe(sel: string): SelectAllProbe {+ const describe = (node: Element | null | undefined): string => {+ if (!node) return 'none';+ const first =+ typeof node.className === 'string' && node.className.trim().length > 0+ ? `.${node.className.trim().split(/\s+/)[0]}`+ : '';+ return `${node.tagName.toLowerCase()}${first}`;+ };+ const matches = document.querySelectorAll(sel).length;+ const editor = document.querySelector(sel);+ if (!editor) {+ return {+ matches,+ focusOwnedOnEntry: false,+ focusOwnedByEditor: false,+ activeElement: describe(document.activeElement),+ viewSelection: 'unreadable',+ };+ }+ const ownsFocus = (): boolean => document.activeElement === editor;+ const focusOwnedOnEntry = ownsFocus();+ if (!focusOwnedOnEntry && editor instanceof HTMLElement) editor.focus({ preventScroll: true });++ const classify = (from: unknown, to: unknown, docEnd: unknown): ViewSelectionState => {+ if (!Number.isInteger(from) || !Number.isInteger(to) || !Number.isInteger(docEnd)) {+ return 'unreadable';+ }+ if (from === 0 && to === docEnd) return 'covers-document';+ return from === to ? 'empty' : 'partial';+ };+ let viewSelection: ViewSelectionState = 'unreadable';+ const prosemirror = (+ window.__activeEditor as unknown as {+ editorView?: {+ dom?: Element;+ state?: {+ selection?: { from?: number; to?: number };+ doc?: { content?: { size?: number } };+ };+ };+ } | null+ )?.editorView;+ if (prosemirror && prosemirror.dom === editor) {+ viewSelection = classify(+ prosemirror.state?.selection?.from,+ prosemirror.state?.selection?.to,+ prosemirror.state?.doc?.content?.size,+ );+ } else {+ const handle = editor as Element & {+ cmTile?: { root?: { view?: unknown } };+ cmView?: { rootView?: { view?: unknown } };+ };+ const codemirror = (handle.cmTile?.root?.view ?? handle.cmView?.rootView?.view) as+ | {+ state?: {+ doc?: { length?: number };+ selection?: { main?: { from?: number; to?: number } };+ };+ }+ | undefined;+ if (codemirror) {+ viewSelection = classify(+ codemirror.state?.selection?.main?.from,+ codemirror.state?.selection?.main?.to,+ codemirror.state?.doc?.length,+ );+ }+ }++ return {+ matches,+ focusOwnedOnEntry,+ focusOwnedByEditor: ownsFocus(),+ activeElement: describe(document.activeElement),+ viewSelection,+ };+}++function repairFocusAndProbe(page: Page, selector: string): Promise<SelectAllProbe> {+ return page.evaluate(repairFocusAndReadProbe, selector);+}++/* Category C (select-all / focus flush) per precedent #20(a): the double-rAF yield this replaces+ established neither that DOM focus was committed before the key dispatch nor that select-all+ applied, so the helper could return with the view's selection in any state. */+export async function selectAllAndWaitForSelection(+ page: Page,+ selector: string,+ budgets: { focusMs?: number; selectionMs?: number } = {},+): Promise<void> {+ const focusMs = budgets.focusMs ?? SELECT_ALL_SETTLE_TIMEOUT_MS;+ const selectionMs = budgets.selectionMs ?? SELECT_ALL_SETTLE_TIMEOUT_MS;await page.focus(selector);- await page.keyboard.press('ControlOrMeta+a');- await page.evaluate(- () =>- new Promise<void>((resolve) => {- requestAnimationFrame(() => requestAnimationFrame(() => resolve()));- }),- );+ await expect+ .poll(() => repairFocusAndProbe(page, selector), {+ message: `selectAllAndWaitForSelection: "${selector}" never took DOM focus, so ControlOrMeta+A would land outside the editor`,+ timeout: focusMs,+ })+ .toMatchObject({+ focusOwnedByEditor: true,+ matches: expect.any(Number),+ activeElement: expect.any(String),+ });++ await expect+ .poll(+ async () => {+ await page.keyboard.press('ControlOrMeta+a');+ return repairFocusAndProbe(page, selector);+ },+ {+ message: `selectAllAndWaitForSelection: ControlOrMeta+A left no full-document selection in the view behind "${selector}"`,+ timeout: selectionMs,+ },+ )+ .toMatchObject({+ viewSelection: 'covers-document',+ focusOwnedOnEntry: expect.any(Boolean),+ matches: expect.any(Number),+ activeElement: expect.any(String),+ });}/**diff --git a/packages/app/tests/stress/_helpers/landing.ts b/packages/app/tests/stress/_helpers/landing.tsindex 5417dcf19..46f69212f 100644--- a/packages/app/tests/stress/_helpers/landing.ts+++ b/packages/app/tests/stress/_helpers/landing.ts@@ -60,11 +60,14 @@ function parseMark(raw: RawMarkPayload | null): LandingMark {export async function waitForLandingSettled(page: Page,- opts?: { since?: number; timeout?: number },+ opts: { since: number; timeout?: number },): Promise<LandingMark> {- const since = opts?.since ?? 0;+ const { since } = opts;await expect- .poll(() => landingMarkCount(page), { timeout: opts?.timeout ?? 10_000 })+ .poll(() => landingMarkCount(page), {+ message: `waitForLandingSettled: no terminal landing mark past ${since}; the mode switch either never started a landing or it was cancelled without one`,+ timeout: opts.timeout ?? 10_000,+ }).toBeGreaterThan(since);const raw = await page.evaluate(diff --git a/packages/app/tests/stress/blank-line-preservation.e2e.ts b/packages/app/tests/stress/blank-line-preservation.e2e.tsindex b7f4176e4..8151b57ac 100644--- a/packages/app/tests/stress/blank-line-preservation.e2e.ts+++ b/packages/app/tests/stress/blank-line-preservation.e2e.ts@@ -64,13 +64,13 @@ test.describe('blank lines typed in the visual editor', () => {await page.waitForSelector('.ProseMirror:not(.composer-prosemirror)');await expect.poll(() => countBlankParagraphs(page), { timeout: 10_000 }).toBe(3);- expect(await readSource(page)).toBe('Above.\n\n\n\n\nBelow.\n');+ await expect.poll(() => readSource(page), { timeout: 10_000 }).toBe('Above.\n\n\n\n\nBelow.\n');await page.reload();await waitForProvider(page);await page.waitForSelector('.ProseMirror:not(.composer-prosemirror)');await expect.poll(() => countBlankParagraphs(page), { timeout: 10_000 }).toBe(3);- expect(await readSource(page)).toBe('Above.\n\n\n\n\nBelow.\n');+ await expect.poll(() => readSource(page), { timeout: 10_000 }).toBe('Above.\n\n\n\n\nBelow.\n');});});diff --git a/packages/app/tests/stress/paste-fidelity.e2e.ts b/packages/app/tests/stress/paste-fidelity.e2e.tsindex 69b3e3383..6b07a6b4d 100644--- a/packages/app/tests/stress/paste-fidelity.e2e.ts+++ b/packages/app/tests/stress/paste-fidelity.e2e.ts@@ -127,7 +127,7 @@ test.describe('V1 paste baseline — text/plain content through WYSIWYG', () =>});});-test.describe('Copy-side: simulateCopyAndRead captures MIME map', () => {+test.describe('Copy-side: select-all barrier and simulateCopyAndRead MIME map', () => {let docName: string;test.beforeEach(async ({ page, api }) => {@@ -181,8 +181,64 @@ test.describe('Copy-side: simulateCopyAndRead captures MIME map', () => {});test('empty WYSIWYG selection copy → clipboard unchanged (FR-15)', async ({ page }) => {- const out = await simulateCopyAndRead(page, 'wysiwyg').catch(() => ({ plain: '', html: '' }));- expect(out.plain === '' || typeof out.plain === 'string').toBe(true);+ const out = await simulateCopyAndRead(page, 'wysiwyg');+ expect(out.plain).toBe('');+ });++ test('a persistent focus thief makes the select-all barrier throw instead of settling', async ({+ page,+ }) => {+ await page.click('.ProseMirror:not(.composer-prosemirror)');+ await pasteText(page, '# Thief\n\nBody that must not be silently lost.\n');+ await expect.poll(() => getYText(page), { timeout: 5_000 }).toContain('must not be silently');++ await page.evaluate((sel) => {+ const editor = document.querySelector<HTMLElement>(sel);+ if (!editor) throw new Error('focus-thief fixture: WYSIWYG editor not found');+ const thief = document.createElement('input');+ thief.setAttribute('data-testid', 'focus-thief');+ document.body.append(thief);+ editor.addEventListener('focus', () => thief.focus());+ thief.focus();+ }, '.ProseMirror:not(.composer-prosemirror)');++ await expect(+ selectAllAndWaitForSelection(page, '.ProseMirror:not(.composer-prosemirror)', {+ focusMs: 800,+ }),+ ).rejects.toThrow(/never took DOM focus/);+ });++ test('a swallowed select-all leaves a partial selection and makes the barrier throw', async ({+ page,+ }) => {+ await page.click('.ProseMirror:not(.composer-prosemirror)');+ await pasteText(page, '# Partial\n\nFirst body line.\n\nSecond body line.\n');+ await expect.poll(() => getYText(page), { timeout: 5_000 }).toContain('Second body line');++ await page.evaluate((sel) => {+ const editor = document.querySelector<HTMLElement>(sel);+ if (!editor) throw new Error('partial-selection fixture: WYSIWYG editor not found');+ document.addEventListener(+ 'keydown',+ (event) => {+ if (event.key.toLowerCase() === 'a' && (event.metaKey || event.ctrlKey)) {+ event.preventDefault();+ event.stopImmediatePropagation();+ }+ },+ true,+ );+ const active = window.__activeEditor;+ if (!active) throw new Error('partial-selection fixture: window.__activeEditor not set');+ active.chain().focus().setTextSelection({ from: 1, to: 5 }).run();+ }, '.ProseMirror:not(.composer-prosemirror)');++ await expect(+ selectAllAndWaitForSelection(page, '.ProseMirror:not(.composer-prosemirror)', {+ selectionMs: 800,+ }),+ ).rejects.toThrow(/left no full-document selection/);});});diff --git a/packages/app/tests/stress/qa-miles-edge-blanks.e2e.ts b/packages/app/tests/stress/qa-miles-edge-blanks.e2e.tsindex 906812b58..70a15d007 100644--- a/packages/app/tests/stress/qa-miles-edge-blanks.e2e.ts+++ b/packages/app/tests/stress/qa-miles-edge-blanks.e2e.ts@@ -67,13 +67,13 @@ test.describe('doc-edge blank runs at browser fidelity', () => {await visualToggle(page).click();await page.waitForSelector('.ProseMirror:not(.composer-prosemirror)');await expect.poll(() => countBlankParagraphs(page), { timeout: 10_000 }).toBe(4);- expect(await readSource(page)).toBe(expected);+ await expect.poll(() => readSource(page), { timeout: 10_000 }).toBe(expected);await page.reload();await waitForProvider(page);await page.waitForSelector('.ProseMirror:not(.composer-prosemirror)');await expect.poll(() => countBlankParagraphs(page), { timeout: 10_000 }).toBe(4);- expect(await readSource(page)).toBe(expected);+ await expect.poll(() => readSource(page), { timeout: 10_000 }).toBe(expected);});test('INV-11: blank lines typed at the tail in source mode appear in the visual editor', async ({@@ -92,6 +92,11 @@ test.describe('doc-edge blank runs at browser fidelity', () => {await visualToggle(page).click();await page.waitForSelector('.ProseMirror:not(.composer-prosemirror)');await expect.poll(() => countBlankParagraphs(page), { timeout: 10_000 }).toBe(2);- expect(await readSource(page), 'source bytes survive the toggle').toBe(expected);+ await expect+ .poll(() => readSource(page), {+ message: 'source bytes survive the toggle',+ timeout: 10_000,+ })+ .toBe(expected);});});diff --git a/packages/app/tests/stress/source-find-scroll.e2e.ts b/packages/app/tests/stress/source-find-scroll.e2e.tsindex c2b8c0e0a..5213d9908 100644--- a/packages/app/tests/stress/source-find-scroll.e2e.ts+++ b/packages/app/tests/stress/source-find-scroll.e2e.ts@@ -2,17 +2,18 @@ import { randomUUID } from 'node:crypto';import type { Page } from '@playwright/test';import {expect,+ landingMarkCount,matchIsWithinReadableScrollport,test,+ toggleMode,waitForActiveProviderSynced,+ waitForLandingSettled,} from './_helpers';function uniqueDocName(label: string): string {return `test-source-find-${label}-${randomUUID().slice(0, 8)}`;}-const sourceToggle = (page: Page) => page.getByRole('radio', { name: 'Markdown source' });-function visibleScrollContainer(page: Page) {return page.locator('[data-testid="editor-scroll-container"]:visible');}@@ -38,8 +39,9 @@ test('source-mode find scrolls an off-screen match into view', async ({ page, ap'Source Find Scroll',);- await sourceToggle(page).click();- await page.waitForSelector('.cm-content');+ const before = await landingMarkCount(page);+ await toggleMode(page, 'source');+ await waitForLandingSettled(page, { since: before, timeout: 6_000 });const scrollContainer = visibleScrollContainer(page);await expect(scrollContainer).toHaveCount(1);diff --git a/turbo.json b/turbo.jsonindex 160af2c79..c87e1b597 100644--- a/turbo.json+++ b/turbo.json@@ -148,6 +148,7 @@"src/**/*.tsx","tests/dom/**/*.ts","tests/dom/**/*.tsx",+ "tests/stress/_helpers/**/*.ts","tests/*.test-helper.ts","tests/integration/test-harness.ts","vitest.dom.config.ts",