Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): place the e2e caret through the editor before typing (#4774)
Nick Gomez35c25d07aaa2
diff --git a/knip.config.ts b/knip.config.tsindex 659eef71e..5b8951125 100644--- a/knip.config.ts+++ b/knip.config.ts@@ -143,15 +143,11 @@ export default {'packages/server': {entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],project: 'src/**',- ignoreDependencies: [- '@types/shell-quote',- ],+ ignoreDependencies: ['@types/shell-quote'],},'packages/cli': {entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],- ignoreDependencies: [- 'yjs',- ],+ ignoreDependencies: ['yjs'],},'packages/desktop': {entry: [diff --git a/packages/app/tests/dom/caret-placement-barrier.dom.test.ts b/packages/app/tests/dom/caret-placement-barrier.dom.test.tsnew file mode 100644index 000000000..be7c9f57f--- /dev/null+++ b/packages/app/tests/dom/caret-placement-barrier.dom.test.ts@@ -0,0 +1,401 @@+import type { Page } from '@playwright/test';+import { afterEach, describe, expect, test, vi } from 'vitest';+import { placeCaretAtEndOfText } from '../stress/_helpers/editor-state';++const TARGET = 'Above.';+const INTENDED_CARET = 7;+const STALE_CARET = 1;++type Reading = { from: number; to: number; focused: boolean };++const placed: Reading = { from: INTENDED_CARET, to: INTENDED_CARET, focused: true };+const drifted: Reading = { from: 3, to: 9, focused: false };++function scriptedEditor(readings: Reading[], text = TARGET) {+ let cursor = 0;+ const current = (): Reading => readings[Math.min(cursor, readings.length - 1)];+ const drives: number[] = [];+ const editor = {+ state: {+ doc: {+ descendants(visit: (node: { isText: boolean; text?: string }, pos: number) => boolean) {+ visit({ isText: true, text }, 1);+ },+ },+ get selection() {+ const reading = current();+ return { from: reading.from, to: reading.to, empty: reading.from === reading.to };+ },+ },+ view: {+ hasFocus: () => current().focused,+ },+ chain() {+ return {+ focus: () => ({+ setTextSelection: ({ from }: { from: number }) => {+ drives.push(from);+ return { run: () => true };+ },+ }),+ };+ },+ };+ return {+ editor,+ drives,+ advance() {+ cursor += 1;+ },+ };+}++function timeoutError(timeoutMs: number): Error {+ const error = new Error(`page.waitForFunction: Timeout ${timeoutMs}ms exceeded.`);+ error.name = 'TimeoutError';+ return error;+}++function barrierHandle(settled: unknown, dispose: () => Promise<void> = async () => {}) {+ return {+ jsonValue: async () => settled,+ dispose,+ };+}++function collectedDisposer(): () => Promise<void> {+ return async () => {+ throw new Error('The object has been collected to prevent unbounded heap growth.');+ };+}++function unreadableBarrierPage(+ unreadable: Error,+ dispose: () => Promise<void> = async () => {},+): Page {+ return {+ evaluate: async (fn: (arg: unknown) => unknown, arg: unknown) => fn(arg),+ waitForFunction: async (fn: (arg: unknown) => unknown, arg: unknown) => {+ fn(arg);+ return {+ jsonValue: async () => {+ throw unreadable;+ },+ dispose,+ };+ },+ } as unknown as Page;+}++function jsdomPage(+ rig: ReturnType<typeof scriptedEditor>,+ pollBudget = 8,+ onPoll: (satisfied: boolean) => void = () => {},+ dispose: () => Promise<void> = async () => {},+): Page {+ return {+ evaluate: async (fn: (arg: unknown) => unknown, arg: unknown) => fn(arg),+ waitForFunction: async (+ fn: (arg: unknown) => unknown,+ arg: unknown,+ options: { timeout?: number } = {},+ ) => {+ for (let poll = 0; poll < pollBudget; poll += 1) {+ const settled = fn(arg);+ rig.advance();+ onPoll(Boolean(settled));+ if (settled) return barrierHandle(settled, dispose);+ }+ throw timeoutError(options.timeout ?? 0);+ },+ } as unknown as Page;+}++function pageThatStopsAnswering(+ rig: ReturnType<typeof scriptedEditor>,+ afterBarrier: () => Promise<never>,+): Page {+ let answering = true;+ const live = jsdomPage(rig, 1, () => {+ answering = false;+ }) as unknown as {+ evaluate: (fn: (arg: unknown) => unknown, arg: unknown) => Promise<unknown>;+ waitForFunction: (+ fn: (arg: unknown) => unknown,+ arg: unknown,+ options: unknown,+ ) => Promise<unknown>;+ };+ return {+ evaluate: (fn: (arg: unknown) => unknown, arg: unknown) =>+ answering ? live.evaluate(fn, arg) : afterBarrier(),+ waitForFunction: live.waitForFunction,+ } as unknown as Page;+}++function installEditor(editor: unknown): void {+ vi.stubGlobal('__activeEditor', editor);+}++function install(rig: ReturnType<typeof scriptedEditor>): void {+ installEditor(rig.editor);+}++function uninstall(): void {+ vi.stubGlobal('__activeEditor', undefined);+}++afterEach(() => {+ vi.unstubAllGlobals();+ (window as unknown as { __caretBarrierProbe?: unknown }).__caretBarrierProbe = undefined;+});++describe('placeCaretAtEndOfText barrier', () => {+ test('returns only once every conjunct of the predicate holds', async () => {+ const rig = scriptedEditor([+ { from: STALE_CARET, to: STALE_CARET, focused: true },+ { from: INTENDED_CARET, to: INTENDED_CARET, focused: false },+ placed,+ ]);+ install(rig);++ const placement = await placeCaretAtEndOfText(jsdomPage(rig), TARGET);++ expect(placement).toEqual({+ pmCaret: INTENDED_CARET,+ pmCaretTo: INTENDED_CARET,+ intendedCaret: INTENDED_CARET,+ editorOwnsDomFocus: true,+ });+ });++ test('returns the reading that satisfied the barrier, not one taken after it', async () => {+ const rig = scriptedEditor([placed, drifted]);+ install(rig);++ const placement = await placeCaretAtEndOfText(jsdomPage(rig), TARGET);++ expect(rig.editor.state.selection).toEqual({+ from: drifted.from,+ to: drifted.to,+ empty: false,+ });+ expect(rig.editor.view.hasFocus()).toBe(drifted.focused);+ expect(placement).toEqual({+ pmCaret: INTENDED_CARET,+ pmCaretTo: INTENDED_CARET,+ intendedCaret: INTENDED_CARET,+ editorOwnsDomFocus: true,+ });+ });++ test('keeps waiting while the editor still reports the stale caret', async () => {+ const rig = scriptedEditor([{ from: STALE_CARET, to: STALE_CARET, focused: true }]);+ install(rig);++ await expect(placeCaretAtEndOfText(jsdomPage(rig), TARGET)).rejects.toThrow(+ /gave up after \d+ms with selection-not-at-caret\b.*\bfrom=1 to=1 empty=true focused=true/,+ );+ });++ test('keeps waiting while the selection is anchored at the caret but spans a range', async () => {+ const rig = scriptedEditor([{ from: INTENDED_CARET, to: INTENDED_CARET + 2, focused: true }]);+ install(rig);++ await expect(placeCaretAtEndOfText(jsdomPage(rig), TARGET)).rejects.toThrow(+ /gave up after \d+ms with selection-not-collapsed\b.*\bfrom=7 to=9 empty=false focused=true/,+ );+ });++ test('keeps waiting while a collapsed caret sits at the position without focus', async () => {+ const rig = scriptedEditor([{ from: INTENDED_CARET, to: INTENDED_CARET, focused: false }]);+ install(rig);++ await expect(placeCaretAtEndOfText(jsdomPage(rig), TARGET)).rejects.toThrow(+ /gave up after \d+ms with editor-lacks-dom-focus\b.*\bfrom=7 to=7 empty=true focused=false/,+ );+ });++ test('re-drives the intended caret on every unsatisfied poll', async () => {+ const rig = scriptedEditor([{ from: STALE_CARET, to: STALE_CARET, focused: true }]);+ install(rig);++ await expect(placeCaretAtEndOfText(jsdomPage(rig, 3), TARGET)).rejects.toThrow(+ /gave up after \d+ms with selection-not-at-caret/,+ );++ expect(rig.drives).toEqual([INTENDED_CARET, INTENDED_CARET, INTENDED_CARET, INTENDED_CARET]);+ });++ test('names a barrier handle it could not read back rather than a barrier timeout', async () => {+ const rig = scriptedEditor([placed]);+ install(rig);+ const unreadable = new Error('Target page, context or browser has been closed');+ const disposals: string[] = [];+ const page = unreadableBarrierPage(unreadable, async () => {+ disposals.push('disposed');+ });++ const failure = await placeCaretAtEndOfText(page, TARGET).catch((reason: unknown) => reason);++ expect(failure).toBeInstanceOf(Error);+ expect((failure as Error).message).toMatch(+ /the caret barrier held for intended caret 7, but the placement it settled on could not be read back off the barrier handle: Target page, context or browser has been closed/,+ );+ expect((failure as Error).message).not.toMatch(/gave up after/);+ expect((failure as Error).cause).toBe(unreadable);+ expect(disposals).toEqual(['disposed']);+ });++ test('disposes the barrier handle once it has read the placement back', async () => {+ const rig = scriptedEditor([placed]);+ install(rig);+ const disposals: string[] = [];+ const record = async () => {+ disposals.push('disposed');+ };++ const placement = await placeCaretAtEndOfText(+ jsdomPage(rig, 8, () => {}, record),+ TARGET,+ );++ expect(placement.pmCaret).toBe(INTENDED_CARET);+ expect(disposals).toEqual(['disposed']);+ });++ test('returns the placement it read back even when disposing the handle fails', async () => {+ const rig = scriptedEditor([placed]);+ install(rig);++ const placement = await placeCaretAtEndOfText(+ jsdomPage(rig, 8, () => {}, collectedDisposer()),+ TARGET,+ );++ expect(placement).toEqual({+ pmCaret: INTENDED_CARET,+ pmCaretTo: INTENDED_CARET,+ intendedCaret: INTENDED_CARET,+ editorOwnsDomFocus: true,+ });+ });++ test('keeps the unreadable-handle failure and its cause when disposal fails too', async () => {+ const rig = scriptedEditor([placed]);+ install(rig);+ const unreadable = new Error(+ 'Execution context was destroyed, most likely because of a navigation',+ );++ const failure = await placeCaretAtEndOfText(+ unreadableBarrierPage(unreadable, collectedDisposer()),+ TARGET,+ ).catch((reason: unknown) => reason);++ expect((failure as Error).message).toMatch(+ /could not be read back off the barrier handle: Execution context was destroyed/,+ );+ expect((failure as Error).message).toMatch(+ /disposing the barrier handle afterwards also failed: The object has been collected to prevent unbounded heap growth\./,+ );+ expect((failure as Error).cause).toBe(unreadable);+ });++ test('names an editor handle lost mid-poll without fabricating a reading', async () => {+ const rig = scriptedEditor([{ from: STALE_CARET, to: STALE_CARET, focused: true }]);+ install(rig);+ const page = jsdomPage(rig, 4, (satisfied) => {+ if (!satisfied) uninstall();+ });++ const failure = await placeCaretAtEndOfText(page, TARGET).catch((reason: unknown) => reason);++ expect((failure as Error).message).toMatch(+ /gave up after \d+ms with editor-handle-absent\b.*\bno editor handle, so it read no selection to report/,+ );+ expect((failure as Error).message).not.toMatch(/from=/);+ });++ test('reports a predicate rejection as a rejection, carrying the causing message', async () => {+ const rig = scriptedEditor([placed]);+ installEditor({+ ...rig.editor,+ view: new Proxy(+ {},+ {+ get: (_target, key) => {+ throw new Error(+ `[tiptap error]: The editor view is not available. Cannot access view['${String(key)}']. The editor may not be mounted yet.`,+ );+ },+ },+ ),+ });++ await expect(placeCaretAtEndOfText(jsdomPage(rig), TARGET)).rejects.toThrow(+ /rejected before its \d+ms budget with no poll reading recorded for intended caret 7; the rejection was: \[tiptap error\]: The editor view is not available\. Cannot access view\['hasFocus'\]/,+ );+ });++ test('separates a read that outran the recovery budget from a reading never recorded', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ try {+ const rig = scriptedEditor([{ from: STALE_CARET, to: STALE_CARET, focused: true }]);+ install(rig);++ const rejected = expect(+ placeCaretAtEndOfText(+ pageThatStopsAnswering(rig, () => new Promise<never>(() => {})),+ TARGET,+ ),+ ).rejects.toThrow(+ /gave up after \d+ms with the poll reading for intended caret 7 could not be read back: the read outran this helper's own \d+ms recovery budget/,+ );+ await vi.advanceTimersByTimeAsync(60_000);+ await rejected;+ } finally {+ vi.useRealTimers();+ }+ });++ test('separates a read the page rejected from a reading never recorded', async () => {+ const rig = scriptedEditor([{ from: STALE_CARET, to: STALE_CARET, focused: true }]);+ install(rig);+ const closed = pageThatStopsAnswering(rig, () =>+ Promise.reject(new Error('Target page, context or browser has been closed')),+ );++ await expect(placeCaretAtEndOfText(closed, TARGET)).rejects.toThrow(+ /gave up after \d+ms with the poll reading for intended caret 7 could not be read back: Target page, context or browser has been closed/,+ );+ });++ test('refuses text that is not in the document instead of placing nothing', async () => {+ const rig = scriptedEditor([placed]);+ install(rig);++ await expect(placeCaretAtEndOfText(jsdomPage(rig), 'Nowhere')).rejects.toThrow(+ /not found within a single text node/,+ );+ expect(rig.drives).toEqual([]);+ });++ test('refuses text that occurs more than once rather than silently taking the first', async () => {+ const rig = scriptedEditor([placed], `${TARGET} and again ${TARGET}`);+ install(rig);++ await expect(placeCaretAtEndOfText(jsdomPage(rig), TARGET)).rejects.toThrow(+ /occurs 2 times, so the caret this places is the first occurrence/,+ );+ expect(rig.drives).toEqual([]);+ });++ test('refuses when the editor handle is absent', async () => {+ const rig = scriptedEditor([placed]);++ await expect(placeCaretAtEndOfText(jsdomPage(rig), TARGET)).rejects.toThrow(+ /__activeEditor not set/,+ );+ });+});diff --git a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts b/packages/app/tests/integration/bug3-source-mode-writeback.test.tsindex a28cc2b18..8a60e5826 100644--- a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts+++ b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts@@ -1,4 +1,3 @@-import { readFileSync } from 'node:fs';import { join } from 'node:path';import { setTimeout as wait } from 'node:timers/promises';diff --git a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts b/packages/app/tests/integration/indented-jsx-byte-sacred.test.tsindex 4fc2c11f9..6fcdc23f2 100644--- a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts+++ b/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts@@ -1,4 +1,3 @@-import { setTimeout as wait } from 'node:timers/promises';import { normalizeBridge } from '@inkeep/open-knowledge-core';import { updateYFragment } from '@tiptap/y-tiptap';diff --git a/packages/app/tests/integration/interior-edit-freshness.test.ts b/packages/app/tests/integration/interior-edit-freshness.test.tsindex 9f2f6feb6..40b5cdfd6 100644--- a/packages/app/tests/integration/interior-edit-freshness.test.ts+++ b/packages/app/tests/integration/interior-edit-freshness.test.ts@@ -1,4 +1,3 @@-import { setTimeout as wait } from 'node:timers/promises';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';import { afterAll, beforeAll, describe, expect, test } from 'vitest';diff --git a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts b/packages/app/tests/integration/keystroke-cadence-danger-space.test.tsindex 2a085742b..93666af70 100644--- a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts+++ b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts@@ -1,4 +1,3 @@-import { setTimeout as wait } from 'node:timers/promises';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';import { afterAll, beforeAll, describe, expect, test } from 'vitest';diff --git a/packages/app/tests/integration/producer-guard-wiring.test.ts b/packages/app/tests/integration/producer-guard-wiring.test.tsindex 878d5196b..867598d34 100644--- a/packages/app/tests/integration/producer-guard-wiring.test.ts+++ b/packages/app/tests/integration/producer-guard-wiring.test.ts@@ -1,4 +1,3 @@-import { setTimeout as wait } from 'node:timers/promises';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';import { afterAll, beforeAll, describe, expect, test } from 'vitest';diff --git a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.tsindex 4ada3cf26..0970ac12f 100644--- a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts+++ b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts@@ -1,4 +1,3 @@-import { randomUUID } from 'node:crypto';import { afterEach, describe, expect, test } from 'vitest';import { agentWriteMd, createTestServer, type TestServer } from './test-harness';diff --git a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts b/packages/app/tests/integration/qa-045-restore-after-gc.test.tsindex cbe2b705f..b632185e1 100644--- a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts+++ b/packages/app/tests/integration/qa-045-restore-after-gc.test.ts@@ -1,4 +1,3 @@-import { execFileSync } from 'node:child_process';import { randomUUID } from 'node:crypto';import { join } from 'node:path';diff --git a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.tsindex 89bc9b4d9..c530ce4ba 100644--- a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts+++ b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts@@ -1,4 +1,3 @@-import { randomUUID } from 'node:crypto';import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest';import type * as Y from 'yjs';diff --git a/packages/app/tests/integration/undo-after-rollback.test.ts b/packages/app/tests/integration/undo-after-rollback.test.tsindex a78aeb0e4..d3767adc9 100644--- a/packages/app/tests/integration/undo-after-rollback.test.ts+++ b/packages/app/tests/integration/undo-after-rollback.test.ts@@ -1,4 +1,3 @@-import { ROLLBACK_ORIGIN } from '@inkeep/open-knowledge-server';import { afterAll, beforeAll, describe, expect, test } from 'vitest';import * as Y from 'yjs';diff --git a/packages/app/tests/integration/undo-recycle-reset.test.ts b/packages/app/tests/integration/undo-recycle-reset.test.tsindex e7cc69c3f..b076f955c 100644--- a/packages/app/tests/integration/undo-recycle-reset.test.ts+++ b/packages/app/tests/integration/undo-recycle-reset.test.ts@@ -1,4 +1,3 @@-import { writeFileSync } from 'node:fs';import { join } from 'node:path';import { setTimeout as wait } from 'node:timers/promises';diff --git a/packages/app/tests/integration/undo-rederive-survival.test.ts b/packages/app/tests/integration/undo-rederive-survival.test.tsindex 9ddcd0730..7935e35f8 100644--- a/packages/app/tests/integration/undo-rederive-survival.test.ts+++ b/packages/app/tests/integration/undo-rederive-survival.test.ts@@ -1,4 +1,3 @@-import { prependFrontmatter } from '@inkeep/open-knowledge-core';import { Plugin, PluginKey } from '@tiptap/pm/state';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';diff --git a/packages/app/tests/stress/_helpers/editor-state.ts b/packages/app/tests/stress/_helpers/editor-state.tsindex be227d51c..b86247397 100644--- a/packages/app/tests/stress/_helpers/editor-state.ts+++ b/packages/app/tests/stress/_helpers/editor-state.ts@@ -1,4 +1,4 @@-import { expect, type Page } from '@playwright/test';+import { expect, type JSHandle, type Page } from '@playwright/test';export const SELECT_ALL_SETTLE_TIMEOUT_MS = process.env.CI ? 15_000 : 5_000;@@ -255,6 +255,183 @@ export async function selectText(page: Page, text: string): Promise<void> {);}+const CARET_BARRIER_PROBE_READ_TIMEOUT_MS = 1_000;++interface CaretBarrierReading {+ from: number;+ to: number;+ empty: boolean;+ focused: boolean;+}++type CaretBarrierProbe =+ | { unsatisfied: 'editor-handle-absent' }+ | (CaretBarrierReading & {+ unsatisfied: 'selection-not-at-caret' | 'selection-not-collapsed' | 'editor-lacks-dom-focus';+ });++interface CaretBarrierProbeWindow {+ __caretBarrierProbe?: CaretBarrierProbe;+}++type CaretBarrierProbeRead =+ | { kind: 'reading'; probe: CaretBarrierProbe }+ | { kind: 'none' }+ | { kind: 'unreadable'; why: string };++async function readCaretBarrierProbe(page: Page): Promise<CaretBarrierProbeRead> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ return await Promise.race([+ page+ .evaluate(() => (window as typeof window & CaretBarrierProbeWindow).__caretBarrierProbe)+ .then(+ (probe): CaretBarrierProbeRead => (probe ? { kind: 'reading', probe } : { kind: 'none' }),+ )+ .catch(+ (cause: unknown): CaretBarrierProbeRead => ({+ kind: 'unreadable',+ why: cause instanceof Error ? cause.message : String(cause),+ }),+ ),+ new Promise<CaretBarrierProbeRead>((resolve) => {+ timer = setTimeout(+ () =>+ resolve({+ kind: 'unreadable',+ why: `the read outran this helper's own ${CARET_BARRIER_PROBE_READ_TIMEOUT_MS}ms recovery budget`,+ }),+ CARET_BARRIER_PROBE_READ_TIMEOUT_MS,+ );+ }),+ ]);+ } finally {+ clearTimeout(timer);+ }+}++export interface CaretPlacement {+ pmCaret: number;+ pmCaretTo: number;+ intendedCaret: number;+ editorOwnsDomFocus: boolean;+}++/** Category C (caret placement / focus flush) per precedent #20(a). */+export async function placeCaretAtEndOfText(+ page: Page,+ text: string,+ timeoutMs = 5_000,+): Promise<CaretPlacement> {+ const intendedCaret = await page.evaluate((target) => {+ (window as typeof window & CaretBarrierProbeWindow).__caretBarrierProbe = undefined;+ const editor = window.__activeEditor;+ if (!editor) throw new Error('placeCaretAtEndOfText: window.__activeEditor not set');+ let caret = -1;+ let matches = 0;+ editor.state.doc.descendants((node, pos) => {+ const nodeText = node.isText ? node.text : undefined;+ if (!nodeText) return true;+ for (let offset = nodeText.indexOf(target); offset !== -1; ) {+ matches += 1;+ if (caret === -1) caret = pos + offset + target.length;+ offset = nodeText.indexOf(target, offset + 1);+ }+ return true;+ });+ if (caret === -1) {+ throw new Error(`placeCaretAtEndOfText: "${target}" not found within a single text node`);+ }+ if (matches > 1) {+ throw new Error(+ `placeCaretAtEndOfText: "${target}" occurs ${matches} times, so the caret this places is the first occurrence and no caller can tell it from the one they meant`,+ );+ }+ editor.chain().focus().setTextSelection({ from: caret, to: caret }).run();+ return caret;+ }, text);++ let barrier: JSHandle<CaretPlacement | false>;+ try {+ barrier = await page.waitForFunction(+ (caret): CaretPlacement | false => {+ const probe = window as typeof window & CaretBarrierProbeWindow;+ const editor = window.__activeEditor;+ if (!editor) {+ probe.__caretBarrierProbe = { unsatisfied: 'editor-handle-absent' };+ return false;+ }+ const { from, to, empty } = editor.state.selection;+ const focused = editor.view.hasFocus();+ const unsatisfied =+ from !== caret+ ? 'selection-not-at-caret'+ : !empty+ ? 'selection-not-collapsed'+ : !focused+ ? 'editor-lacks-dom-focus'+ : null;+ if (unsatisfied === null) {+ return {+ pmCaret: from,+ pmCaretTo: to,+ intendedCaret: caret,+ editorOwnsDomFocus: focused,+ };+ }+ probe.__caretBarrierProbe = { unsatisfied, from, to, empty, focused };+ editor.chain().focus().setTextSelection({ from: caret, to: caret }).run();+ return false;+ },+ intendedCaret,+ { timeout: timeoutMs },+ );+ } catch (cause) {+ const read = await readCaretBarrierProbe(page);+ const reading =+ read.kind === 'reading'+ ? read.probe.unsatisfied === 'editor-handle-absent'+ ? `editor-handle-absent still unsatisfied for intended caret ${intendedCaret}; the last poll held no editor handle, so it read no selection to report`+ : `${read.probe.unsatisfied} still unsatisfied for intended caret ${intendedCaret}; the last poll read from=${read.probe.from} to=${read.probe.to} empty=${read.probe.empty} focused=${read.probe.focused}`+ : read.kind === 'none'+ ? `no poll reading recorded for intended caret ${intendedCaret}`+ : `the poll reading for intended caret ${intendedCaret} could not be read back: ${read.why}`;+ throw new Error(+ cause instanceof Error && cause.name === 'TimeoutError'+ ? `placeCaretAtEndOfText: the caret barrier gave up after ${timeoutMs}ms with ${reading}`+ : `placeCaretAtEndOfText: the caret barrier rejected before its ${timeoutMs}ms budget with ${reading}; the rejection was: ${cause instanceof Error ? cause.message : String(cause)}`,+ { cause },+ );+ }++ const read = await barrier.jsonValue().then(+ (settled) => ({ ok: true as const, settled }),+ (cause: unknown) => ({ ok: false as const, cause }),+ );+ const disposalFailure = await barrier.dispose().then(+ () => undefined,+ (reason: unknown) => reason,+ );++ if (!read.ok) {+ const disposalReport =+ disposalFailure === undefined+ ? ''+ : `; disposing the barrier handle afterwards also failed: ${disposalFailure instanceof Error ? disposalFailure.message : String(disposalFailure)}`;+ throw new Error(+ `placeCaretAtEndOfText: the caret barrier held for intended caret ${intendedCaret}, but the placement it settled on could not be read back off the barrier handle: ${read.cause instanceof Error ? read.cause.message : String(read.cause)}${disposalReport}`,+ { cause: read.cause },+ );+ }++ if (read.settled === false) {+ throw new Error(+ `placeCaretAtEndOfText: the caret barrier for intended caret ${intendedCaret} resolved on the value its own predicate returns while unsatisfied, so no placement was ever taken`,+ );+ }+ return read.settled;+}+/** Category C per precedent #20(a). *//* WARN: walks `$from` ancestors, so it can never match a NodeSelection; a caller arming aNodeSelection needs its own predicate. */diff --git a/packages/app/tests/stress/_helpers/index.ts b/packages/app/tests/stress/_helpers/index.tsindex ba59fac7c..d43b0a0ed 100644--- a/packages/app/tests/stress/_helpers/index.ts+++ b/packages/app/tests/stress/_helpers/index.ts@@ -6,7 +6,9 @@ export {export { simulateCopyAndRead, simulateCutAndRead } from './clipboard.ts';export { resetContentToFixtureBaseline } from './content-reset.ts';export {+ type CaretPlacement,focusEditor,+ placeCaretAtEndOfText,primeFullLayout,selectAllAndWaitForSelection,selectText,diff --git a/packages/app/tests/stress/blank-line-preservation.e2e.ts b/packages/app/tests/stress/blank-line-preservation.e2e.tsindex 8151b57ac..76275ca75 100644--- a/packages/app/tests/stress/blank-line-preservation.e2e.ts+++ b/packages/app/tests/stress/blank-line-preservation.e2e.ts@@ -1,6 +1,17 @@import { randomUUID } from 'node:crypto';import type { Page } from '@playwright/test';-import { expect, test, waitForActiveProviderSynced as waitForProvider } from './_helpers';+import {+ type CaretPlacement,+ expect,+ placeCaretAtEndOfText,+ test,+ waitForActiveProviderSynced as waitForProvider,+} from './_helpers';++const ABOVE_PARAGRAPH = 'Above.';+const BELOW_PARAGRAPH = 'Below.';+const SEED_SOURCE = `${ABOVE_PARAGRAPH}\n\n${BELOW_PARAGRAPH}\n`;+const ABSENT_PARAGRAPH = 'Nowhere in this document.';const sourceToggle = (page: Page) => page.getByRole('radio', { name: 'Markdown source' });const visualToggle = (page: Page) => page.getByRole('radio', { name: 'Visual editor' });@@ -19,13 +30,21 @@ function countBlankParagraphs(page: Page): Promise<number> {});}+function readPmSelection(page: Page): Promise<{ from: number; to: number }> {+ return page.evaluate(() => {+ const editor = window.__activeEditor;+ if (!editor) throw new Error('readPmSelection: window.__activeEditor not set');+ return { from: editor.state.selection.from, to: editor.state.selection.to };+ });+}+test.describe('blank lines typed in the visual editor', () => {let docName: string;test.beforeEach(async ({ page, api }) => {docName = `test-blank-lines-${randomUUID().slice(0, 8)}`;await api.createPage(`${docName}.md`);- await api.replaceDoc(docName, 'Above.\n\nBelow.\n');+ await api.replaceDoc(docName, SEED_SOURCE);await page.goto(`/#/${docName}`);await waitForProvider(page);await page.waitForSelector('.ProseMirror:not(.composer-prosemirror)');@@ -39,19 +58,42 @@ test.describe('blank lines typed in the visual editor', () => {);});+ test('the returned placement is what the editor independently reports', async ({ page }) => {+ const placement: CaretPlacement = await placeCaretAtEndOfText(page, ABOVE_PARAGRAPH);+ const live = await readPmSelection(page);++ expect(+ { from: placement.pmCaret, to: placement.pmCaretTo },+ `placeCaretAtEndOfText returned ${placement.pmCaret}-${placement.pmCaretTo}, but the editor independently reports ${live.from}-${live.to}. The helper owes the reading its own barrier accepted, and this is a separate, later read, so the break is in that promise or in the window after it: the selection moved, or the editor was swapped, before this read`,+ ).toEqual(live);+ expect(+ placement.pmCaret,+ `the editor settled at ${placement.pmCaret} rather than the intended ${placement.intendedCaret}. Enter runs TipTap's splitBlock, which reads tr.selection and never the DOM, so a key dispatched from here splits wherever ProseMirror still believes the caret is`,+ ).toBe(placement.intendedCaret);+ expect(+ placement.editorOwnsDomFocus,+ 'caret placement resolved without the editor holding DOM focus, so keys pressed after it would not reach the editor at all',+ ).toBe(true);+ });++ test('caret placement refuses absent text and leaves the selection where it was', async ({+ page,+ }) => {+ const anchored: CaretPlacement = await placeCaretAtEndOfText(page, ABOVE_PARAGRAPH);+ const before = await readPmSelection(page);++ await expect(+ placeCaretAtEndOfText(page, ABSENT_PARAGRAPH),+ `"${ABSENT_PARAGRAPH}" is not in the seeded document, so the helper owes a rejection rather than a return: a caller that presses a key after an unplaced caret splits wherever the editor's selection happened to be, which is the defect this helper exists to close`,+ ).rejects.toThrow(/not found within a single text node/);+ expect(+ await readPmSelection(page),+ `a refused placement moved ProseMirror's selection off ${anchored.intendedCaret}, so the caller is left with a caret this helper relocated on its way to failing`,+ ).toEqual(before);+ });+test('survive a source-mode round trip and a reload', async ({ page }) => {- const firstParagraph = page- .locator('.ProseMirror:not(.composer-prosemirror)')- .getByText('Above.', { exact: true });- await firstParagraph.evaluate((paragraph) => {- paragraph.closest<HTMLElement>('.ProseMirror')?.focus();- const selection = window.getSelection();- const range = document.createRange();- range.selectNodeContents(paragraph);- range.collapse(false);- selection?.removeAllRanges();- selection?.addRange(range);- });+ await placeCaretAtEndOfText(page, ABOVE_PARAGRAPH);await page.keyboard.press('Enter');await page.keyboard.press('Enter');await page.keyboard.press('Enter');diff --git a/packages/app/tsconfig.json b/packages/app/tsconfig.jsonindex eaef5e89b..63124f485 100644--- a/packages/app/tsconfig.json+++ b/packages/app/tsconfig.json@@ -58,12 +58,27 @@// its parameter. It imports `@playwright/test` and// `@inkeep/open-knowledge-core`, whose declarations `src` already pulls into// the program, so its closure adds no other file to it.+ //+ // `tests/stress/_helpers/editor-state.ts` is named for the same reason. It+ // pins the `CaretPlacement` shape `placeCaretAtEndOfText` returns: four+ // required fields, so the barrier predicate that constructs it fails to+ // compile if a field is dropped or carries the wrong type (TS2322) or is+ // misnamed (TS2561), rather than surfacing as a wrong number at an+ // assertion. The pin stops+ // there: a construction that supplies all four with the right types is+ // accepted whatever the values mean. Playwright's runner transforms+ // `.ts` without typechecking it, so without this entry nothing checks the+ // type the barrier's callers narrow against. It imports only+ // `@playwright/test`, so its closure adds no other file to the program. The+ // `.e2e.ts` and `.dom.test.ts` consumers stay outside: the former would pull+ // the whole `_helpers` barrel in, and the latter is excluded as `*.test.ts`."include": ["src","*.ts","tests/stress/fixtures","tests/half-open-forced-close.test-helper.ts","tests/stress/_helpers/acp-catalog.ts",+ "tests/stress/_helpers/editor-state.ts","tests/stress/_helpers/image.ts","tests/stress/_helpers/theme-fade.ts"],diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.tsindex 2a597ec3d..f4cc8a286 100644--- a/packages/core/src/bridge/compose.ts+++ b/packages/core/src/bridge/compose.ts@@ -1,4 +1,3 @@-import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.tsindex 01ef76a9f..8fb428b90 100644--- a/packages/core/src/bridge/doc-boundary-space.ts+++ b/packages/core/src/bridge/doc-boundary-space.ts@@ -1,4 +1,3 @@-import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.tsindex fb0ba5a7c..fc267cbea 100644--- a/packages/core/src/markdown/comment-promoter.ts+++ b/packages/core/src/markdown/comment-promoter.ts@@ -1,4 +1,3 @@-import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.tsindex fa3cfcd86..bfd7e3109 100644--- a/packages/core/src/markdown/merged-walker.ts+++ b/packages/core/src/markdown/merged-walker.ts@@ -1,4 +1,3 @@-import type { Nodes, Parent, Root } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.tsindex 8be632ba4..4d3250d3a 100644--- a/packages/core/src/markdown/safe-url.ts+++ b/packages/core/src/markdown/safe-url.ts@@ -1,4 +1,3 @@-export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');