Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(open-knowledge): mode-switch flash honesty and mis-landing pins (#3074)

Nick Gomezcb3b6ff79949
diff --git a/.changeset/mode-switch-honest-flash.md b/.changeset/mode-switch-honest-flash.md
new file mode 100644
index 000000000..51e008dc9
--- /dev/null
+++ b/.changeset/mode-switch-honest-flash.md
@@ -0,0 +1,7 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Switching to source mode no longer flashes the landing highlight on a block it could not verify, so a flash now always means you landed on the text you selected.
+
+The underlying mis-landing is unchanged for now: on documents whose editor block structure and markdown source disagree about how many top-level blocks exist (for example after deleting the paragraph between two bullet lists, which leaves two adjacent lists the markdown source cannot distinguish from one), the "View in source markdown" jump and the plain mode toggle can land one or more blocks past the intended target — one block for each such divergence in the document. Those unverified landings simply no longer paint the highlight.
diff --git a/packages/app/package.json b/packages/app/package.json
index 072a45057..998a82d1f 100644
--- a/packages/app/package.json
+++ b/packages/app/package.json
@@ -26,7 +26,7 @@
"measure:fuzz": "bash scripts/measure-fuzz.sh",
"measure:stress": "bash scripts/measure-stress.sh",
"perf:compare": "bash scripts/perf-compare.sh",
- "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts",
+ "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts",
"test:e2e:install-browsers": "playwright install chromium webkit firefox",
"test:visual": "playwright test --config playwright.visual.config.ts",
"test:visual:update": "playwright test --config playwright.visual.config.ts --update-snapshots",
diff --git a/packages/app/src/editor/block-spans.ts b/packages/app/src/editor/block-spans.ts
index 8c706dc92..150a0d27c 100644
--- a/packages/app/src/editor/block-spans.ts
+++ b/packages/app/src/editor/block-spans.ts
@@ -3,12 +3,23 @@
* decorations and cross-mode position mapping.
*
* Both surfaces need the same primitive: the alignment between the body's mdast
- * top-level blocks and the PM doc's top-level nodes. The bridge invariant makes
- * them 1:1 (Y.Text is truth; the fragment derives via parse), so a block's
- * ordinal is a representation-independent handle — provided the count-equality
- * tripwire (`comparableChildCount`) holds. This module is intentionally
- * dependency-light (no React, no floating-ui) so the resolver can build on it
- * without dragging in a decoration plugin's module graph.
+ * top-level blocks and the PM doc's top-level nodes. That alignment is NOT
+ * guaranteed. The bridge invariant is a byte check on the serialize side only,
+ * and on the WYSIWYG write path the fragment is the mutated structure — it is
+ * never re-derived via parse. Because `serialize` is non-injective at the top
+ * level, a WYSIWYG-authored fragment can hold shapes markdown cannot spell —
+ * adjacent same-kind `list` siblings, interior empty paragraphs — which
+ * `parse` merges or drops, shifting every ordinal after the collapse. Such
+ * divergence is PERSISTENT (it survives Observer A and persistence), not a
+ * mid-drain transient.
+ *
+ * The count-equality tripwire (`comparableChildCount`) detects a shifted count
+ * but is necessary, not sufficient: equal counts do not prove identity
+ * alignment. A consumer must not index an ordinal across the representation
+ * boundary when the tripwire fails — refuse the pass or re-locate by content;
+ * never index through. This module is intentionally dependency-light (no
+ * React, no floating-ui) so the resolver can build on it without dragging in a
+ * decoration plugin's module graph.
*/
import { type MarkdownManager, stripFrontmatter } from '@inkeep/open-knowledge-core';
diff --git a/packages/app/src/editor/extensions/markdown-lint-decorations.ts b/packages/app/src/editor/extensions/markdown-lint-decorations.ts
index 7a68d9f2f..d5c2d429b 100644
--- a/packages/app/src/editor/extensions/markdown-lint-decorations.ts
+++ b/packages/app/src/editor/extensions/markdown-lint-decorations.ts
@@ -12,10 +12,14 @@
* serialization normalizes away exactly the byte-level constructs many rules
* flag (hard tabs, trailing spaces, list-marker style, blank-line runs), so a
* serialize-then-lint pass can never see them and WYSIWYG would silently show
- * fewer problems than the panel. The mdast children of `parse(body)` line up
- * 1:1 with the doc's top-level nodes by the bridge invariant (Y.Text is truth;
- * the fragment derives via parse) — a transient mid-drain mismatch is detected
- * by block-count comparison and the pass is dropped, not misanchored.
+ * fewer problems than the panel. The mdast children of `parse(body)` usually
+ * line up 1:1 with the doc's top-level nodes; a mismatch is detected by
+ * block-count comparison and the pass is dropped, not misanchored. The
+ * mismatch is NOT always a mid-drain transient: a WYSIWYG-authored fragment
+ * can hold top-level shapes markdown cannot spell and diverge persistently
+ * (see the block-spans.ts module doc) — on such docs the dropped pass
+ * persists too, and block lint stays absent until the fragment is re-derived
+ * from bytes.
*
* Pool-safety: like `chunk-wrapper-decoration`, the plugin keys off `state.doc`
* (PM structure), never `documentName`, and adds NO Y.js observer (the CLAUDE.md
@@ -457,11 +461,13 @@ export const MarkdownLintDecorations = Extension.create<MarkdownLintDecorationsO
const diagnostics = await lintDocument(source, activeConfig, docName);
if (!view.state.doc.eq(doc)) return { kind: 'stale' };
const { spans } = computeSourceBlockSpans(source, md);
- // Bridge-invariant guard: body mdast children ↔ PM top-level nodes
+ // Alignment guard: body mdast children ↔ PM top-level nodes
// (minus the sourceless trailing empty paragraph) must be 1:1 for
- // the index mapping to anchor correctly. A mismatch is a transient
- // mid-drain snapshot — drop the pass (keep current decorations)
- // rather than misanchor.
+ // the index mapping to anchor correctly. Drop the pass (keep
+ // current decorations) rather than misanchor. Not always a
+ // mid-drain transient: WYSIWYG-authored shapes markdown cannot
+ // spell diverge persistently (see block-spans.ts), and the drop
+ // then persists with them.
if (spans.length !== comparableChildCount(doc)) return { kind: 'mismatch' };
const byBlock = mapDiagnosticsToBlocks(source, diagnostics, md);
return { kind: 'ok', ...buildDecorationSet(doc, byBlock) };
diff --git a/packages/app/src/editor/mode-switch-landing.ts b/packages/app/src/editor/mode-switch-landing.ts
index 20b3a8329..7f73afed1 100644
--- a/packages/app/src/editor/mode-switch-landing.ts
+++ b/packages/app/src/editor/mode-switch-landing.ts
@@ -481,7 +481,8 @@ export function startSourceLanding(params: {
? (outcome) => {
// Flash the whole block once it is genuinely on screen (the controller
// landed it), so the highlight's 2s clock measures visible time. A
- // clamped grade self-suppresses inside `flashSourceLanding`.
+ // clamped or unverified ordinal grade self-suppresses inside
+ // `flashSourceLanding`.
if (outcome.status === 'landed') {
flashSourceLanding(view, target.blockStart, target.blockEnd, target.confidence);
}
diff --git a/packages/app/src/editor/mode-switch-position-resolver.ts b/packages/app/src/editor/mode-switch-position-resolver.ts
index e99c6e9a2..e7bea7579 100644
--- a/packages/app/src/editor/mode-switch-position-resolver.ts
+++ b/packages/app/src/editor/mode-switch-position-resolver.ts
@@ -36,7 +36,9 @@ import {
* How much the resolver trusts a landing, most to least precise. `exact` is the
* only grade at which an inline (within-block) refinement is trustworthy;
* `clamped` means the block ordinal fell outside the target and the landing was
- * pulled to the nearest block, so the caller suppresses the highlight there.
+ * pulled to the nearest block. The caller suppresses the highlight on both
+ * `clamped` and `ordinal` — neither is content- or kind-verified (see
+ * `clampFlashRange`).
*/
export type ResolveConfidence = 'exact' | 'same-type-ordinal' | 'ordinal' | 'clamped';
diff --git a/packages/app/src/editor/plugins/landing-flash-shared.test.ts b/packages/app/src/editor/plugins/landing-flash-shared.test.ts
index 7c2e942d0..b53e9c33a 100644
--- a/packages/app/src/editor/plugins/landing-flash-shared.test.ts
+++ b/packages/app/src/editor/plugins/landing-flash-shared.test.ts
@@ -2,16 +2,18 @@ import { describe, expect, test } from 'vitest';
import { clampFlashRange } from './landing-flash-shared';
describe('clampFlashRange', () => {
- test('admits a range at a precise grade', () => {
+ test('admits a range at a verified grade', () => {
expect(clampFlashRange(100, 10, 20, 'exact')).toEqual({ from: 10, to: 20 });
expect(clampFlashRange(100, 10, 20, 'same-type-ordinal')).toEqual({ from: 10, to: 20 });
- expect(clampFlashRange(100, 10, 20, 'ordinal')).toEqual({ from: 10, to: 20 });
});
- test('refuses the flash at a clamped grade', () => {
- // A clamped landing could not place the target, so a flash there would
+ test('refuses the flash at an unverified grade', () => {
+ // A clamped landing could not place the target; an ordinal landing is an
+ // unverified guess that can sit on the wrong block entirely (a count
+ // mismatch shifts every ordinal below the collapse). Flashing either would
// assert a precision the landing does not have.
expect(clampFlashRange(100, 10, 20, 'clamped')).toBeNull();
+ expect(clampFlashRange(100, 10, 20, 'ordinal')).toBeNull();
});
test('clamps a range that runs past the document end', () => {
diff --git a/packages/app/src/editor/plugins/landing-flash-shared.ts b/packages/app/src/editor/plugins/landing-flash-shared.ts
index 3f32a9935..425f88903 100644
--- a/packages/app/src/editor/plugins/landing-flash-shared.ts
+++ b/packages/app/src/editor/plugins/landing-flash-shared.ts
@@ -16,11 +16,16 @@ export const OK_LANDING_FLASH_CLASS = 'ok-landing-flash';
/**
* Admit a landing range for a flash, or refuse it. A `clamped` grade means the
- * resolver could not place the target and fell back to a best-effort scroll, so
- * flashing there would assert a precision the landing does not have — refuse it.
- * The range is clamped to `[0, length]`; a range that collapses to empty after
- * clamping (or that arrives empty) is refused because an inline decoration over
- * a zero-width range has nothing to paint.
+ * resolver could not place the target and fell back to a best-effort scroll. An
+ * `ordinal` grade means the landing is an unverified ordinal guess: either the
+ * count tripwire failed (the two representations disagree about how many
+ * top-level blocks exist, so every ordinal after a collapse indexes the wrong
+ * block) or content and kind verification both missed at the target. Flashing
+ * either grade would assert "here is your text" over text that may not be the
+ * user's — refuse both; only content- or kind-verified landings get the
+ * precision signal. The range is clamped to `[0, length]`; a range that
+ * collapses to empty after clamping (or that arrives empty) is refused because
+ * an inline decoration over a zero-width range has nothing to paint.
*/
export function clampFlashRange(
length: number,
@@ -28,7 +33,7 @@ export function clampFlashRange(
to: number,
grade: ResolveConfidence,
): { from: number; to: number } | null {
- if (grade === 'clamped') return null;
+ if (grade === 'clamped' || grade === 'ordinal') return null;
const start = Math.max(0, Math.min(from, length));
const end = Math.max(start, Math.min(to, length));
if (end <= start) return null;
diff --git a/packages/app/src/editor/plugins/landing-flash-source.test.ts b/packages/app/src/editor/plugins/landing-flash-source.test.ts
index 2d3c36e97..abf59ef1f 100644
--- a/packages/app/src/editor/plugins/landing-flash-source.test.ts
+++ b/packages/app/src/editor/plugins/landing-flash-source.test.ts
@@ -58,6 +58,12 @@ describe('landing flash — source', () => {
expect(getState().field(landingFlashField).size).toBe(0);
});
+ test('suppresses the flash at an unverified ordinal grade', () => {
+ const { view, getState } = drivenView('alpha\nbeta\ngamma');
+ flashSourceLanding(view, 0, 5, 'ordinal');
+ expect(getState().field(landingFlashField).size).toBe(0);
+ });
+
test('clears the flash after the shared duration', () => {
vi.useFakeTimers();
const { view, getState } = drivenView('alpha\nbeta\ngamma');
diff --git a/packages/app/src/editor/plugins/landing-flash-source.ts b/packages/app/src/editor/plugins/landing-flash-source.ts
index 9b3d815e8..092bbcc61 100644
--- a/packages/app/src/editor/plugins/landing-flash-source.ts
+++ b/packages/app/src/editor/plugins/landing-flash-source.ts
@@ -61,9 +61,9 @@ const landingFlashCleanup = ViewPlugin.define((view) => ({
}));
/**
- * Flash the landed range and schedule its removal. A `clamped` grade suppresses
- * the flash (see `clampFlashRange`). Call this when the range is on screen; the
- * expiry timer starts here.
+ * Flash the landed range and schedule its removal. A `clamped` or unverified
+ * `ordinal` grade suppresses the flash (see `clampFlashRange`). Call this when
+ * the range is on screen; the expiry timer starts here.
*/
export function flashSourceLanding(
view: EditorView,
diff --git a/packages/app/src/editor/plugins/landing-flash-wysiwyg.test.ts b/packages/app/src/editor/plugins/landing-flash-wysiwyg.test.ts
index a252c70a0..706748263 100644
--- a/packages/app/src/editor/plugins/landing-flash-wysiwyg.test.ts
+++ b/packages/app/src/editor/plugins/landing-flash-wysiwyg.test.ts
@@ -101,6 +101,12 @@ describe('landing flash — wysiwyg trigger', () => {
expect(flashes(getState())).toHaveLength(0);
});
+ test('suppresses the flash at an unverified ordinal grade', () => {
+ const { view, getState } = drivenView();
+ flashWysiwygLanding(view, 1, 6, 'ordinal');
+ expect(flashes(getState())).toHaveLength(0);
+ });
+
test('flashes then clears after the shared duration', () => {
vi.useFakeTimers();
const { view, getState } = drivenView();
diff --git a/packages/app/src/editor/plugins/landing-flash-wysiwyg.ts b/packages/app/src/editor/plugins/landing-flash-wysiwyg.ts
index 70fd1f40f..9fe6e1dd9 100644
--- a/packages/app/src/editor/plugins/landing-flash-wysiwyg.ts
+++ b/packages/app/src/editor/plugins/landing-flash-wysiwyg.ts
@@ -72,9 +72,9 @@ export function createLandingFlashPlugin(): Plugin<DecorationSet> {
}
/**
- * Flash the landed range and schedule its removal. A `clamped` grade suppresses
- * the flash (see `clampFlashRange`). Call this when the range is on screen; the
- * expiry timer starts here.
+ * Flash the landed range and schedule its removal. A `clamped` or unverified
+ * `ordinal` grade suppresses the flash (see `clampFlashRange`). Call this when
+ * the range is on screen; the expiry timer starts here.
*/
export function flashWysiwygLanding(
view: EditorView,
diff --git a/packages/app/tests/stress/mode-switch-ordinal-divergence.e2e.ts b/packages/app/tests/stress/mode-switch-ordinal-divergence.e2e.ts
new file mode 100644
index 000000000..30debdb41
--- /dev/null
+++ b/packages/app/tests/stress/mode-switch-ordinal-divergence.e2e.ts
@@ -0,0 +1,265 @@
+/**
+ * Pins the OPEN mode-switch mis-landing on ordinal-divergent documents, plus
+ * the honest-flash behavior that ships while the mis-landing is open.
+ *
+ * Shape under test: the WYSIWYG fragment holds TWO ADJACENT `list` nodes, a
+ * top-level shape markdown cannot spell. `serialize` emits a blank line between
+ * the groups; `parse` merges them back into one list. Every top-level block
+ * after the collapse therefore sits one ordinal too far in the parsed-source
+ * block array the position resolver indexes into, so both the view-in-source
+ * jump and the plain mode toggle land one block past their target.
+ *
+ * FLIP CONTRACT — the `KNOWN-BUG` tests assert today's WRONG landings on
+ * purpose. When a fix lands (content-verified resolution or fragment
+ * normalization), they fail loudly; flip their landing assertions to the
+ * correct target and retitle them. They are written this way round, rather
+ * than as `test.fail()`, so a setup regression (the gesture failing to mint
+ * the divergent fragment) cannot be silently swallowed as an expected failure.
+ *
+ * The two-adjacent-lists state is NOT API-seedable (a markdown seed
+ * round-trips through `parse`, which merges), so each test mints it with a
+ * real WYSIWYG gesture: seed a paragraph between the two bullet groups, then
+ * delete it with real keyboard input.
+ */
+
+import { randomUUID } from 'node:crypto';
+import type { Page } from '@playwright/test';
+import {
+ expect,
+ landingMarkCount,
+ readSourceCaretHead,
+ scrollWysiwygBlockToTop,
+ selectText,
+ test,
+ toggleMode,
+ waitForActiveProviderSynced,
+ waitForLandingSettled,
+} from './_helpers';
+
+const WYSIWYG = '.ProseMirror:not(.composer-prosemirror)';
+const VIEW_IN_SOURCE_BUBBLE = 'view-in-source-bubble-button';
+const LANDING_FLASH = '.cm-editor .ok-landing-flash';
+
+/** Two bullet groups with an intervening paragraph the gesture deletes. */
+const SEED = [
+ 'cs',
+ '',
+ '- https://www.youtube.com/watch?v=0l5XgnQ6rB4 (yjs walkthrough)',
+ '- https://www.palanikannan.com/blogs/version-history-and-snapshots-in-yjs (yjs guide)',
+ '- https://fosdem.org/2026/schedule/event/8VKQXR-blocknote-yjs-prosemirror/ (yjs v14 talk)',
+ '',
+ 'SPLITMARKER',
+ '',
+ '- https://tailscale.com/blog/jailbroken-kindle-proxy-tun-modes (tailscale on a kindle?)',
+ '- https://mitchellh.com/writing (hashicorp guy)',
+ '',
+ 'research',
+ '',
+ '- https://arxiv.org/abs/2409.14252 (eg-walker paper)',
+ '- https://www.inkandswitch.com/essay/local-first/ (local-first design)',
+ '- https://30papers.com/ (foundational AI research/education list)',
+ '',
+ 'competitors',
+ '',
+ '- https://workbench.md/',
+ '- https://plane.so/wiki',
+ '',
+].join('\n');
+
+/** Blocks appended past the collapse point so a deep toggle has a real anchor. */
+const PADDING = `\n${Array.from(
+ { length: 120 },
+ (_, i) => `BLOCK-${String(i).padStart(3, '0')} padding paragraph`,
+).join('\n\n')}\n`;
+
+/** The trailing run of the research bullet the jump is invoked from. */
+const EOL_TAIL = 'g-walker paper)';
+
+function docName(label: string): string {
+ return `msod-${label}-${randomUUID().slice(0, 8)}`;
+}
+
+/** PM top-level child kinds + the live serialized source, read in-page. */
+async function ordinalTable(page: Page): Promise<{ pm: string[]; source: string }> {
+ return page.evaluate(() => {
+ const editor = window.__activeEditor;
+ if (!editor) throw new Error('no active editor');
+ const pm: string[] = [];
+ editor.state.doc.forEach((n: { type: { name: string }; textContent: string }) => {
+ pm.push(`${n.type.name}[${n.textContent.slice(0, 26)}]`);
+ });
+ const source = window.__activeProvider?.document?.getText('source')?.toString() ?? '';
+ return { pm, source };
+ });
+}
+
+/** Line (1-based) and text the source caret currently sits on. */
+async function caretLine(page: Page): Promise<{ line: number; text: string; head: number }> {
+ const head = await readSourceCaretHead(page);
+ const source = await page.evaluate(
+ () => window.__activeProvider?.document?.getText('source')?.toString() ?? '',
+ );
+ const before = source.slice(0, head);
+ const line = before.split('\n').length;
+ return { line, text: source.split('\n')[line - 1] ?? '', head };
+}
+
+/**
+ * Seed, open, then mint the two-adjacent-lists fragment with a real gesture:
+ * select the intervening paragraph and delete it with the keyboard.
+ */
+async function openSplitDoc(
+ page: Page,
+ api: { seedDocs: (d: Array<{ name: string; markdown: string }>) => Promise<void> },
+ name: string,
+ extra = '',
+): Promise<void> {
+ await api.seedDocs([{ name, markdown: SEED + extra }]);
+ await page.goto(`/#/${name}`);
+ await waitForActiveProviderSynced(page);
+ await expect(page.locator(WYSIWYG).first()).toBeVisible();
+
+ // Click into the paragraph first so the keystrokes below reach a focused
+ // editor; a programmatic selection alone can leave DOM focus elsewhere.
+ await page.locator(`${WYSIWYG} p`, { hasText: 'SPLITMARKER' }).first().click();
+ await selectText(page, 'SPLITMARKER');
+ await page.keyboard.press('Backspace'); // clears the text, leaves an empty paragraph
+ // Wait for the text deletion to land before the join keystroke — pressing both
+ // back to back races the first transaction and leaves one list.
+ await expect
+ .poll(async () => (await ordinalTable(page)).pm.join('|').includes('SPLITMARKER'), {})
+ .toBe(false);
+ await page.keyboard.press('Backspace'); // removes the now-empty paragraph
+
+ // The gesture is the whole point of the test — fail loudly if it did not mint
+ // two adjacent `list` nodes rather than silently testing the healthy shape.
+ await expect
+ .poll(async () => {
+ const { pm } = await ordinalTable(page);
+ return pm.some((k, i) => k.startsWith('list[') && (pm[i + 1] ?? '').startsWith('list['));
+ }, {})
+ .toBe(true);
+
+ // Wait for Observer A to push the serialized fragment back into Y.Text. This is
+ // the one poll here that crosses a server round-trip, so give it the same 10s
+ // ceiling as `waitForLandingSettled` rather than the 5s `expect` default —
+ // under CI contention a bare 5s can time out before propagation lands, which
+ // would surface as a setup error rather than the behavioral signal under test.
+ await expect
+ .poll(async () => (await ordinalTable(page)).source.includes('SPLITMARKER'), {
+ timeout: 10_000,
+ message: 'Observer A did not propagate the deletion from the fragment into Y.Text',
+ })
+ .toBe(false);
+}
+
+test('KNOWN-BUG: view-in-source jump lands one block past the target on a divergent doc; the unverified landing must not flash', async ({
+ page,
+ api,
+}) => {
+ const name = docName('jump');
+ await openSplitDoc(page, api, name);
+
+ await selectText(page, EOL_TAIL);
+ const bubble = page.getByTestId(VIEW_IN_SOURCE_BUBBLE);
+ await expect(bubble, 'the View in source bubble entry did not appear').toBeVisible();
+
+ const before = await landingMarkCount(page);
+ await bubble.click();
+ const mark = await waitForLandingSettled(page, { since: before });
+ expect(mark.kind, `jump did not land (grade ${mark.grade})`).toBe('land');
+
+ const landed = await caretLine(page);
+ const flashes = await page.locator(LANDING_FLASH).count();
+ console.log(
+ `landing: grade=${mark.grade} caret head=${landed.head} -> line ${landed.line}: ${JSON.stringify(landed.text)}, flash spans=${flashes}`,
+ );
+
+ // The resolver detects the divergence (count tripwire) and grades the landing
+ // an unverified ordinal. Flip on a regrading fix: fragment normalization clears
+ // the count mismatch and lifts this to `exact`/`same-type-ordinal`; a fix that
+ // only corrects placement while leaving the grade `ordinal` keeps it as-is.
+ expect(mark.grade).toBe('ordinal');
+
+ // Flash presence is a function of grade (`clampFlashRange`) AND settle
+ // outcome — only a landing that reached `landed` dispatches the flash at all,
+ // which is why the `kind` assertion above is load-bearing: without it an
+ // abandoned settle satisfies zero-flash for free. This flips WITH the grade
+ // above, not unconditionally: keep `toBe(0)` only while the landing stays an
+ // unverified `ordinal`; any fix that lifts the grade to a verified one
+ // restores the flash — flip to `toBeGreaterThan(0)` and assert the span
+ // covers the landed block.
+ expect(flashes, 'an ordinal-grade landing must not paint the landing flash').toBe(0);
+
+ // KNOWN BUG (flip on fix): the caret lands on `competitors`, one top-level
+ // block past the selected research bullet. A fix must land it on the line
+ // containing `arxiv.org/abs/2409.14252` instead.
+ expect(
+ landed.text,
+ 'landing moved off the known-wrong block — the mis-landing may be fixed; flip this assertion to the correct target',
+ ).toContain('competitors');
+});
+
+test('KNOWN-BUG: the plain mode toggle mis-anchors by one block on a divergent doc', async ({
+ page,
+ api,
+}) => {
+ // The short doc fits on one screen, so its topmost block is always ordinal 0,
+ // which resolves correctly even under a shift. Pad past the collapse point so
+ // the toggle has a deep block to preserve.
+ const name = docName('toggle');
+ await openSplitDoc(page, api, name, PADDING);
+
+ const anchor = 'BLOCK-060';
+ const residual = await scrollWysiwygBlockToTop(page, anchor);
+ expect(Math.abs(residual), 'setup scroll did not converge').toBeLessThan(40);
+
+ const before = await landingMarkCount(page);
+ await toggleMode(page, 'source');
+ const mark = await waitForLandingSettled(page, { since: before });
+ expect(mark.kind, `toggle did not land (grade ${mark.grade})`).toBe('land');
+
+ // The `kind` assertion above rules out an abandoned settle (the controller
+ // stamps the same resolve-time grade on land and abandon marks); the grade
+ // then pins that the divergent setup fired the count tripwire, so the
+ // mis-anchor below is the ordinal-divergence this test is named for. Flip
+ // semantics match the jump test's grade assertion above.
+ expect(mark.grade).toBe('ordinal');
+
+ // Read the source line sitting at the top of the readable area through
+ // CodeMirror's own coordinate lookup, the way the landing oracle does.
+ const topLine = await page.evaluate(() => {
+ const scroller = Array.from(
+ document.querySelectorAll<HTMLElement>('[data-testid="editor-scroll-container"]'),
+ ).find((el) => el.getClientRects().length > 0);
+ if (!scroller) throw new Error('no visible scroll container');
+ const content = Array.from(document.querySelectorAll<HTMLElement>('.cm-editor'))
+ .find((el) => el.getClientRects().length > 0)
+ ?.querySelector('.cm-content');
+ const handle = content as
+ | (Element & {
+ cmTile?: { root?: { view?: unknown } };
+ cmView?: { rootView?: { view?: unknown } };
+ })
+ | null;
+ const view = (handle?.cmTile?.root?.view ?? handle?.cmView?.rootView?.view) as
+ | {
+ posAtCoords: (c: { x: number; y: number }, precise: boolean) => number;
+ state: { doc: { lineAt: (p: number) => { number: number; text: string } } };
+ }
+ | undefined;
+ if (!view) throw new Error('no CodeMirror view');
+ const box = scroller.getBoundingClientRect();
+ const pos = view.posAtCoords({ x: box.left + 40, y: box.top + 56 + 4 }, false);
+ const line = view.state.doc.lineAt(pos);
+ return `L${line.number}: ${line.text}`;
+ });
+ console.log(`toggle: grade=${mark.grade} anchored=${anchor} topmost=${JSON.stringify(topLine)}`);
+
+ // KNOWN BUG (flip on fix): the toggle shows the block AFTER the anchored one
+ // at the top of the readable area. A fix must keep `anchor` in view.
+ expect(
+ topLine,
+ 'the toggle preserved the anchored block — the mis-anchor may be fixed; flip this assertion to require the anchor',
+ ).not.toContain(anchor);
+});