Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Record editor display-lock state on renderer crash dumps (PRD-8158) (#3921)

Andrew Mikofalvyf670151403b3
diff --git a/.changeset/display-lock-crash-key.md b/.changeset/display-lock-crash-key.md
new file mode 100644
index 000000000..97219d0dd
--- /dev/null
+++ b/.changeset/display-lock-crash-key.md
@@ -0,0 +1,15 @@
+---
+"@inkeep/open-knowledge": minor
+---
+
+Crash reports from the desktop app now record what the editor's block-level `content-visibility` was doing when a renderer died.
+
+One class of renderer crash aborts inside Chromium when a click lands on content whose ancestor has just been made unpaintable. The minidump in a bug report carries the faulting stack but nothing about the page, so triage could establish that the crash happened and not whether the editor's block wrappers were changing state at the time. That gap made the difference between a diagnosis and an informed guess.
+
+The renderer now keeps a small crash key current as those blocks change state, and a bug report that carries a crash dump surfaces whatever the dump captured. Reports that carry no dump are unchanged, and a report from a renderer that never published a value says so explicitly rather than reading as "nothing was happening".
+
+The reading also says whether it was current. A crash during a burst of changes is recorded differently from one that happened long after the last change, so a value in a report cannot be mistaken for evidence that something was happening at the moment of the crash when it was not.
+
+It covers the editor's block wrappers only. The other place the app uses this CSS feature cannot report state changes at all, by design of the underlying browser event, so a crash there records nothing about that site rather than something misleading.
+
+What is recorded is a short fixed-shape string of counters and flags. It carries no document content, no file paths, and no user data. It appears in the crash dump and, like other diagnostic decisions, in the desktop log that any bug report bundles.
diff --git a/knip.config.ts b/knip.config.ts
index b61debe5e..8ad68f996 100644
--- a/knip.config.ts
+++ b/knip.config.ts
@@ -124,7 +124,9 @@ 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'],
diff --git a/packages/app/src/editor/display-lock-crash-key.test.ts b/packages/app/src/editor/display-lock-crash-key.test.ts
new file mode 100644
index 000000000..5eaf2fb22
--- /dev/null
+++ b/packages/app/src/editor/display-lock-crash-key.test.ts
@@ -0,0 +1,272 @@
+/**
+ * @covers-unit src/editor/display-lock-crash-key.ts
+ *
+ * The publish path is the thing under test, not the encoding alone. Three ways
+ * this diagnostic could be worse than nothing, each pinned below: it goes quiet
+ * under load (silent exactly when it matters), it keeps writing after the
+ * editor is gone (a stale reading in a dump gets trusted), or it publishes a
+ * value that cannot be dated relative to the crash (residue from a scroll
+ * minutes earlier reads identically to a burst in flight).
+ */
+
+import { describe, expect, test } from 'vitest';
+import {
+ type DisplayLockSnapshot,
+ encodeDisplayLockState,
+ startDisplayLockCrashKeyReporter,
+} from './display-lock-crash-key.ts';
+import { OK_CHUNK_WRAPPER_CLASS } from './extensions/chunk-wrapper-decoration.ts';
+
+/**
+ * Conservative byte ceiling the desktop bridge enforces before handing a value
+ * to Crashpad. Asserted as an inequality with real margin rather than pinned to
+ * the bridge's exact constant: the app cannot import from the desktop package,
+ * and an equality across that boundary would be a drift hazard where a bound
+ * with headroom is not.
+ */
+const BRIDGE_BYTE_CEILING = 127;
+
+/** Minimal stand-in for an element; only `classList.contains` is read. */
+function elementWithClass(className: string): { classList: { contains(t: string): boolean } } {
+ return { classList: { contains: (token: string) => token === className } };
+}
+
+/**
+ * Built from the class the decoration extension actually stamps, not a third
+ * copy of the literal: the whole diagnostic hinges on the reporter matching
+ * that exact string, and a rename there would otherwise leave this test green
+ * while the reporter silently matched nothing.
+ */
+const chunkWrapper = () => elementWithClass(OK_CHUNK_WRAPPER_CLASS);
+
+/** A root that records its listener so tests can dispatch straight into it. */
+function fakeRoot() {
+ let handler: ((event: Event) => void) | null = null;
+ return {
+ root: {
+ addEventListener(_type: string, listener: (event: Event) => void) {
+ handler = listener;
+ },
+ removeEventListener() {
+ handler = null;
+ },
+ },
+ attached: () => handler !== null,
+ fire(target: unknown, skipped: boolean) {
+ handler?.({ target, skipped } as unknown as Event);
+ },
+ };
+}
+
+/** Reporter wired to collectors, with frames run manually. */
+function harness() {
+ const published: string[] = [];
+ const frames: Array<() => void> = [];
+ const root = fakeRoot();
+ const stop = startDisplayLockCrashKeyReporter({
+ root: root.root,
+ publish: (s) => published.push(s),
+ schedule: (run) => frames.push(run),
+ });
+ return {
+ published,
+ frames,
+ stop,
+ fire: root.fire,
+ attached: root.attached,
+ /** Run the next queued frame callback, if any. */
+ tick: () => frames.shift()?.(),
+ };
+}
+
+describe('encodeDisplayLockState', () => {
+ test('names the lock direction and whether the burst had settled', () => {
+ expect(encodeDisplayLockState({ locked: true, inFrame: 3, total: 12, settled: false })).toBe(
+ 'v1 lock=1 f=3 n=12 s=0',
+ );
+ expect(encodeDisplayLockState({ locked: false, inFrame: 1, total: 4, settled: true })).toBe(
+ 'v1 lock=0 f=1 n=4 s=1',
+ );
+ });
+
+ test('counters saturate rather than grow, keeping the value bounded', () => {
+ const huge: DisplayLockSnapshot = {
+ locked: true,
+ inFrame: Number.MAX_SAFE_INTEGER,
+ total: Number.MAX_SAFE_INTEGER,
+ settled: false,
+ };
+ expect(encodeDisplayLockState(huge)).toBe('v1 lock=1 f=99999 n=99999 s=0');
+ expect(encodeDisplayLockState(huge).length).toBeLessThan(BRIDGE_BYTE_CEILING);
+ // Real margin, not a squeak past the ceiling: a value the bridge drops is a
+ // diagnostic that silently stops reporting.
+ expect(encodeDisplayLockState(huge).length).toBeLessThan(60);
+ });
+
+ test('nonsense counters degrade to zero instead of into the encoding', () => {
+ expect(
+ encodeDisplayLockState({ locked: true, inFrame: Number.NaN, total: -5, settled: false }),
+ ).toBe('v1 lock=1 f=0 n=0 s=0');
+ });
+});
+
+describe('startDisplayLockCrashKeyReporter', () => {
+ test('declines without throwing when there is no window to read a bridge from', () => {
+ // Passing no `publish` drives the module down its real bridge-lookup path,
+ // which reads a global. In a node environment that global is absent, and an
+ // unguarded read throws `ReferenceError` rather than yielding undefined.
+ //
+ // `window` is DELETED here rather than left to chance: sibling suites leak a
+ // `globalThis.window`, and under that leak this case passes while exercising
+ // nothing. That is exactly how the bug escaped once already — the file was
+ // green alone and red in the full run.
+ const hadWindow = 'window' in globalThis;
+ const saved = (globalThis as { window?: unknown }).window;
+ delete (globalThis as { window?: unknown }).window;
+ try {
+ const root = fakeRoot();
+ let stop: (() => void) | undefined;
+ expect(() => {
+ stop = startDisplayLockCrashKeyReporter({ root: root.root });
+ }).not.toThrow();
+ expect(root.attached(), 'with no sink, no listener may be attached at all').toBe(false);
+ expect(() => stop?.()).not.toThrow();
+ } finally {
+ // Restoring is not optional: a leaked deletion would break every later
+ // suite in this process that expects the DOM global to be present.
+ if (hadWindow) (globalThis as { window?: unknown }).window = saved;
+ }
+ });
+
+ test('coalesces a burst of transitions into one publish per frame', () => {
+ const h = harness();
+ for (let i = 0; i < 40; i += 1) h.fire(chunkWrapper(), true);
+ expect(h.published, 'nothing may publish before the frame runs').toEqual([]);
+ expect(h.frames, 'a burst must schedule exactly one flush').toHaveLength(1);
+
+ h.tick();
+ expect(h.published).toEqual(['v1 lock=1 f=40 n=40 s=0']);
+ });
+
+ test('republishes once, marked settled, on the first frame with no transitions', () => {
+ // This is what makes a reading datable. Without it, a burst from a scroll
+ // minutes before the crash is indistinguishable from one in flight during
+ // the crashing frame.
+ const h = harness();
+ h.fire(chunkWrapper(), true);
+ h.tick();
+ expect(h.published).toEqual(['v1 lock=1 f=1 n=1 s=0']);
+
+ h.tick();
+ expect(h.published).toEqual(['v1 lock=1 f=1 n=1 s=0', 'v1 lock=1 f=1 n=1 s=1']);
+
+ // And exactly once — a settled burst must not keep rewriting the key.
+ expect(h.frames, 'settling must not re-arm another frame').toHaveLength(0);
+ });
+
+ test('a burst that keeps going never publishes a settled reading', () => {
+ const h = harness();
+ h.fire(chunkWrapper(), true);
+ h.tick(); // publishes the first frame, live
+ h.fire(chunkWrapper(), false); // arrives during the settle frame
+ h.tick(); // must publish the new transitions, not a settled marker
+
+ expect(h.published).toEqual(['v1 lock=1 f=1 n=1 s=0', 'v1 lock=0 f=1 n=2 s=0']);
+ });
+
+ test('a new burst after settling publishes live again', () => {
+ const h = harness();
+ h.fire(chunkWrapper(), true);
+ h.tick();
+ h.tick(); // settles
+ h.fire(chunkWrapper(), true);
+ h.tick();
+
+ expect(h.published).toEqual([
+ 'v1 lock=1 f=1 n=1 s=0',
+ 'v1 lock=1 f=1 n=1 s=1',
+ 'v1 lock=1 f=1 n=2 s=0',
+ ]);
+ });
+
+ test('counts each frame separately while accumulating the running total', () => {
+ const h = harness();
+ h.fire(chunkWrapper(), true);
+ h.fire(chunkWrapper(), true);
+ h.tick();
+ h.fire(chunkWrapper(), false);
+ h.tick();
+
+ expect(h.published).toEqual(['v1 lock=1 f=2 n=2 s=0', 'v1 lock=0 f=1 n=3 s=0']);
+ });
+
+ test('ignores elements that are not chunk wrappers, including the pane site', () => {
+ // `.ok-mode-hidden` is `content-visibility: hidden`, so it cannot fire this
+ // event at all — an earlier draft mapped it anyway, which was dead code that
+ // would have made a pane crash look like a chunk-wrapper one. Pinned so the
+ // mapping cannot come back by accident.
+ const h = harness();
+ h.fire(elementWithClass('ok-mode-hidden'), true);
+ h.fire(elementWithClass('some-other-class'), true);
+ h.fire(null, true);
+ expect(h.frames, 'a non-chunk-wrapper target must not even schedule a frame').toHaveLength(0);
+ expect(h.published).toEqual([]);
+ });
+
+ test('a throwing sink cannot break the frame loop or inflate later counts', () => {
+ // `publish` crosses the contextBridge into a native binding, so a throw is
+ // a real possibility rather than a hypothetical. Two things must hold: the
+ // throw does not escape into the rAF callback (where it would recur every
+ // frame for a whole scroll burst), and the frame's bookkeeping still
+ // completes, so `f` counts that frame's transitions rather than
+ // accumulating every failed frame's into the next reading.
+ const published: string[] = [];
+ const frames: Array<() => void> = [];
+ let failNext = true;
+ const root = fakeRoot();
+ startDisplayLockCrashKeyReporter({
+ root: root.root,
+ publish: (s) => {
+ if (failNext) {
+ failNext = false;
+ throw new Error('bridge exploded');
+ }
+ published.push(s);
+ },
+ schedule: (run) => frames.push(run),
+ });
+
+ root.fire(chunkWrapper(), true);
+ root.fire(chunkWrapper(), true);
+ expect(() => frames.shift()?.()).not.toThrow();
+ expect(published, 'the failed publish produced no reading').toEqual([]);
+
+ // The settle republish must still happen for a burst whose own publish
+ // threw. `s` is the only field that dates a reading, so a refactor that
+ // marked a burst live only after a SUCCESSFUL publish — which reads as
+ // tightening — would leave one bridge throw permanently suppressing that
+ // burst's settled marker, and the dump would carry a stale `s=0` forever.
+ frames.shift()?.();
+ expect(published).toEqual(['v1 lock=1 f=2 n=2 s=1']);
+
+ // And the next burst reports ONLY its own transitions, not the failed
+ // frame's accumulated on top.
+ root.fire(chunkWrapper(), true);
+ frames.shift()?.();
+ expect(published).toEqual(['v1 lock=1 f=2 n=2 s=1', 'v1 lock=1 f=1 n=3 s=0']);
+ });
+
+ test('stop detaches the listener and neuters a frame already in flight', () => {
+ const h = harness();
+ h.fire(chunkWrapper(), true);
+ expect(h.frames).toHaveLength(1);
+
+ h.stop();
+ expect(h.attached(), 'stop must remove the listener').toBe(false);
+
+ // The frame callback was queued before stop and still runs; it must not
+ // write a reading for an editor that is gone.
+ h.tick();
+ expect(h.published).toEqual([]);
+ });
+});
diff --git a/packages/app/src/editor/display-lock-crash-key.ts b/packages/app/src/editor/display-lock-crash-key.ts
new file mode 100644
index 000000000..437e140af
--- /dev/null
+++ b/packages/app/src/editor/display-lock-crash-key.ts
@@ -0,0 +1,266 @@
+/**
+ * Publishes editor `content-visibility: auto` relevance transitions as a
+ * desktop crash key, so a renderer abort can be told apart from a renderer that
+ * merely died near one.
+ *
+ * WHY THIS EXISTS. Blink hard-CHECKs in `HitTestResult::GetPosition()` when a
+ * click's hit-tested node has a paint-blocked ANCESTOR. OK stamps
+ * `.ok-chunk-wrapper` (`content-visibility: auto`) on every top-level
+ * ProseMirror block, and a minidump carries the faulting stack but nothing
+ * about renderer DOM or CSS state — so when that abort shows up in the field,
+ * whether a chunk wrapper was flipping relevance at the time is exactly the
+ * question triage cannot answer, and the one this key answers.
+ *
+ * SCOPE: CHUNK WRAPPERS ONLY, AND THAT IS A HARD LIMIT, NOT A CHOICE.
+ * `contentvisibilityautostatechange` fires only for elements whose own
+ * `content-visibility` is `auto` — Blink schedules it behind
+ * `state_ == EContentVisibility::kAuto` in
+ * `DisplayLockContext::ScheduleStateChangeEventIfNeeded`. OK's other
+ * display-lock site, `.ok-mode-hidden`, is `content-visibility: hidden`, so it
+ * can never fire this event and is structurally outside what this key can see.
+ * An earlier draft mapped that class too; the arm was dead, and worse, on a
+ * `.ok-mode-hidden` crash the key would have carried leftover chunk-wrapper
+ * state and invited triage to read it as relevant. Covering the pane site would
+ * need a different mechanism (its class flip is React state, not this event)
+ * and is deliberately not attempted here.
+ *
+ * WHY IT IS CONTINUOUS RATHER THAN CAPTURED AT CRASH TIME. The CHECK is an
+ * immediate process abort. No JS runs after it fires, so there is no crash
+ * handler to ask. The only value that reaches the dump is the one last written
+ * before the abort.
+ *
+ * WHY A READING CAN BE DATED. A high-water mark alone would be untriageable: a
+ * burst from a scroll minutes earlier and a burst in flight during the crashing
+ * frame would publish identical values. So a burst publishes `s=0` (live), and
+ * the first frame afterwards with no new transitions republishes `s=1`
+ * (settled). A dump carrying `s=0` says a transition burst had not finished
+ * when the process died; `s=1` says the last burst had already settled. That
+ * costs one extra write per burst, not per frame.
+ *
+ * WHY CAPTURE PHASE ON A ROOT, NOT PER-ELEMENT LISTENERS. A capture-phase
+ * listener on an ancestor fires for events dispatched at any descendant whether
+ * or not the event bubbles, so one listener covers every wrapper without
+ * depending on the event's bubbling behavior and without attaching hundreds of
+ * listeners that ProseMirror's decorations would churn.
+ *
+ * WHY IT COALESCES PER FRAME. Scrolling a long document produces transitions in
+ * bursts — a mid-document jump measured ~100 in one go — and
+ * `content-visibility: auto` exists here for render performance, so this must
+ * not become the thing that costs it. Transitions fold into one pending
+ * snapshot published at most once per animation frame, and nothing is published
+ * while the document is idle.
+ */
+
+import { OK_CHUNK_WRAPPER_CLASS } from './extensions/chunk-wrapper-decoration.ts';
+
+export interface DisplayLockSnapshot {
+ /** True when the most recent transition was INTO the paint lock. */
+ locked: boolean;
+ /** Transitions folded into the frame being published. */
+ inFrame: number;
+ /** Transitions observed since the reporter started. */
+ total: number;
+ /**
+ * True once a frame has passed with no further transitions. A dump carrying
+ * `false` died with a burst still in flight.
+ */
+ settled: boolean;
+}
+
+/**
+ * Ceiling on every published counter.
+ *
+ * Counters exist to say "a burst was in flight", not to be exact, so they
+ * saturate rather than grow. Saturating is what makes the encoded value's
+ * length provably bounded, which is what keeps it clear of the byte ceiling the
+ * desktop bridge enforces — a value over that ceiling is dropped, and a
+ * diagnostic that silently stops publishing under load would be worse than
+ * none, because load is exactly when it matters.
+ */
+const COUNTER_CEILING = 99_999;
+
+function saturate(n: number): number {
+ if (!Number.isFinite(n) || n < 0) return 0;
+ return n > COUNTER_CEILING ? COUNTER_CEILING : Math.floor(n);
+}
+
+/**
+ * Encode a snapshot as the compact ASCII string the crash key carries.
+ *
+ * Versioned so a dump read years from now is self-describing: `v1` means
+ * chunk-wrapper cv:auto transitions with these four fields, and a later shape
+ * changes the prefix rather than silently redefining them. Fixed field set and
+ * saturated counters make the maximum length a constant, which
+ * `display-lock-crash-key.test.ts` pins against the bridge's budget.
+ */
+export function encodeDisplayLockState(snapshot: DisplayLockSnapshot): string {
+ const lock = snapshot.locked ? '1' : '0';
+ const settled = snapshot.settled ? '1' : '0';
+ return `v1 lock=${lock} f=${saturate(snapshot.inFrame)} n=${saturate(snapshot.total)} s=${settled}`;
+}
+
+/**
+ * Structural minimum this module needs from an event target.
+ *
+ * Deliberately not `instanceof Element`. Nothing here needs an `Element` — one
+ * `classList.contains` call is the whole requirement — and structural typing
+ * keeps the module loadable wherever it is imported, including the node test
+ * tier, without a DOM shim standing in for a check it never had to make. It
+ * reads the same property either way.
+ */
+interface ClassListBearing {
+ classList: { contains(token: string): boolean };
+}
+
+function isChunkWrapper(target: EventTarget | null): boolean {
+ const classList = (target as ClassListBearing | null)?.classList;
+ if (typeof classList?.contains !== 'function') return false;
+ return classList.contains(OK_CHUNK_WRAPPER_CLASS);
+}
+
+/** The listener surface this module needs from its root. */
+interface ListenerTarget {
+ addEventListener(
+ type: string,
+ listener: (event: Event) => void,
+ options?: { capture?: boolean },
+ ): void;
+ removeEventListener(
+ type: string,
+ listener: (event: Event) => void,
+ options?: { capture?: boolean },
+ ): void;
+}
+
+/**
+ * The desktop bridge's crash-key writer, or undefined when there is none.
+ *
+ * `typeof window` rather than a bare `window.okDesktop`: this module's unit
+ * tests run in the node environment, where the global does not exist and a
+ * direct read throws `ReferenceError` rather than yielding undefined. Same
+ * guard `main.tsx` uses to read the bridge at startup.
+ */
+function desktopSink(): ((state: string) => void) | undefined {
+ if (typeof window === 'undefined') return undefined;
+ // Capability check, not just a host check — the same reasoning
+ // `BackgroundThrottleReporter` records for its own bridge channel. The
+ // preload bridge is a cross-process contract the renderer cannot enforce, so
+ // a shell built before this method existed exposes `okDesktop` without it.
+ // The type says the method is always there; the running shell is what
+ // decides. A crash annotation is a diagnostic, and its absence must never
+ // take down the editor.
+ const publish = window.okDesktop?.setDisplayLockCrashKey;
+ if (typeof publish !== 'function') return undefined;
+ return publish;
+}
+
+export interface DisplayLockReporterOptions {
+ /** Root to observe; every chunk wrapper lives beneath it. */
+ root: ListenerTarget;
+ /** Sink for the encoded value. Defaults to the desktop bridge. */
+ publish?: (state: string) => void;
+ /** Frame scheduler, injectable so tests need no real animation frames. */
+ schedule?: (run: () => void) => void;
+}
+
+/**
+ * Start publishing chunk-wrapper relevance transitions. Returns a stop function
+ * that detaches the listener; a pending frame callback after stop is a no-op.
+ *
+ * Publishing is skipped entirely when no sink is available, which is the normal
+ * case outside the desktop app: there is no crash database to annotate in a
+ * browser, so nothing is attached at all.
+ */
+export function startDisplayLockCrashKeyReporter(options: DisplayLockReporterOptions): () => void {
+ // No sink means no crash database to annotate — the browser build, or any
+ // host with no `window` at all. Attaching anyway would run the handler on
+ // every transition to feed a no-op, and transitions come in bursts during
+ // exactly the scrolling `content-visibility: auto` exists to keep cheap.
+ // Decline outright instead.
+ const publish = options.publish ?? desktopSink();
+ if (publish === undefined) return () => {};
+ const schedule = options.schedule ?? ((run: () => void) => requestAnimationFrame(run));
+
+ let stopped = false;
+ let frameScheduled = false;
+ let inFrame = 0;
+ let total = 0;
+ let locked = false;
+ /** Frame count of the burst last published, reused by the settled republish. */
+ let lastBurst = 0;
+ /** True between publishing a burst and confirming it has stopped. */
+ let burstLive = false;
+
+ /**
+ * Hand a value to the sink without letting a failure reach the frame loop.
+ *
+ * `publish` crosses the contextBridge into a native binding, so a throw is
+ * not hypothetical. Swallowing it is deliberate: this is a diagnostic, and
+ * the module's whole premise is that it must not cost the editor anything.
+ * An unguarded throw here would do the opposite — it escapes into the rAF
+ * callback, so the frame's bookkeeping never completes and the next
+ * transition re-arms into the identical throw, once per frame for the whole
+ * scroll burst, which is exactly when `content-visibility: auto` is meant to
+ * be cheap.
+ */
+ const publishSafely = (state: string): void => {
+ try {
+ publish(state);
+ } catch {
+ // Nothing to recover: the annotation for this frame is simply lost, and
+ // the next transition publishes a fresh one.
+ }
+ };
+
+ const onFrame = (): void => {
+ frameScheduled = false;
+ if (stopped) return;
+
+ if (inFrame === 0) {
+ // A frame with no new transitions: the burst just published has stopped.
+ // Republish once, marked settled, so a dump can tell a live burst from
+ // residue. Then go quiet until the next transition.
+ if (burstLive) {
+ burstLive = false;
+ publishSafely(encodeDisplayLockState({ locked, inFrame: lastBurst, total, settled: true }));
+ }
+ return;
+ }
+
+ // Bookkeeping is settled BEFORE publishing, so a sink that misbehaves
+ // cannot leave `inFrame` accumulating across frames and inflating every
+ // later reading.
+ const burst = inFrame;
+ lastBurst = burst;
+ inFrame = 0;
+ burstLive = true;
+ // Re-arm to detect the end of the burst. If more transitions arrive first,
+ // this same callback publishes them instead and re-arms again.
+ frameScheduled = true;
+ schedule(onFrame);
+ publishSafely(encodeDisplayLockState({ locked, inFrame: burst, total, settled: false }));
+ };
+
+ const onTransition = (event: Event): void => {
+ if (!isChunkWrapper(event.target)) return;
+ // The DOM lib declares this event with a REQUIRED `skipped: boolean`, so
+ // narrow to it rather than to a hand-rolled optional field — a guessed
+ // shape would type-check clean against itself if the contract ever moved.
+ locked = (event as ContentVisibilityAutoStateChangeEvent).skipped;
+ inFrame += 1;
+ total += 1;
+ if (frameScheduled) return;
+ frameScheduled = true;
+ schedule(onFrame);
+ };
+
+ options.root.addEventListener('contentvisibilityautostatechange', onTransition, {
+ capture: true,
+ });
+ return () => {
+ stopped = true;
+ options.root.removeEventListener('contentvisibilityautostatechange', onTransition, {
+ capture: true,
+ });
+ };
+}
diff --git a/packages/app/src/main.tsx b/packages/app/src/main.tsx
index 484487ffa..be891cdd9 100644
--- a/packages/app/src/main.tsx
+++ b/packages/app/src/main.tsx
@@ -31,6 +31,7 @@ import { selectDesktopRootApp } from '@/components/desktop-root-app';
import { ReportBugCrashInviteTrigger } from '@/components/ReportBugCrashInviteTrigger';
import { Toaster } from '@/components/ui/sonner';
import { TooltipProvider } from '@/components/ui/tooltip';
+import { startDisplayLockCrashKeyReporter } from '@/editor/display-lock-crash-key';
// Side-effect import to load the `Window.okDesktop?` global augmentation.
import '@/lib/desktop-bridge-types';
import { useHydrateRegisteredAgentMeta } from '@/lib/acp/catalog';
@@ -248,6 +249,15 @@ function RegisteredAgentHydrator(): null {
return null;
}
+// Publish editor display-lock transitions as a desktop crash key for the whole
+// life of this renderer. Deliberately not scoped to an editor mount: the key
+// describes the renderer Crashpad may be about to dump, and a display-lock
+// abort can land during a remount, when a mount-scoped observer would be
+// detached. Self-declines to a no-op when there is no desktop bridge to
+// annotate, so the browser build pays nothing. Never stopped — the only
+// terminal event for it is the renderer going away.
+startDisplayLockCrashKeyReporter({ root: document });
+
createRoot(root).render(
<StrictMode>
<I18nProvider i18n={i18n}>
diff --git a/packages/app/tests/stress/fixtures/handoff-mocks.ts b/packages/app/tests/stress/fixtures/handoff-mocks.ts
index 072bfd3c4..9bae6179d 100644
--- a/packages/app/tests/stress/fixtures/handoff-mocks.ts
+++ b/packages/app/tests/stress/fixtures/handoff-mocks.ts
@@ -665,6 +665,9 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
appVersion: 'test-0.0.0',
instanceLabel: null,
getPathForFile: () => null,
+ // Crash annotations have no meaning in a fixture; the reporter only
+ // needs the method to exist so it attaches its observer at all.
+ setDisplayLockCrashKey: () => undefined,
} satisfies OkDesktopBridge;
// biome-ignore lint/suspicious/noExplicitAny: test-only global attachment.
diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.ts
index d7a845280..dfd95ef49 100644
--- a/packages/core/src/bridge/bind-frontmatter-doc.ts
+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts
@@ -1,3 +1,4 @@
+
import type * as Y from 'yjs';
import type { Err, Ok, Result } from '../config/result.ts';
import { type FrontmatterValidationError, toFrontmatterIssue } from '../frontmatter/errors.ts';
diff --git a/packages/core/src/bridge/bridge-invariant.ts b/packages/core/src/bridge/bridge-invariant.ts
index 005627195..8bfdb40cd 100644
--- a/packages/core/src/bridge/bridge-invariant.ts
+++ b/packages/core/src/bridge/bridge-invariant.ts
@@ -1,3 +1,4 @@
+
import { fnv1aDigest } from './hash-util.ts';
export type BridgeInvariantSite = 'observer-b' | 'persistence' | 'test-harness';
diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.ts
index f4cc8a286..2a597ec3d 100644
--- a/packages/core/src/bridge/compose.ts
+++ b/packages/core/src/bridge/compose.ts
@@ -1,3 +1,4 @@
+
import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';
export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';
diff --git a/packages/core/src/bridge/divergence-locate.ts b/packages/core/src/bridge/divergence-locate.ts
index 6b505314d..d979f4b39 100644
--- a/packages/core/src/bridge/divergence-locate.ts
+++ b/packages/core/src/bridge/divergence-locate.ts
@@ -1,3 +1,4 @@
+
import { findFirstDivergenceIndex } from './tolerance-telemetry.ts';
export const BRIDGE_LINE_KINDS = [
diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.ts
index 8fb428b90..01ef76a9f 100644
--- a/packages/core/src/bridge/doc-boundary-space.ts
+++ b/packages/core/src/bridge/doc-boundary-space.ts
@@ -1,3 +1,4 @@
+
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/bridge/growth-detect.ts b/packages/core/src/bridge/growth-detect.ts
index 9d9c244b0..463e89595 100644
--- a/packages/core/src/bridge/growth-detect.ts
+++ b/packages/core/src/bridge/growth-detect.ts
@@ -1,3 +1,4 @@
+
const DEFAULT_MIN_SUBSTANTIVE_LINE_LENGTH = 16;
export const DUPLICATION_GATE_MIN_LINE_LENGTH = 8;
diff --git a/packages/core/src/bridge/intraline-predicate.ts b/packages/core/src/bridge/intraline-predicate.ts
index c43fdd7e7..0939885bb 100644
--- a/packages/core/src/bridge/intraline-predicate.ts
+++ b/packages/core/src/bridge/intraline-predicate.ts
@@ -1,3 +1,4 @@
+
export function rawLineCounts(doc: string): Map<string, number> {
const counts = new Map<string, number>();
for (const line of doc.split('\n')) {
diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.ts
index 251560a35..c0dc65705 100644
--- a/packages/core/src/bridge/merge-three-way.ts
+++ b/packages/core/src/bridge/merge-three-way.ts
@@ -65,6 +65,7 @@ export function tryLineLevelCombine(
return { clean: true, merged };
}
+
export type BridgeMergeContentLossSide = 'user' | 'agent';
export type BridgeMergeContentLossWhich = 'substring' | 'order' | 'growth';
diff --git a/packages/core/src/bridge/normalize.ts b/packages/core/src/bridge/normalize.ts
index 01ac80099..dcc5b0690 100644
--- a/packages/core/src/bridge/normalize.ts
+++ b/packages/core/src/bridge/normalize.ts
@@ -1,3 +1,4 @@
+
import { stripFrontmatter } from '../extensions/frontmatter.ts';
import { bodyEdgeEmpties } from './doc-boundary-space.ts';
diff --git a/packages/core/src/bridge/pm-structural-equivalence.ts b/packages/core/src/bridge/pm-structural-equivalence.ts
index bb53e7c7c..4f7b79587 100644
--- a/packages/core/src/bridge/pm-structural-equivalence.ts
+++ b/packages/core/src/bridge/pm-structural-equivalence.ts
@@ -32,6 +32,7 @@ const BR_SENTINEL: PmStructuralNode = { type: '__br__' };
const BR_LITERAL_RE = /^<br\s*\/?>$/i;
+
interface DegradeEntry {
readonly label: string;
readonly severity: ToleranceClassSeverity;
@@ -128,6 +129,7 @@ export interface ComparePmStructuralOptions {
rawSourceSide?: 'expected';
}
+
/** Rebuild a node with `fn` applied to each child; identity when childless.
* Shared by the degrade canonicalizers so none re-implements the walk. */
function mapChildren(
@@ -253,6 +255,7 @@ function applyDegrades(tree: PmStructuralNode): {
return { normalized: current, fired };
}
+
export function comparePmStructural(
expected: PmStructuralNode,
actual: PmStructuralNode,
diff --git a/packages/core/src/bridge/subsequence.ts b/packages/core/src/bridge/subsequence.ts
index af20de1e2..dca644141 100644
--- a/packages/core/src/bridge/subsequence.ts
+++ b/packages/core/src/bridge/subsequence.ts
@@ -1,3 +1,4 @@
+
/** True when `needle` is a subsequence of `haystack` (two-pointer, O(n+m)):
* insertions in `haystack` are free; any dropped or substituted `needle` byte
* fails. */
diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.ts
index 2e0c57948..ae1b843ca 100644
--- a/packages/core/src/desktop-bridge.ts
+++ b/packages/core/src/desktop-bridge.ts
@@ -2162,6 +2162,31 @@ export interface OkDesktopBridge {
*/
getPathForFile(file: File): string | null;
+ /**
+ * Publish the editor's current `content-visibility` display-lock state as a
+ * crash key on THIS renderer's Crashpad annotations (renderer-side, no IPC).
+ *
+ * It has to be this process: Crashpad annotations are per-process, so a value
+ * set from main would ride main's dumps and never appear on the renderer dump
+ * that a display-lock crash actually produces.
+ *
+ * And it has to be continuous, not on-demand at crash time. The abort this
+ * exists to explain is a Blink `CHECK` in `HitTestResult::GetPosition()`,
+ * which fires when a click's hit-tested node has a paint-blocked ancestor —
+ * an immediate process abort, with no JS running afterwards. Only the value
+ * last published before it survives into the dump, so the caller keeps this
+ * current as lock state changes and the dump carries whatever was true in the
+ * crashing frame.
+ *
+ * `state` is an opaque compact string owned by the caller; this bridge only
+ * transports it and owns the key name. Over-budget values are dropped rather
+ * than sent, because Crashpad truncates silently and a half-written value in
+ * a dump would read as a complete reading.
+ *
+ * No-ops outside the desktop app.
+ */
+ setDisplayLockCrashKey(state: string): void;
+
/**
* Debug-only namespace — populated by preload ONLY when the
* `OK_DEBUG_KEYRING_SMOKE=1` env var is set OR the app is unpacked (dev
diff --git a/packages/core/src/markdown/callout-transformer.ts b/packages/core/src/markdown/callout-transformer.ts
index 83d47404a..a363dfd54 100644
--- a/packages/core/src/markdown/callout-transformer.ts
+++ b/packages/core/src/markdown/callout-transformer.ts
@@ -1,3 +1,4 @@
+
import type { Blockquote, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/code-fence.ts b/packages/core/src/markdown/code-fence.ts
index 9807a7e82..4499dbc92 100644
--- a/packages/core/src/markdown/code-fence.ts
+++ b/packages/core/src/markdown/code-fence.ts
@@ -1,3 +1,4 @@
+
export function selectFenceChar(info: string): '`' | '~' {
return info.includes('`') ? '~' : '`';
}
diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.ts
index 7415c474a..34704165b 100644
--- a/packages/core/src/markdown/comment-promoter.ts
+++ b/packages/core/src/markdown/comment-promoter.ts
@@ -1,3 +1,4 @@
+
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/dedent-block-jsx-close.ts b/packages/core/src/markdown/dedent-block-jsx-close.ts
index ece5c02a1..b6299a948 100644
--- a/packages/core/src/markdown/dedent-block-jsx-close.ts
+++ b/packages/core/src/markdown/dedent-block-jsx-close.ts
@@ -1,3 +1,4 @@
+
import { findFencedRegions, isInsideFence } from './fence-regions.ts';
const INDENTED_BLOCK_JSX_CLOSE_RE = /^([ ]{1,3})(<\/[A-Z][A-Za-z0-9_]*\s*>)([ \t]*)$/gm;
diff --git a/packages/core/src/markdown/details-accordion-promoter.ts b/packages/core/src/markdown/details-accordion-promoter.ts
index 54774764a..acd398aa6 100644
--- a/packages/core/src/markdown/details-accordion-promoter.ts
+++ b/packages/core/src/markdown/details-accordion-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/div-align-promoter.ts b/packages/core/src/markdown/div-align-promoter.ts
index 43ecdc709..ba9b56384 100644
--- a/packages/core/src/markdown/div-align-promoter.ts
+++ b/packages/core/src/markdown/div-align-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';
import type { MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/fence-regions.ts b/packages/core/src/markdown/fence-regions.ts
index 6d3f3643e..4513da9bb 100644
--- a/packages/core/src/markdown/fence-regions.ts
+++ b/packages/core/src/markdown/fence-regions.ts
@@ -1,3 +1,4 @@
+
const FENCE_RE = /^(`{3,}|~{3,})/gm;
export function findFencedRegions(src: string): Array<[number, number]> {
diff --git a/packages/core/src/markdown/fixtures/index.ts b/packages/core/src/markdown/fixtures/index.ts
index 00f5771ee..6931623c7 100644
--- a/packages/core/src/markdown/fixtures/index.ts
+++ b/packages/core/src/markdown/fixtures/index.ts
@@ -1,3 +1,4 @@
+
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -8,6 +9,7 @@ function fixturePath(...segments: string[]): string {
return resolve(FIXTURES_DIR, ...segments);
}
+
interface GfmExample {
section: string;
markdown: string;
@@ -17,6 +19,7 @@ export function loadGfmExamples(): GfmExample[] {
return JSON.parse(readFileSync(fixturePath('gfm', 'examples.json'), 'utf8')) as GfmExample[];
}
+
interface MdxCrashEntry {
id: string;
input: string;
@@ -68,6 +71,7 @@ export function loadLargeEmbedFixtures(): LargeEmbedFixture[] {
) as LargeEmbedFixture[];
}
+
export function loadPrd6955Before(): string {
return readFileSync(fixturePath('regression', 'prd-6955-before.md'), 'utf8');
}
@@ -76,6 +80,7 @@ export function loadPrd6955CorruptedTriplicated(): string {
return readFileSync(fixturePath('regression', 'prd-6955-corrupted-triplicated.md'), 'utf8');
}
+
export interface NgPinnedCase {
id: string;
name: string;
@@ -92,6 +97,7 @@ export function loadNgPinnedCases(): NgPinnedCase[] {
) as NgPinnedCase[];
}
+
export function loadLargeRealistic(): string {
return readFileSync(fixturePath('perf', 'large-realistic.md'), 'utf8');
}
diff --git a/packages/core/src/markdown/fixtures/perf/generate.ts b/packages/core/src/markdown/fixtures/perf/generate.ts
index 8b1eb8519..daa3ef82b 100644
--- a/packages/core/src/markdown/fixtures/perf/generate.ts
+++ b/packages/core/src/markdown/fixtures/perf/generate.ts
@@ -1,3 +1,4 @@
+
import { writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -10,6 +11,7 @@ const BASELINE_ONLY_COUNTS = [500, 2500] as const;
const SEED = 0xf1de1117;
+
function mulberry32(seed: number): () => number {
let a = seed >>> 0;
return () => {
@@ -36,6 +38,7 @@ function pickWeighted<T>(rand: () => number, items: readonly [T, number][]): T {
return items[items.length - 1][0];
}
+
const WORDS = [
'lorem',
'ipsum',
@@ -153,6 +156,7 @@ function mdxBlock(rand: () => number): string {
return `<${name}>\n\n${sentence(rand)}\n\n</${name}>`;
}
+
type BlockKind = 'paragraph' | 'heading' | 'list' | 'code' | 'table' | 'mdx';
const MIX: readonly [BlockKind, number][] = [
@@ -191,6 +195,7 @@ function generateDocument(blockCount: number, seed: number): string {
return `${blocks.join('\n\n')}\n`;
}
+
function main(): void {
for (const count of [...BLOCK_COUNTS, ...BASELINE_ONLY_COUNTS]) {
const doc = generateDocument(count, SEED);
diff --git a/packages/core/src/markdown/guard-flanking-matrix.ts b/packages/core/src/markdown/guard-flanking-matrix.ts
index 420dc0fe5..32c055c5b 100644
--- a/packages/core/src/markdown/guard-flanking-matrix.ts
+++ b/packages/core/src/markdown/guard-flanking-matrix.ts
@@ -7,6 +7,7 @@ import {
import { BACKSLASH_GUARD_SUBSTITUTIONS, encodeBackslashEscapes } from './backslash-escape-guard.ts';
import { ENTITY_REF_GUARD_SUBSTITUTIONS, encodeEntityRefs } from './entity-ref-guard.ts';
+
export const ATTENTION_DELIMITERS = ['*', '_', '**', '~~', '=='] as const;
export type FlankClass = 'whitespace' | 'punctuation' | 'other';
diff --git a/packages/core/src/markdown/handler-shadow-audit.ts b/packages/core/src/markdown/handler-shadow-audit.ts
index 2653473da..283913255 100644
--- a/packages/core/src/markdown/handler-shadow-audit.ts
+++ b/packages/core/src/markdown/handler-shadow-audit.ts
@@ -1,3 +1,4 @@
+
export interface HandlerShadowWitness {
input: string;
expect: 'byte' | 'byte-and-reparse-type';
diff --git a/packages/core/src/markdown/highlight-promoter.ts b/packages/core/src/markdown/highlight-promoter.ts
index da0a81d23..5d1000cc4 100644
--- a/packages/core/src/markdown/highlight-promoter.ts
+++ b/packages/core/src/markdown/highlight-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parent, PhrasingContent, Root, Text } from 'mdast';
import type { MdxJsxTextElement } from 'mdast-util-mdx';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/html-to-mdast.ts b/packages/core/src/markdown/html-to-mdast.ts
index 787315157..9681c0056 100644
--- a/packages/core/src/markdown/html-to-mdast.ts
+++ b/packages/core/src/markdown/html-to-mdast.ts
@@ -1,3 +1,4 @@
+
import type { Element as HastElement, Root as HastRoot } from 'hast';
import type { List, Nodes as MdastNodes, Root as MdastRoot } from 'mdast';
import rehypeParse from 'rehype-parse';
@@ -128,7 +129,8 @@ export function htmlToMdast(html: string, options?: HtmlToMdastOptions): MdastRo
throw new HtmlPayloadTooLargeError(html.length, maxBytes);
}
- const processor = unified().use(rehypeParse, { fragment: true });
+ const processor = unified()
+ .use(rehypeParse, { fragment: true });
for (const plugin of cleanupPlugins) {
processor.use(plugin);
diff --git a/packages/core/src/markdown/image-promoter.ts b/packages/core/src/markdown/image-promoter.ts
index 706fa9afb..994eb6917 100644
--- a/packages/core/src/markdown/image-promoter.ts
+++ b/packages/core/src/markdown/image-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Image, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.ts
index 779e27500..ec1ac1b7e 100644
--- a/packages/core/src/markdown/index.ts
+++ b/packages/core/src/markdown/index.ts
@@ -1,3 +1,4 @@
+
import {
type FromProseMirrorOptions,
fromPmMark,
@@ -206,6 +207,7 @@ export class MarkdownManager {
}
}
+
const registry = createRegistry();
function destructureAttrs(
@@ -254,6 +256,7 @@ function destructureAttrs(
return result;
}
+
function hasDirtyDescendant(node: PmNode): boolean {
let found = false;
node.descendants((child) => {
@@ -276,6 +279,7 @@ function effectiveDirty(node: PmNode, freshnessChecker?: StructuralFreshnessChec
return freshnessChecker ? freshnessChecker.isDiverged(node.toJSON()) : false;
}
+
function isEmptyMdastParagraph(node: MdastNodes): boolean {
if (node.type !== 'paragraph') return false;
const children = node.children ?? [];
@@ -344,6 +348,7 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {
return out;
}
+
import {
AUDIO_EXTENSIONS,
FILE_ATTACHMENT_EXTENSIONS,
@@ -596,6 +601,7 @@ function buildMdastToPmHandlers(
}));
}
+
if (m.emphasis) {
handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({
sourceDelimiter: node.data?.sourceDelimiter ?? '*',
@@ -676,6 +682,7 @@ function buildMdastToPmHandlers(
}));
}
+
if (m.link) {
const sourceLiteralMark = m.sourceLiteral;
handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {
@@ -973,6 +980,7 @@ function buildMdastToPmHandlers(
};
}
+
const blockUnknownHandler = (node: {
type: string;
position?: { start: { offset: number }; end: { offset: number } };
@@ -1098,6 +1106,7 @@ function buildMdastToPmHandlers(
return handlers as RemarkProseMirrorOptions['handlers'];
}
+
function buildPmToMdastHandlers(
schema: Schema,
freshness: FreshnessCheckerHolder,
diff --git a/packages/core/src/markdown/lint/applies-to.ts b/packages/core/src/markdown/lint/applies-to.ts
index fa0be9e86..b79e9aef7 100644
--- a/packages/core/src/markdown/lint/applies-to.ts
+++ b/packages/core/src/markdown/lint/applies-to.ts
@@ -1,3 +1,4 @@
+
import picomatch from 'picomatch';
import { SUPPORTED_DOC_EXTENSIONS } from '../../constants/doc-extensions.ts';
diff --git a/packages/core/src/markdown/lint/config-files.ts b/packages/core/src/markdown/lint/config-files.ts
index 312c9c74b..94b34dee1 100644
--- a/packages/core/src/markdown/lint/config-files.ts
+++ b/packages/core/src/markdown/lint/config-files.ts
@@ -1,3 +1,4 @@
+
const MARKDOWNLINT_JSON_CONFIG_FILES: ReadonlySet<string> = new Set([
'.markdownlint.json',
'.markdownlint.jsonc',
diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.ts
index cc667b93e..7c54c0a73 100644
--- a/packages/core/src/markdown/lint/config-schemas.ts
+++ b/packages/core/src/markdown/lint/config-schemas.ts
@@ -52,6 +52,7 @@ const fullPluginShape = Object.fromEntries(
LINT_PLUGINS.map((plugin) => [plugin.id, plugin.sliceSchema]),
) as z.ZodRawShape;
+
export const LinterConfigSchema = z.object({
enabled: z.boolean(),
plugins: z.object(fullPluginShape),
diff --git a/packages/core/src/markdown/lint/default-config.ts b/packages/core/src/markdown/lint/default-config.ts
index d48eea5e4..a51f2ffb0 100644
--- a/packages/core/src/markdown/lint/default-config.ts
+++ b/packages/core/src/markdown/lint/default-config.ts
@@ -6,6 +6,7 @@ export const DEFAULT_MARKDOWNLINT_CONFIG: Record<string, MarkdownlintRuleSetting
MD013: false,
};
+
export function resolveMarkdownlintConfig(
rules: Record<string, MarkdownlintRuleSetting> | undefined,
): Configuration {
diff --git a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
index ef478e268..9c9542661 100644
--- a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
+++ b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
@@ -1,3 +1,4 @@
+
import { CANONICAL_SCHEMA_DIALECT_URIS, DEFAULT_SCHEMA_DIALECT } from './frontmatter-validate.ts';
export interface FrontmatterFieldConstraint {
diff --git a/packages/core/src/markdown/lint/frontmatter-validate.ts b/packages/core/src/markdown/lint/frontmatter-validate.ts
index 5f953d667..b0e7833fd 100644
--- a/packages/core/src/markdown/lint/frontmatter-validate.ts
+++ b/packages/core/src/markdown/lint/frontmatter-validate.ts
@@ -1,3 +1,4 @@
+
import Ajv, { type ValidateFunction } from 'ajv';
import Ajv2019 from 'ajv/dist/2019.js';
import Ajv2020 from 'ajv/dist/2020.js';
diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.ts
index 781226a5d..26fbc2b22 100644
--- a/packages/core/src/markdown/lint/index.ts
+++ b/packages/core/src/markdown/lint/index.ts
@@ -1,3 +1,4 @@
+
import type { LintPluginFailureReporter } from './plugin-failure.ts';
import { isLintPluginSelected, LINT_PLUGINS, type LinterConfig } from './plugins.ts';
import type { LintDiagnostic } from './types.ts';
@@ -79,7 +80,8 @@ function renderErrorMessage(error: unknown, depth = 0): string {
try {
const json = JSON.stringify(error);
if (json !== undefined) return json;
- } catch {}
+ } catch {
+ }
}
return String(error);
}
diff --git a/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts b/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts
index 7a5af097e..f438f1b16 100644
--- a/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts
+++ b/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts
@@ -1,3 +1,4 @@
+
import type { OkfRuleId } from '../okf-rule-meta.ts';
import { fileNameFor, OKF_SCHEMA_DIR, okfSchemaPathFor } from './paths.ts';
import { OKF_FRONTMATTER_REGISTRY } from './registry.ts';
diff --git a/packages/core/src/markdown/lint/okf-frontmatter/paths.ts b/packages/core/src/markdown/lint/okf-frontmatter/paths.ts
index 1ee913527..c290b6878 100644
--- a/packages/core/src/markdown/lint/okf-frontmatter/paths.ts
+++ b/packages/core/src/markdown/lint/okf-frontmatter/paths.ts
@@ -1,3 +1,4 @@
+
import type { OkfRuleId } from '../okf-rule-meta.ts';
export const OKF_SCHEMA_DIR = '.ok/okf';
diff --git a/packages/core/src/markdown/lint/okf-frontmatter/registry.ts b/packages/core/src/markdown/lint/okf-frontmatter/registry.ts
index f325fbbb4..53ecb619d 100644
--- a/packages/core/src/markdown/lint/okf-frontmatter/registry.ts
+++ b/packages/core/src/markdown/lint/okf-frontmatter/registry.ts
@@ -1,3 +1,4 @@
+
import { compileAppliesTo } from '../applies-to.ts';
import { validateFrontmatterSource } from '../frontmatter-validate.ts';
import {
diff --git a/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts b/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts
index f1c37671b..89845d3d5 100644
--- a/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts
+++ b/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts
@@ -1,3 +1,4 @@
+
// file-level form is deliberate: the sibling `biome-ignore` must sit on the line
// oxlint-disable unicorn/no-thenable
diff --git a/packages/core/src/markdown/lint/okf-project/rules.ts b/packages/core/src/markdown/lint/okf-project/rules.ts
index 6d691ae2b..8b476332e 100644
--- a/packages/core/src/markdown/lint/okf-project/rules.ts
+++ b/packages/core/src/markdown/lint/okf-project/rules.ts
@@ -1,3 +1,4 @@
+
import { SUPPORTED_DOC_EXTENSIONS } from '../../../constants/doc-extensions.ts';
import { isOkfRuleEnabled, type OkfRuleId, type OkfRuleToggles } from '../okf-rule-meta.ts';
diff --git a/packages/core/src/markdown/lint/okf-rule-meta.ts b/packages/core/src/markdown/lint/okf-rule-meta.ts
index 4de50d79f..44913a9dc 100644
--- a/packages/core/src/markdown/lint/okf-rule-meta.ts
+++ b/packages/core/src/markdown/lint/okf-rule-meta.ts
@@ -1,3 +1,4 @@
+
export const OKF_RULE_IDS = [
'no-wiki-links',
'log-shape',
diff --git a/packages/core/src/markdown/lint/okf-rules.ts b/packages/core/src/markdown/lint/okf-rules.ts
index 1d5538421..d0999b62e 100644
--- a/packages/core/src/markdown/lint/okf-rules.ts
+++ b/packages/core/src/markdown/lint/okf-rules.ts
@@ -1,3 +1,4 @@
+
import { isOkfRuleEnabled, type OkfRuleId, type OkfRuleToggles } from './okf-rule-meta.ts';
import type { OkfRule } from './okf-runner.ts';
import { indexShape } from './rules/index-shape.ts';
diff --git a/packages/core/src/markdown/lint/okf-runner.ts b/packages/core/src/markdown/lint/okf-runner.ts
index de130e3f4..fabb08d6e 100644
--- a/packages/core/src/markdown/lint/okf-runner.ts
+++ b/packages/core/src/markdown/lint/okf-runner.ts
@@ -1,3 +1,4 @@
+
import type { Root } from 'mdast';
import remarkFrontmatter from 'remark-frontmatter';
import remarkGfm from 'remark-gfm';
diff --git a/packages/core/src/markdown/lint/plugin-failure.ts b/packages/core/src/markdown/lint/plugin-failure.ts
index e7d694890..1cd0d2543 100644
--- a/packages/core/src/markdown/lint/plugin-failure.ts
+++ b/packages/core/src/markdown/lint/plugin-failure.ts
@@ -1,3 +1,4 @@
+
import type { LintPluginId } from './types.ts';
export interface LintPluginFailure {
diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.ts
index e7455ccf7..1dae8316d 100644
--- a/packages/core/src/markdown/lint/plugins.ts
+++ b/packages/core/src/markdown/lint/plugins.ts
@@ -1,3 +1,4 @@
+
import { z } from 'zod';
import { DEFAULT_MARKDOWNLINT_CONFIG, resolveMarkdownlintConfig } from './default-config.ts';
import {
@@ -23,6 +24,7 @@ import {
type OkfSlice,
} from './types.ts';
+
const MarkdownlintRuleSettingSchema = z.union([
z.boolean(),
z.enum(MARKDOWNLINT_RULE_SEVERITIES),
diff --git a/packages/core/src/markdown/lint/rules/index-shape.ts b/packages/core/src/markdown/lint/rules/index-shape.ts
index 59fe9b87d..fcbb1b56c 100644
--- a/packages/core/src/markdown/lint/rules/index-shape.ts
+++ b/packages/core/src/markdown/lint/rules/index-shape.ts
@@ -1,3 +1,4 @@
+
import type { List, ListItem } from 'mdast';
import { EXIT, visit } from 'unist-util-visit';
import { defineScopedOkfRule } from '../okf-runner.ts';
diff --git a/packages/core/src/markdown/lint/rules/log-shape.ts b/packages/core/src/markdown/lint/rules/log-shape.ts
index e0159519f..431e4e9c8 100644
--- a/packages/core/src/markdown/lint/rules/log-shape.ts
+++ b/packages/core/src/markdown/lint/rules/log-shape.ts
@@ -1,3 +1,4 @@
+
import type { Heading } from 'mdast';
import { toString as headingText } from 'mdast-util-to-string';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/lint/rules/no-wiki-links.ts b/packages/core/src/markdown/lint/rules/no-wiki-links.ts
index 2123e977f..f75a04d15 100644
--- a/packages/core/src/markdown/lint/rules/no-wiki-links.ts
+++ b/packages/core/src/markdown/lint/rules/no-wiki-links.ts
@@ -1,3 +1,4 @@
+
import type { Point } from 'unist';
import { visit } from 'unist-util-visit';
import { defineOkfRule } from '../okf-runner.ts';
diff --git a/packages/core/src/markdown/lint/rules/reserved-casing.ts b/packages/core/src/markdown/lint/rules/reserved-casing.ts
index 89ef3e4a9..c8b4d8f28 100644
--- a/packages/core/src/markdown/lint/rules/reserved-casing.ts
+++ b/packages/core/src/markdown/lint/rules/reserved-casing.ts
@@ -1,3 +1,4 @@
+
import { SUPPORTED_DOC_EXTENSIONS } from '../../../constants/doc-extensions.ts';
import { defineOkfRule } from '../okf-runner.ts';
diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.ts
index 2cffecae6..594830b88 100644
--- a/packages/core/src/markdown/lint/types.ts
+++ b/packages/core/src/markdown/lint/types.ts
@@ -1,3 +1,4 @@
+
import type { BrokenLinkReason } from '../../schemas/api/agent-write.ts';
import type { OkfRuleId } from './okf-rule-meta.ts';
@@ -112,6 +113,7 @@ export interface OkfSlice {
generate?: { index?: boolean };
}
+
interface RuleOptionSpecBase {
key: string;
description: string;
diff --git a/packages/core/src/markdown/lint/validation-counts.ts b/packages/core/src/markdown/lint/validation-counts.ts
index 98238656e..437cc539a 100644
--- a/packages/core/src/markdown/lint/validation-counts.ts
+++ b/packages/core/src/markdown/lint/validation-counts.ts
@@ -1,3 +1,4 @@
+
export interface ValidationSourceCounts {
errorCount: number;
warningCount: number;
diff --git a/packages/core/src/markdown/math-promoter.ts b/packages/core/src/markdown/math-promoter.ts
index a5b511f25..bd79424c7 100644
--- a/packages/core/src/markdown/math-promoter.ts
+++ b/packages/core/src/markdown/math-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Code, Root } from 'mdast';
import type { Math as MdastMath } from 'mdast-util-math';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-to-hast-handlers.ts b/packages/core/src/markdown/mdast-to-hast-handlers.ts
index ed89371d0..00fbc0035 100644
--- a/packages/core/src/markdown/mdast-to-hast-handlers.ts
+++ b/packages/core/src/markdown/mdast-to-hast-handlers.ts
@@ -1,3 +1,4 @@
+
import type { Comment, Element, ElementContent, Properties } from 'hast';
import type { FootnoteDefinition, FootnoteReference } from 'mdast';
import type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-to-html.ts b/packages/core/src/markdown/mdast-to-html.ts
index 8ce2b2492..df788a80d 100644
--- a/packages/core/src/markdown/mdast-to-html.ts
+++ b/packages/core/src/markdown/mdast-to-html.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root as HastRoot, Text as HastText } from 'hast';
import type { Root as MdastRoot, Text as MdastText } from 'mdast';
import type { Handler } from 'mdast-util-to-hast';
diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.ts
index bfd7e3109..fa3cfcd86 100644
--- a/packages/core/src/markdown/merged-walker.ts
+++ b/packages/core/src/markdown/merged-walker.ts
@@ -1,3 +1,4 @@
+
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/mermaid-promoter.ts b/packages/core/src/markdown/mermaid-promoter.ts
index 1a897fca8..17ed2b829 100644
--- a/packages/core/src/markdown/mermaid-promoter.ts
+++ b/packages/core/src/markdown/mermaid-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Code, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/parse-with-fallback.ts b/packages/core/src/markdown/parse-with-fallback.ts
index d988f4b8b..4aa0490c4 100644
--- a/packages/core/src/markdown/parse-with-fallback.ts
+++ b/packages/core/src/markdown/parse-with-fallback.ts
@@ -168,6 +168,7 @@ export function parseRecursive(
}
}
+
interface VFilePlace {
offset?: number;
start?: { offset?: number };
@@ -186,6 +187,7 @@ function extractErrorOffset(err: unknown): number | undefined {
return undefined;
}
+
interface Region {
start: number;
end: number;
@@ -209,6 +211,7 @@ function nearestBlankLineAfter(src: string, offset: number): number | null {
return null;
}
+
export interface TagEvent {
kind: 'open' | 'close' | 'self-close';
name: string;
@@ -355,6 +358,7 @@ function findFallbackRegion(src: string, errorOffset: number): Region {
return { start: blockStart, end: blockEnd };
}
+
interface SourceBlock {
src: string;
start: number;
@@ -452,6 +456,7 @@ function tryPerBlockFallback(
};
}
+
function wholeDocRawText(source: string): JSONContent {
return {
type: 'doc',
diff --git a/packages/core/src/markdown/parser-drop-closure.ts b/packages/core/src/markdown/parser-drop-closure.ts
index e6ab4fd57..43d420187 100644
--- a/packages/core/src/markdown/parser-drop-closure.ts
+++ b/packages/core/src/markdown/parser-drop-closure.ts
@@ -1,3 +1,4 @@
+
export type DroppedTokenAdjudication =
| {
kind: 'format-dof-axis';
diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.ts
index 0e3224206..55736041c 100644
--- a/packages/core/src/markdown/pipeline.ts
+++ b/packages/core/src/markdown/pipeline.ts
@@ -1,3 +1,4 @@
+
import {
type FromProseMirrorOptions,
fromProseMirror,
diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.ts
index 91cdf658f..ccf06e94d 100644
--- a/packages/core/src/markdown/position-aware-join.ts
+++ b/packages/core/src/markdown/position-aware-join.ts
@@ -1,3 +1,4 @@
+
import type { Join } from 'mdast-util-to-markdown';
import type { Position } from 'unist';
import { isBlankLineParagraph } from './zero-emission-blocks.ts';
diff --git a/packages/core/src/markdown/position-slice.ts b/packages/core/src/markdown/position-slice.ts
index 0f399d34c..e5b4c9eba 100644
--- a/packages/core/src/markdown/position-slice.ts
+++ b/packages/core/src/markdown/position-slice.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Root } from 'mdast';
import { visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
@@ -476,7 +477,8 @@ export function applyPositionSliceToNode(
const first = source[startOff];
if (first !== '[' && first !== '<' && !node.title) {
node.data.sourceStyle = 'gfm-autolink';
- } else if (first === '[') {
+ }
+ else if (first === '[') {
const slice = source.slice(startOff, endOff);
const closeBracketIdx = slice.lastIndexOf('](');
if (closeBracketIdx !== -1) {
diff --git a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
index db10fa54b..ca225ce9b 100644
--- a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
+++ b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
@@ -1,3 +1,4 @@
+
import type { Comment, Element, Root, Text } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
index 34068d103..3a2524a9a 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
@@ -1,3 +1,4 @@
+
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
index 93151d43b..2279a0189 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
index 188f02d83..a0f467c42 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
index 4ba2c3418..4e8542a21 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
index 1a74b1272..a3c96b24a 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
@@ -1,3 +1,4 @@
+
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
index de35e7b79..e95cf43d6 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
@@ -1,3 +1,4 @@
+
import type { Comment, Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
index b4be1b2ea..ffdb4d5b5 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
@@ -1,3 +1,4 @@
+
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
index 3c8d88b7c..e2a96d1a7 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/resolve-image-url.ts b/packages/core/src/markdown/resolve-image-url.ts
index cf2c9da8e..0389575ac 100644
--- a/packages/core/src/markdown/resolve-image-url.ts
+++ b/packages/core/src/markdown/resolve-image-url.ts
@@ -1,3 +1,4 @@
+
import { isRelativeUrl } from './safe-url.ts';
function isDevDiagnosticContext(): boolean {
diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.ts
index 4d3250d3a..8be632ba4 100644
--- a/packages/core/src/markdown/safe-url.ts
+++ b/packages/core/src/markdown/safe-url.ts
@@ -1,3 +1,4 @@
+
export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;
const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');
diff --git a/packages/core/src/markdown/serialize-fidelity.test-helper.ts b/packages/core/src/markdown/serialize-fidelity.test-helper.ts
index 0dd54070e..96304e7a5 100644
--- a/packages/core/src/markdown/serialize-fidelity.test-helper.ts
+++ b/packages/core/src/markdown/serialize-fidelity.test-helper.ts
@@ -1,3 +1,4 @@
+
import type { JSONContent } from '@tiptap/core';
import type { Nodes } from 'mdast';
import { expect } from 'vitest';
diff --git a/packages/core/src/markdown/serialize-helpers.ts b/packages/core/src/markdown/serialize-helpers.ts
index 7cac5b042..93798cf83 100644
--- a/packages/core/src/markdown/serialize-helpers.ts
+++ b/packages/core/src/markdown/serialize-helpers.ts
@@ -1,3 +1,4 @@
+
import type { Node as PmNode } from '@tiptap/pm/model';
import type {
MdxJsxAttribute,
diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.ts
index b012a5aff..8c08b7a04 100644
--- a/packages/core/src/markdown/single-dollar-math-promoter.ts
+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts
@@ -1,3 +1,4 @@
+
import type { PhrasingContent, Root, Text } from 'mdast';
import type { InlineMath } from 'mdast-util-math';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.ts
index b50bea5ec..83d4af672 100644
--- a/packages/core/src/markdown/to-markdown-handlers.ts
+++ b/packages/core/src/markdown/to-markdown-handlers.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parents } from 'mdast';
import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import type { Handle, Info, State } from 'mdast-util-to-markdown';
diff --git a/packages/core/src/markdown/underline-promoter.ts b/packages/core/src/markdown/underline-promoter.ts
index 0f1b0f27d..6e6d73400 100644
--- a/packages/core/src/markdown/underline-promoter.ts
+++ b/packages/core/src/markdown/underline-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parent, Root } from 'mdast';
import type { MdxJsxTextElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/unknown-mdast-guard.ts b/packages/core/src/markdown/unknown-mdast-guard.ts
index 1a082bda7..932d7d2a8 100644
--- a/packages/core/src/markdown/unknown-mdast-guard.ts
+++ b/packages/core/src/markdown/unknown-mdast-guard.ts
@@ -1,3 +1,4 @@
+
import type { Root as MdastRoot } from 'mdast';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/whitespace-char-ref.ts b/packages/core/src/markdown/whitespace-char-ref.ts
index d578476a7..ac9f5239b 100644
--- a/packages/core/src/markdown/whitespace-char-ref.ts
+++ b/packages/core/src/markdown/whitespace-char-ref.ts
@@ -1,3 +1,4 @@
+
const INLINE_WHITESPACE_BY_CODE: ReadonlyMap<number, string> = new Map([
[0x20, ' '],
[0x09, '\t'],
diff --git a/packages/core/src/markdown/wiki-link-micromark.ts b/packages/core/src/markdown/wiki-link-micromark.ts
index 6dad26200..afd9936fe 100644
--- a/packages/core/src/markdown/wiki-link-micromark.ts
+++ b/packages/core/src/markdown/wiki-link-micromark.ts
@@ -17,6 +17,7 @@ declare module 'micromark-util-types' {
}
}
+
const CODE_BANG = 33; // !
const CODE_LBRACKET = 91; // [
const CODE_RBRACKET = 93; // ]
@@ -260,6 +261,7 @@ export function wikiLinkSyntax(): Extension {
};
}
+
function enterWikiLink(this: CompileContext, token: Token) {
this.enter(
{
@@ -385,6 +387,7 @@ export const wikiLinkToMarkdown: {
unsafe: [{ character: '[', inConstruct: ['phrasing'] }],
};
+
const MICROMARK_EXT = wikiLinkSyntax();
export function remarkWikiLink(this: Processor) {
diff --git a/packages/desktop/src/main/ipc/bug-report.ts b/packages/desktop/src/main/ipc/bug-report.ts
index b369329ac..cf6f17292 100644
--- a/packages/desktop/src/main/ipc/bug-report.ts
+++ b/packages/desktop/src/main/ipc/bug-report.ts
@@ -44,7 +44,10 @@ import type { OkBugReportSendInput } from '@inkeep/open-knowledge-core/desktop-b
import { type BugReportSendTrace, beginSendTrace } from '../bug-report-trace.ts';
import type { MinidumpReportLookup } from '../crash-detection.ts';
import { logIpcError } from '../ipc-log.ts';
-import { readMinidumpAccessibilityMode } from '../minidump-ownership.ts';
+import {
+ readMinidumpAccessibilityMode,
+ readMinidumpDisplayLockState,
+} from '../minidump-ownership.ts';
import { isPathWithinProject } from '../path-containment.ts';
import type { UpdateChannel } from '../state-store.ts';
@@ -420,6 +423,7 @@ export async function handleBugReportCreate(
// describes ride the same report rather than being correlated later.
const dumpAccessibilityMode =
minidumpPath === null ? null : readMinidumpAccessibilityMode(minidumpPath);
+ const dumpDisplayLock = minidumpPath === null ? null : readMinidumpDisplayLockState(minidumpPath);
// Deliberately says nothing about WHICH dump: a minidump is unredactable
// process memory and its filename is a per-crash identifier, so the record
@@ -451,6 +455,16 @@ export async function handleBugReportCreate(
accessibilityMode: dumpAccessibilityMode.mode,
accessibilityModeParseFailed: dumpAccessibilityMode.parseFailed,
}),
+ // Same present-as-null discipline as the accessibility mode above, and for
+ // the same reason: on a display-lock crash, "the renderer published no lock
+ // state" and "no dump was read" are different findings, and one absent
+ // field for both would collapse them.
+ ...(dumpDisplayLock === null
+ ? {}
+ : {
+ displayLock: dumpDisplayLock.state,
+ displayLockParseFailed: dumpDisplayLock.parseFailed,
+ }),
};
// Written BEFORE the bundle is collected, because the collector snapshots
diff --git a/packages/desktop/src/main/minidump-ownership.test.ts b/packages/desktop/src/main/minidump-ownership.test.ts
index 525f84e0c..817871cee 100644
--- a/packages/desktop/src/main/minidump-ownership.test.ts
+++ b/packages/desktop/src/main/minidump-ownership.test.ts
@@ -23,6 +23,7 @@ import {
classifyMinidumpOwnership,
readMinidumpAccessibilityMode,
readMinidumpAppVersion,
+ readMinidumpDisplayLockState,
} from './minidump-ownership.ts';
const tmpDirs: string[] = [];
@@ -1027,3 +1028,61 @@ describe('readMinidumpAccessibilityMode', () => {
expect(readMinidumpAccessibilityMode(absent)).toEqual({ mode: null, parseFailed: false });
});
});
+
+describe('readMinidumpDisplayLockState', () => {
+ /**
+ * The shape the renderer publishes: a chunk-wrapper transition into the paint
+ * lock, one in that frame and twelve in the session, with the burst still in
+ * flight (`s=0`) when the process died.
+ */
+ const REAL_STATE = 'v1 lock=1 f=1 n=12 s=0';
+
+ function stateOf(patch: MinidumpPatch): string | null {
+ const dir = makeDir();
+ const dumpPath = join(dir, 'crash.dmp');
+ writeFileSync(dumpPath, buildMinidump([ownModule(join(dir, 'OpenKnowledge.app'))], patch));
+ const read = readMinidumpDisplayLockState(dumpPath);
+ expect(read.parseFailed).toBe(false);
+ return read.state;
+ }
+
+ test('a renderer dump names the display-lock state it died with', () => {
+ expect(stateOf({ annotationObjects: [{ ok_display_lock: REAL_STATE }] })).toBe(REAL_STATE);
+ });
+
+ test('a dump from a renderer that never published one has no state', () => {
+ // A renderer that died before the editor mounted, or any build predating
+ // the key. Null is "we do not know", never "no lock was active" — the
+ // contract that says so is on `MinidumpDisplayLockRead`.
+ expect(stateOf({ annotationObjects: [{ process_type: 'renderer' }] })).toBeNull();
+ });
+
+ test('the state is found on a later module, not just the first', () => {
+ expect(stateOf({ annotationObjects: [{}, { ok_display_lock: REAL_STATE }] })).toBe(REAL_STATE);
+ });
+
+ test('a missing dump reads as no state rather than as a broken parser', () => {
+ expect(readMinidumpDisplayLockState(join(makeDir(), 'nope.dmp'))).toEqual({
+ state: null,
+ parseFailed: false,
+ });
+ });
+
+ test('reading the display lock does not cost the accessibility mode its answer', () => {
+ // Both readers share one minidump traversal. Extracting that shared walk
+ // must not let either key shadow the other: a dump carrying both has to
+ // answer both, from independent calls, on the same bytes.
+ const dir = makeDir();
+ const dumpPath = join(dir, 'crash.dmp');
+ const axMode = 'kNativeAPIs | kWebContents';
+ writeFileSync(
+ dumpPath,
+ buildMinidump([ownModule(join(dir, 'OpenKnowledge.app'))], {
+ annotations: { _productName: 'OpenKnowledge', _version: '0.62.1' },
+ annotationObjects: [{ ax_mode: axMode, ok_display_lock: REAL_STATE }],
+ }),
+ );
+ expect(readMinidumpDisplayLockState(dumpPath).state).toBe(REAL_STATE);
+ expect(readMinidumpAccessibilityMode(dumpPath).mode).toBe(axMode);
+ });
+});
diff --git a/packages/desktop/src/main/minidump-ownership.ts b/packages/desktop/src/main/minidump-ownership.ts
index 3c2f685a4..4b60e3788 100644
--- a/packages/desktop/src/main/minidump-ownership.ts
+++ b/packages/desktop/src/main/minidump-ownership.ts
@@ -59,6 +59,7 @@
*/
import { closeSync, openSync, readSync, realpathSync } from 'node:fs';
+import { DISPLAY_LOCK_CRASH_KEY } from '../shared/display-lock-crash-key.ts';
import { asReportableAppVersion } from './crashed-app-version.ts';
import { isPathWithinProject } from './path-containment.ts';
@@ -805,40 +806,57 @@ function findModuleAnnotation(
* descendant processes. Classify first.
*/
export function readMinidumpAccessibilityMode(dumpPath: string): MinidumpAccessibilityModeRead {
+ const read = readDumpAnnotation(dumpPath, AX_MODE_ANNOTATION_KEY);
+ return { mode: read.value, parseFailed: read.parseFailed };
+}
+
+/**
+ * Walk `dumpPath`'s Crashpad stream and return the annotation stored under
+ * `key`, or null when the dump carries none.
+ *
+ * Shared by every annotation reader here so the minidump traversal — signature
+ * check, stream-count ceiling, directory read, Crashpad-stream selection — has
+ * one implementation rather than one per key. The value/parseFailed split is
+ * the callers' contract: null with `parseFailed: false` is "the dump does not
+ * say", null with `parseFailed: true` is "the parser broke".
+ */
+function readDumpAnnotation(
+ dumpPath: string,
+ key: string,
+): { value: string | null; parseFailed: boolean } {
let fd: number | null = null;
try {
fd = openSync(dumpPath, 'r');
const header = readExactly(fd, HEADER_BYTES, 0);
if (header === null || header.readUInt32LE(0) !== MINIDUMP_SIGNATURE) {
- return { mode: null, parseFailed: false };
+ return { value: null, parseFailed: false };
}
const streamCount = header.readUInt32LE(NUMBER_OF_STREAMS_OFFSET);
- if (streamCount === 0 || streamCount > MAX_STREAMS) return { mode: null, parseFailed: false };
+ if (streamCount === 0 || streamCount > MAX_STREAMS) return { value: null, parseFailed: false };
const directory = readExactly(
fd,
streamCount * DIRECTORY_ENTRY_BYTES,
header.readUInt32LE(STREAM_DIRECTORY_RVA_OFFSET),
);
- if (directory === null) return { mode: null, parseFailed: false };
+ if (directory === null) return { value: null, parseFailed: false };
for (let i = 0; i < streamCount; i += 1) {
const at = i * DIRECTORY_ENTRY_BYTES;
if (directory.readUInt32LE(at) !== CRASHPAD_INFO_STREAM_TYPE) continue;
- const read = readModuleAnnotation(
+ return readModuleAnnotation(
fd,
directory.readUInt32LE(at + DIRECTORY_ENTRY_RVA_OFFSET),
directory.readUInt32LE(at + DIRECTORY_ENTRY_SIZE_OFFSET),
- AX_MODE_ANNOTATION_KEY,
+ key,
);
- return { mode: read.value, parseFailed: read.parseFailed };
}
- return { mode: null, parseFailed: false };
+ return { value: null, parseFailed: false };
} catch {
// Unopenable file, torn read, permissions change mid-scan, or a dump that
// is not a minidump — none of which is a broken parser, so none of which
// sets the flag. Matches what `readMinidumpFacts` does with the same shapes.
- return { mode: null, parseFailed: false };
+ return { value: null, parseFailed: false };
} finally {
if (fd !== null) {
try {
@@ -849,3 +867,44 @@ export function readMinidumpAccessibilityMode(dumpPath: string): MinidumpAccessi
}
}
}
+
+export interface MinidumpDisplayLockRead {
+ /**
+ * OK's `ok_display_lock` crash key as the crashed renderer last published it,
+ * or null when the dump does not carry one.
+ *
+ * Null is "we do not know", never "no display lock was active". A renderer
+ * that died before the editor mounted never published a value; so does a dump
+ * for a process with no renderer in it, a build predating the key, and a dump
+ * truncated before its Crashpad stream. The only thing null rules out is a
+ * confident "nothing was locked".
+ *
+ * What a NON-null value means, since it is equally easy to over-read. The
+ * shape is `v1 lock=<0|1> f=<n> n=<n> s=<0|1>`, written by the app's
+ * `display-lock-crash-key` reporter, and it describes `.ok-chunk-wrapper`
+ * (`content-visibility: auto`) transitions ONLY. The other display-lock site,
+ * `.ok-mode-hidden`, is `content-visibility: hidden` and cannot fire the
+ * event this is built on, so a crash there carries whatever the chunk
+ * wrappers last did and says nothing about the pane.
+ *
+ * `s` is the field that dates the reading: `s=0` means a transition burst was
+ * still in flight when the process died, `s=1` means the last burst had
+ * already settled and the rest of the value is residue rather than something
+ * that coincided with the crash.
+ */
+ state: string | null;
+ /** True only when the parser itself threw, which is a bug in this module. */
+ parseFailed: boolean;
+}
+
+/**
+ * Read OK's display-lock crash key out of `dumpPath`.
+ *
+ * Same ownership caveat as `readMinidumpAccessibilityMode`: call this only on a
+ * dump already classified as ours, because Crashpad stamps our annotations onto
+ * dumps it writes for descendant processes too.
+ */
+export function readMinidumpDisplayLockState(dumpPath: string): MinidumpDisplayLockRead {
+ const read = readDumpAnnotation(dumpPath, DISPLAY_LOCK_CRASH_KEY);
+ return { state: read.value, parseFailed: read.parseFailed };
+}
diff --git a/packages/desktop/src/preload/index.ts b/packages/desktop/src/preload/index.ts
index a6baa7497..282d73203 100644
--- a/packages/desktop/src/preload/index.ts
+++ b/packages/desktop/src/preload/index.ts
@@ -34,7 +34,13 @@ import type {
WorktreeCreateResult,
WorktreeListResult,
} from '@inkeep/open-knowledge-core';
-import { contextBridge, type IpcRendererEvent, ipcRenderer, webUtils } from 'electron';
+import {
+ contextBridge,
+ crashReporter,
+ type IpcRendererEvent,
+ ipcRenderer,
+ webUtils,
+} from 'electron';
import type {
OkChromeColors,
OkDesktopBridge,
@@ -64,6 +70,10 @@ import type {
OkUpdateStuckHintInfo,
OkWhatsNewInfo,
} from '../shared/bridge-contract.ts';
+import {
+ DISPLAY_LOCK_CRASH_KEY,
+ DISPLAY_LOCK_CRASH_KEY_MAX_BYTES,
+} from '../shared/display-lock-crash-key.ts';
import type {
IntegrationsSetResult,
IntegrationsStatus,
@@ -1109,6 +1119,23 @@ const bridge: OkDesktopBridge = {
const path = webUtils.getPathForFile(file);
return path === '' ? null : path;
},
+
+ // Renderer-side call (no IPC) because Crashpad annotations are per-process:
+ // the same call from main would annotate main's dumps, never the renderer
+ // dump a display-lock crash produces. `crashReporter` is one of the six
+ // Electron renderer modules a sandboxed preload may import, so this stays
+ // inside the sandbox budget.
+ setDisplayLockCrashKey: (state) => {
+ // Crashpad truncates an over-long value silently, and a truncated reading
+ // in a dump is worse than none: it still parses, so triage would trust it.
+ // Drop instead. Measured in BYTES via `TextEncoder` rather than in string
+ // length, which would undercount anything non-ASCII — and via TextEncoder
+ // rather than `Buffer`, because that is a renderer standard here while
+ // `Buffer` in a sandboxed preload is a Node polyfill this file otherwise
+ // never leans on.
+ if (new TextEncoder().encode(state).length > DISPLAY_LOCK_CRASH_KEY_MAX_BYTES) return;
+ crashReporter.addExtraParameter(DISPLAY_LOCK_CRASH_KEY, state);
+ },
};
// Debug namespace — populated ONLY when main decided the runtime gate is
diff --git a/packages/desktop/src/shared/display-lock-crash-key.ts b/packages/desktop/src/shared/display-lock-crash-key.ts
new file mode 100644
index 000000000..9039d8392
--- /dev/null
+++ b/packages/desktop/src/shared/display-lock-crash-key.ts
@@ -0,0 +1,31 @@
+/**
+ * The Crashpad annotation OK uses to record editor display-lock state on a
+ * renderer dump, shared by the only two sites that may name it: the preload,
+ * which writes it, and the minidump reader in main, which reads it back.
+ *
+ * One definition rather than two string literals, because a drift between the
+ * writer's key and the reader's key would not fail anything — it would produce
+ * dumps that silently carry no display-lock state, which is exactly the
+ * undiagnosable shape the key exists to remove.
+ */
+
+/**
+ * Annotation key. Crashpad silently ignores keys over 39 bytes, so this stays
+ * far inside that ceiling; the `ok_` prefix keeps it clear of Chromium's own
+ * keys (`ax_mode`, `ptype`, and the rest) in a dump's annotation list.
+ */
+export const DISPLAY_LOCK_CRASH_KEY = 'ok_display_lock';
+
+/**
+ * Byte ceiling the preload enforces on a value before handing it to Crashpad.
+ *
+ * Electron's own documentation is self-contradictory here: the
+ * `addExtraParameter` section states a 20320-byte value limit while the
+ * `start()` notes state 127 bytes for the same mechanism. Crashpad truncates an
+ * over-long value silently, and a truncated reading is worse than a missing one
+ * because it still parses and would therefore be trusted during triage. So the
+ * conservative figure is the one enforced, and the writer drops rather than
+ * sends anything above it. Callers are expected to stay well under this by
+ * construction; the cap is a boundary safety net, not a budget to spend.
+ */
+export const DISPLAY_LOCK_CRASH_KEY_MAX_BYTES = 127;