Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Comment on code blocks and table rows. (#3159)

shagun-singh-inkeepea1550fae10a
diff --git a/.changeset/comment-on-non-text-content.md b/.changeset/comment-on-non-text-content.md
new file mode 100644
index 000000000..a5a7780f2
--- /dev/null
+++ b/.changeset/comment-on-non-text-content.md
@@ -0,0 +1,13 @@
+---
+'@inkeep/open-knowledge': minor
+---
+
+Comment on code blocks and table rows.
+
+Dragging a selection across a code block and asking for a comment failed with "The quoted passage is not in the document." A fenced block's backticks were already invisible to the anchor matcher, but the language tag after them was not, so any selection crossing into or out of a ` ```ts ` block could not be located. The same gap closed for thematic breaks, setext heading underlines, table delimiter rows, table cell boundaries, and task-list checkboxes — every source line that renders as nothing.
+
+A code block's sparkle button used to hand the whole block straight to a fresh agent session, with no way to file the note for a later batch. It now opens the same composer the text toolbar's Ask AI opens, offering both. A selection already inside the block is what the comment is about; with nothing selected, the block itself is.
+
+Table rows and columns can now be selected by clicking the handle above a column or beside a row, so a row can be commented on, copied, or deleted as a unit. Previously the handles only opened a menu and the sole way to select cells was sweeping the pointer across them.
+
+Commenting on a selected row quoted a single cell. The composer read the selection's first range, which for a table selection is the anchor cell alone, so picking a three-column row and commenting on it filed the comment against one word of it.
diff --git a/packages/app/src/comments/CommentSelectionAffordance.tsx b/packages/app/src/comments/CommentSelectionAffordance.tsx
index a15e9e821..e951f31bf 100644
--- a/packages/app/src/comments/CommentSelectionAffordance.tsx
+++ b/packages/app/src/comments/CommentSelectionAffordance.tsx
@@ -35,6 +35,7 @@ import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';
import { setCommentDraftRange } from './anchor-decorations';
import { captureSelectionContext } from './anchor-search';
import { appendQueueToOpenSession } from './append-to-open-session';
+import { selectedSpan } from './selected-span';
import { createThread, emitStartComment, subscribeStartComment } from './store';
interface Captured {
@@ -85,8 +86,10 @@ export function CommentSelectionAffordance({
// live selection at that moment (no continuous tracking needed).
useEffect(() => {
return subscribeStartComment(() => {
- const { from, to, empty } = editor.state.selection;
- if (empty || to - from < 1) return;
+ const { selection } = editor.state;
+ if (selection.empty) return;
+ const { from, to } = selectedSpan(selection);
+ if (to - from < 1) return;
// The rendered text, deliberately — NOT the selection serialized back to
// markdown. A serialized partial selection carries the block marker of
// whatever block it sits in, so picking mid-bullet yields
diff --git a/packages/app/src/comments/comment-composer-submit.dom.test.tsx b/packages/app/src/comments/comment-composer-submit.dom.test.tsx
index 26232f1e8..7e5a806b8 100644
--- a/packages/app/src/comments/comment-composer-submit.dom.test.tsx
+++ b/packages/app/src/comments/comment-composer-submit.dom.test.tsx
@@ -114,7 +114,16 @@ function fakeEditor() {
return {
isDestroyed: false,
state: {
- selection: { from: 4, to: 12, empty: false },
+ selection: {
+ from: 4,
+ to: 12,
+ empty: false,
+ // The composer takes its span from `ranges`, not `from`/`to` — those
+ // report the first range only, which on a table CellSelection is one
+ // cell. A real Selection always carries `ranges`, so the double does
+ // too; a single range is the TextSelection case this file covers.
+ ranges: [{ $from: { pos: 4 }, $to: { pos: 12 } }],
+ },
// `content.size` bounds the selection-context capture — a real PM node
// always carries it, so the double has to as well.
doc: { textBetween: () => 'the tofu', content: { size: 40 } },
diff --git a/packages/app/src/comments/selected-span.test.ts b/packages/app/src/comments/selected-span.test.ts
new file mode 100644
index 000000000..09586a06b
--- /dev/null
+++ b/packages/app/src/comments/selected-span.test.ts
@@ -0,0 +1,117 @@
+/**
+ * The span the comment composer captures from a selection.
+ *
+ * The reported failure: selecting a table row and commenting on it quoted the
+ * anchor cell alone (`3`), because `Selection.from`/`.to` report the first
+ * range and a `CellSelection` has one range per cell.
+ */
+
+import { sharedExtensions } from '@inkeep/open-knowledge-core';
+import { getSchema } from '@tiptap/core';
+import type { Node as PmNode } from '@tiptap/pm/model';
+import { EditorState, TextSelection } from '@tiptap/pm/state';
+import { CellSelection, TableMap } from '@tiptap/pm/tables';
+import { describe, expect, test } from 'vitest';
+import { selectedSpan } from './selected-span';
+
+// Schema from core's shared extensions rather than `@tiptap/extension-*`
+// directly — those are only transitive deps here and importing them trips knip.
+const schema = getSchema(sharedExtensions);
+
+/** A `rows × cols` table at pos 0; row 0 is header cells, each cell `R{r}C{c}`. */
+function makeTableDoc(rows: number, cols: number): PmNode {
+ const cell = (r: number, c: number) =>
+ (r === 0 ? schema.nodes.tableHeader : schema.nodes.tableCell).createChecked(
+ null,
+ schema.nodes.paragraph.create(null, schema.text(`R${r}C${c}`)),
+ );
+ const tableRows: PmNode[] = [];
+ for (let r = 0; r < rows; r++) {
+ const cells: PmNode[] = [];
+ for (let c = 0; c < cols; c++) cells.push(cell(r, c));
+ tableRows.push(schema.nodes.tableRow.createChecked(null, cells));
+ }
+ return schema.nodes.doc.create(null, schema.nodes.table.createChecked(null, tableRows));
+}
+
+/** Position of the cell node at (row, col) — what `CellSelection` anchors on. */
+function cellPos(doc: PmNode, row: number, col: number): number {
+ const table = doc.nodeAt(0);
+ if (!table) throw new Error('no table at pos 0');
+ return 1 + TableMap.get(table).positionAt(row, col, table);
+}
+
+/** What the composer would quote for the current selection. */
+function quoteFor(state: EditorState): string {
+ const { from, to } = selectedSpan(state.selection);
+ return state.doc.textBetween(from, to, '\n').trim();
+}
+
+describe('selectedSpan', () => {
+ test('a text selection is unchanged', () => {
+ const doc = schema.nodes.doc.create(
+ null,
+ schema.nodes.paragraph.create(null, schema.text('hello world')),
+ );
+ const state = EditorState.create({
+ schema,
+ doc,
+ selection: TextSelection.create(doc, 1, 6),
+ });
+ expect(selectedSpan(state.selection)).toEqual({ from: 1, to: 6 });
+ expect(quoteFor(state)).toBe('hello');
+ });
+
+ test('a selected row quotes every cell, not just the anchor', () => {
+ const doc = makeTableDoc(3, 3);
+ const $cell = doc.resolve(cellPos(doc, 2, 0));
+ const state = EditorState.create({
+ schema,
+ doc,
+ selection: CellSelection.rowSelection($cell),
+ });
+
+ // The bug: `selection.from`/`.to` describe ONE cell of the row (which one
+ // depends on which end the range list starts from — the point is that two
+ // of the three cells are missing either way).
+ expect(doc.textBetween(state.selection.from, state.selection.to, '\n').trim()).toMatch(
+ /^R2C\d$/,
+ );
+ expect(quoteFor(state)).toBe('R2C0\nR2C1\nR2C2');
+ });
+
+ test('the anchor cell does not have to be the leftmost one', () => {
+ const doc = makeTableDoc(3, 3);
+ const state = EditorState.create({
+ schema,
+ doc,
+ selection: CellSelection.rowSelection(doc.resolve(cellPos(doc, 1, 2))),
+ });
+ expect(quoteFor(state)).toBe('R1C0\nR1C1\nR1C2');
+ });
+
+ test('a selected column spans the table region it runs through', () => {
+ // A column's cells are not adjacent in the markdown source, so the span —
+ // and the quote — is the contiguous region from its top cell to its
+ // bottom one. That IS locatable in the body; a cells-only quote is not.
+ const doc = makeTableDoc(3, 2);
+ const state = EditorState.create({
+ schema,
+ doc,
+ selection: CellSelection.colSelection(doc.resolve(cellPos(doc, 0, 0))),
+ });
+ const quote = quoteFor(state);
+ expect(quote.startsWith('R0C0')).toBe(true);
+ expect(quote.endsWith('R2C0')).toBe(true);
+ });
+
+ test('a whole-table selection spans first cell to last', () => {
+ const doc = makeTableDoc(2, 2);
+ const state = EditorState.create({
+ schema,
+ doc,
+ selection: CellSelection.create(doc, cellPos(doc, 0, 0), cellPos(doc, 1, 1)),
+ });
+ expect(quoteFor(state)).toBe('R0C0\nR0C1\nR1C0\nR1C1');
+ });
+});
diff --git a/packages/app/src/comments/selected-span.ts b/packages/app/src/comments/selected-span.ts
new file mode 100644
index 000000000..5f1e11997
--- /dev/null
+++ b/packages/app/src/comments/selected-span.ts
@@ -0,0 +1,39 @@
+/**
+ * The document span a selection actually covers.
+ *
+ * `Selection.from` / `.to` report the FIRST range only. For a `TextSelection`
+ * there is exactly one range, so they are the whole story — but a table
+ * `CellSelection` carries one range per selected cell, and its first range is
+ * the ANCHOR cell. Reading `from`/`to` off a selected table row therefore
+ * described a single cell: picking the row and commenting on it quoted `3`,
+ * the anchor cell's text, instead of the row.
+ *
+ * The union of every range is a contiguous span because the ranges come from
+ * one document: for a row it is exactly that row's cells, and for a column it
+ * is the table region from the column's top cell through its bottom one. Both
+ * are passages the anchor resolver can locate; a per-cell quote of a column
+ * would not be, since the cells are not adjacent in the markdown source.
+ */
+
+import type { Selection } from '@tiptap/pm/state';
+
+export interface SelectedSpan {
+ from: number;
+ to: number;
+}
+
+export function selectedSpan(selection: Selection): SelectedSpan {
+ let from = Number.POSITIVE_INFINITY;
+ let to = Number.NEGATIVE_INFINITY;
+ for (const range of selection.ranges) {
+ if (range.$from.pos < from) from = range.$from.pos;
+ if (range.$to.pos > to) to = range.$to.pos;
+ }
+ // A selection always has at least one range; the guard keeps a hypothetical
+ // empty one from producing infinities that would poison every position math
+ // downstream.
+ if (!Number.isFinite(from) || !Number.isFinite(to)) {
+ return { from: selection.from, to: selection.to };
+ }
+ return { from, to };
+}
diff --git a/packages/app/src/editor/extensions/CodeBlockView.dom.test.tsx b/packages/app/src/editor/extensions/CodeBlockView.dom.test.tsx
index 356141f4b..3a9aaaa17 100644
--- a/packages/app/src/editor/extensions/CodeBlockView.dom.test.tsx
+++ b/packages/app/src/editor/extensions/CodeBlockView.dom.test.tsx
@@ -12,26 +12,10 @@
import type { Config } from '@inkeep/open-knowledge-core';
import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react';
import type { NodeViewProps } from '@tiptap/core';
-import { afterEach, describe, expect, test, vi } from 'vitest';
-import { subscribeToOpenAskAiComposer } from '@/components/ask-ai-composer-events';
-import {
- type ActiveTerminalInputDetail,
- subscribeToActiveTerminalInput,
-} from '@/components/handoff/terminal-input-events';
+import { afterEach, describe, expect, test } from 'vitest';
+import { subscribeStartComment } from '@/comments/store';
import { ConfigContext, type ConfigContextValue } from '@/lib/config-context';
-
-// The Ask AI click handler routes through `serializeWysiwygSelection`, which
-// runs the full markdown pipeline against the selected slice. Testing that
-// pipeline end-to-end is the fidelity suite's job; this file tests the
-// click→dispatch contract, so stub the serializer to a fixed fenced body.
-vi.doMock('../edit-with-ai-selection', () => ({
- serializeWysiwygSelection: () => '```json\n{ "name": "sample" }\n```',
-}));
-
-// Import the NodeView AFTER the mock registers so its `../edit-with-ai-selection`
-// import binds to the stub serializer rather than the real markdown pipeline.
-const { CodeBlockView } = await import('./CodeBlockView');
-const { setEditorDocName } = await import('./doc-context');
+import { CodeBlockView } from './CodeBlockView';
function makeConfigValue(merged: Config | null): ConfigContextValue {
return {
@@ -232,16 +216,17 @@ describe('CodeBlockView CSP-violation notice wiring', () => {
});
/**
- * Pins the click→dispatch contract for the code-block chrome's Ask AI button.
- * The button drives the block through `setNodeSelection` → serialize →
- * `composeSelectionPrompt` → `requestActiveTerminalInput`; `TerminalSessionsHost`
- * either pastes into a live PTY or launches a fresh Claude tab. This file
- * exercises the button's own decisions (guarded position lookup, doc-grounded
- * dispatch, composer fallback for the empty / no-doc branches); the serializer
- * is stubbed above and the pipeline is covered by the fidelity suite.
+ * Pins the click→compose contract for the code-block chrome's Ask AI button.
+ *
+ * The button opens the same comment composer the text bubble menu's Ask AI
+ * opens — which offers both filing the note for a later batch and handing it
+ * to an agent now. Before that it establishes what the comment is ABOUT: a
+ * pick already inside this block stands, and only an empty or outside
+ * selection gets replaced by a NodeSelection over the whole fence.
*/
-describe('CodeBlockView Ask AI dispatch', () => {
- // rAF is used to defer the dispatch a frame; polyfill for jsdom under bun.
+describe('CodeBlockView Ask AI composer', () => {
+ // rAF defers the emit a frame so the selection transaction lands first;
+ // polyfill for jsdom.
if (typeof globalThis.requestAnimationFrame === 'undefined') {
globalThis.requestAnimationFrame = ((cb: FrameRequestCallback) => {
queueMicrotask(() => cb(0));
@@ -249,47 +234,44 @@ describe('CodeBlockView Ask AI dispatch', () => {
}) as typeof globalThis.requestAnimationFrame;
}
- let terminalInputs: ActiveTerminalInputDetail[] = [];
- let composerOpens = 0;
- let unsubscribeTerminal: (() => void) | null = null;
- let unsubscribeComposer: (() => void) | null = null;
+ let starts = 0;
+ let nodeSelections: number[] = [];
+ let unsubscribeStart: (() => void) | null = null;
afterEach(() => {
- unsubscribeTerminal?.();
- unsubscribeTerminal = null;
- unsubscribeComposer?.();
- unsubscribeComposer = null;
- terminalInputs = [];
- composerOpens = 0;
+ unsubscribeStart?.();
+ unsubscribeStart = null;
+ starts = 0;
+ nodeSelections = [];
cleanup();
});
- function subscribeAll() {
- unsubscribeTerminal = subscribeToActiveTerminalInput((detail) => {
- terminalInputs.push(detail);
- });
- unsubscribeComposer = subscribeToOpenAskAiComposer(() => {
- composerOpens += 1;
+ function subscribeStart() {
+ unsubscribeStart = subscribeStartComment(() => {
+ starts += 1;
});
}
interface EditorMockOverrides {
setNodeSelectionThrows?: 'range' | 'other';
+ /** Live selection, in document positions. */
+ selection?: { from: number; to: number };
}
- // Fake editor shaped enough for the click handler: `.commands.setNodeSelection`
- // is a spy that either records the pos or throws, and `state.selection.empty`
- // reads false (my code doesn't check it, but leaving a NodeSelection-ish
- // shape here matches production). `serializeWysiwygSelection` is stubbed at
- // module load so it never touches `state` directly.
+ /**
+ * Fake editor shaped enough for the click handler: `setNodeSelection` records
+ * the position it was handed (or throws), and `state.selection` is whatever
+ * the case under test needs the live pick to be.
+ */
function makeEditorWithCommands(overrides: EditorMockOverrides = {}) {
- const setNodeSelection = (_pos: number) => {
+ const setNodeSelection = (pos: number) => {
if (overrides.setNodeSelectionThrows === 'range') {
throw new RangeError('Position 5 out of range');
}
if (overrides.setNodeSelectionThrows === 'other') {
throw new Error('unrelated failure');
}
+ nodeSelections.push(pos);
};
return {
isEditable: true,
@@ -297,7 +279,7 @@ describe('CodeBlockView Ask AI dispatch', () => {
commands: { setNodeSelection },
state: {
doc: { nodeAt: () => ({ nodeSize: 10 }) },
- selection: { from: 0, to: 0, empty: false },
+ selection: overrides.selection ?? { from: 0, to: 0, empty: true },
},
on: () => {},
off: () => {},
@@ -310,6 +292,7 @@ describe('CodeBlockView Ask AI dispatch', () => {
node: {
attrs: { language: 'json', meta: null },
textContent: '{ "name": "sample" }',
+ nodeSize: 10,
},
getPos: pos === undefined ? undefined : () => pos,
selected: false,
@@ -317,93 +300,71 @@ describe('CodeBlockView Ask AI dispatch', () => {
} as unknown as NodeViewProps;
}
- function renderAskAi(props: NodeViewProps) {
- return render(
+ function clickAskAi(props: NodeViewProps): HTMLButtonElement {
+ render(
<ConfigContext value={makeConfigValue(null)}>
<CodeBlockView {...props} />
</ConfigContext>,
);
- }
-
- test('click with a grounded doc dispatches a composed prompt to the terminal input channel', async () => {
- subscribeAll();
- const props = makeAskAiProps();
- setEditorDocName(props.editor, 'specs/foo/SPEC');
- const { container } = renderAskAi(props);
-
- const askBtn = container.querySelector(
+ const askBtn = document.querySelector(
'[data-testid="ok-codeblock-ask-ai-btn"]',
) as HTMLButtonElement | null;
expect(askBtn).toBeTruthy();
- fireEvent.click(askBtn as HTMLButtonElement);
-
- await waitFor(() => expect(terminalInputs).toHaveLength(1));
- const [detail] = terminalInputs;
- // Doc named as an @-mention (grounding contract from composeSelectionPrompt).
- expect(detail.text).toContain('@specs/foo/SPEC.md');
- // Stubbed fenced body survives verbatim into the composed prompt.
- expect(detail.text).toContain('```json');
- expect(detail.text).toContain('{ "name": "sample" }');
- // A composed Ask AI instruction RUNS on a fresh session (submit).
- expect(detail.submit).toBe(true);
- // Terminal-input branch does NOT open the composer.
- expect(composerOpens).toBe(0);
+ return askBtn as HTMLButtonElement;
+ }
+
+ test('with nothing picked, selects the whole block and opens the composer', async () => {
+ subscribeStart();
+ fireEvent.click(clickAskAi(makeAskAiProps()));
+
+ await waitFor(() => expect(starts).toBe(1));
+ expect(nodeSelections).toEqual([5]);
});
- test('click with no registered doc name opens the composer instead of dispatching', async () => {
- subscribeAll();
- const props = makeAskAiProps();
- // No setEditorDocName — getEditorDocName returns null.
- renderAskAi(props);
- const askBtn = document.querySelector(
- '[data-testid="ok-codeblock-ask-ai-btn"]',
- ) as HTMLButtonElement | null;
- expect(askBtn).toBeTruthy();
- fireEvent.click(askBtn as HTMLButtonElement);
+ test('a pick inside this block stands — the comment is about those lines', async () => {
+ subscribeStart();
+ // The block occupies [5, 15); this selection sits within its content.
+ fireEvent.click(clickAskAi(makeAskAiProps({ selection: { from: 7, to: 11 } })));
- await waitFor(() => expect(composerOpens).toBe(1));
- expect(terminalInputs).toEqual([]);
+ await waitFor(() => expect(starts).toBe(1));
+ expect(nodeSelections).toEqual([]);
});
- test('click with a stale position (setNodeSelection throws RangeError) neither crashes nor dispatches', async () => {
- subscribeAll();
- const props = makeAskAiProps({ setNodeSelectionThrows: 'range' });
- setEditorDocName(props.editor, 'specs/foo/SPEC');
- // Silence the classified warn so the test log stays clean; the classification
- // itself is what we're asserting via the no-dispatch + no-throw combo.
+ test('a pick in a DIFFERENT block does not stop this one selecting itself', async () => {
+ subscribeStart();
+ // `editor.isActive('codeBlock')` would answer "yes, some code block" here
+ // and wrongly leave the other block's selection in place.
+ fireEvent.click(clickAskAi(makeAskAiProps({ selection: { from: 40, to: 46 } })));
+
+ await waitFor(() => expect(starts).toBe(1));
+ expect(nodeSelections).toEqual([5]);
+ });
+
+ test('a stale position (setNodeSelection throws RangeError) neither crashes nor composes', async () => {
+ subscribeStart();
+ // Silence the classified warn so the test log stays clean; the
+ // classification itself is what the no-emit + no-throw combo asserts.
const originalWarn = console.warn;
console.warn = () => {};
try {
- renderAskAi(props);
- const askBtn = document.querySelector(
- '[data-testid="ok-codeblock-ask-ai-btn"]',
- ) as HTMLButtonElement | null;
- expect(askBtn).toBeTruthy();
- expect(() => fireEvent.click(askBtn as HTMLButtonElement)).not.toThrow();
- // Give any deferred rAF a chance to fire before asserting nothing landed.
+ const btn = clickAskAi(makeAskAiProps({ setNodeSelectionThrows: 'range' }));
+ expect(() => fireEvent.click(btn)).not.toThrow();
await new Promise((resolve) => queueMicrotask(() => resolve(null)));
- expect(terminalInputs).toEqual([]);
- expect(composerOpens).toBe(0);
+ expect(starts).toBe(0);
} finally {
console.warn = originalWarn;
}
});
test('a non-RangeError from setNodeSelection is re-thrown (guard does not swallow real bugs)', async () => {
- subscribeAll();
- const props = makeAskAiProps({ setNodeSelectionThrows: 'other' });
- setEditorDocName(props.editor, 'specs/foo/SPEC');
- renderAskAi(props);
- const askBtn = document.querySelector(
- '[data-testid="ok-codeblock-ask-ai-btn"]',
- ) as HTMLButtonElement | null;
- expect(askBtn).toBeTruthy();
+ subscribeStart();
+ const btn = clickAskAi(makeAskAiProps({ setNodeSelectionThrows: 'other' }));
// A throw from a React 19 event handler is not caught by RTL's fireEvent
// under jsdom; the runtime reports the uncaught error to the window 'error'
// event instead of rethrowing synchronously. Capture it (preventDefault so
// the report does not fail the test) and assert the message, proving the
- // guard only class-catches RangeError and lets a real bug escape rather than
- // swallowing every throw.
+ // guard only class-catches RangeError and lets a real bug escape rather
+ // than swallowing every throw.
const uncaught: string[] = [];
const onError = (event: ErrorEvent) => {
event.preventDefault();
@@ -411,7 +372,7 @@ describe('CodeBlockView Ask AI dispatch', () => {
};
window.addEventListener('error', onError);
try {
- fireEvent.click(askBtn as HTMLButtonElement);
+ fireEvent.click(btn);
} finally {
window.removeEventListener('error', onError);
}
@@ -419,17 +380,10 @@ describe('CodeBlockView Ask AI dispatch', () => {
});
test('click with getPos absent (unrenderable NodeView) is a no-op', async () => {
- subscribeAll();
- const props = makeAskAiProps({}, /* pos */ undefined);
- setEditorDocName(props.editor, 'specs/foo/SPEC');
- renderAskAi(props);
- const askBtn = document.querySelector(
- '[data-testid="ok-codeblock-ask-ai-btn"]',
- ) as HTMLButtonElement | null;
- expect(askBtn).toBeTruthy();
- expect(() => fireEvent.click(askBtn as HTMLButtonElement)).not.toThrow();
+ subscribeStart();
+ const btn = clickAskAi(makeAskAiProps({}, /* pos */ undefined));
+ expect(() => fireEvent.click(btn)).not.toThrow();
await new Promise((resolve) => queueMicrotask(() => resolve(null)));
- expect(terminalInputs).toEqual([]);
- expect(composerOpens).toBe(0);
+ expect(starts).toBe(0);
});
});
diff --git a/packages/app/src/editor/extensions/CodeBlockView.tsx b/packages/app/src/editor/extensions/CodeBlockView.tsx
index eb70eb805..07599d902 100644
--- a/packages/app/src/editor/extensions/CodeBlockView.tsx
+++ b/packages/app/src/editor/extensions/CodeBlockView.tsx
@@ -8,7 +8,6 @@
* (precedent #30) so codeblocks compose visually with other rich blocks.
*/
-import { composeSelectionPrompt } from '@inkeep/open-knowledge-core';
import { Trans, useLingui } from '@lingui/react/macro';
import type { NodeViewProps } from '@tiptap/core';
import { NodeViewContent, NodeViewWrapper } from '@tiptap/react';
@@ -25,8 +24,7 @@ import {
} from 'lucide-react';
import { useTheme } from 'next-themes';
import { useEffect, useId, useRef, useState } from 'react';
-import { emitOpenAskAiComposer } from '@/components/ask-ai-composer-events';
-import { requestActiveTerminalInput } from '@/components/handoff/terminal-input-events';
+import { emitStartComment } from '@/comments/store';
import {
Command,
CommandEmpty,
@@ -40,12 +38,10 @@ import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover
import { useIsEmbedded } from '@/hooks/use-is-embedded';
import { useColorThemeEpoch } from '@/lib/color-theme-epoch';
import { cn } from '@/lib/utils';
-import { docNameToRelativePath } from '@/lib/workspace-paths';
import { OPT_OUT_ATTR } from '../clipboard/index.ts';
import { CodePreviewEditModal } from '../components/CodePreviewEditModal';
import { PreviewBlockedNotice } from '../components/PreviewBlockedNotice';
import { ResizeHandles } from '../components/ResizeHandles.tsx';
-import { serializeWysiwygSelection } from '../edit-with-ai-selection';
import { CODE_BLOCK_LANGUAGES, normalizeCodeLanguage } from './code-block-languages';
import {
addMetaToken,
@@ -59,7 +55,6 @@ import {
setMetaTitle,
shouldShowPreview,
} from './code-block-meta';
-import { getEditorDocName } from './doc-context';
import {
buildPreviewIframeHeader,
buildPreviewThemeMessage,
@@ -173,11 +168,26 @@ export function CodeBlockView({ node, updateAttributes, editor, getPos, selected
// because "edit source" is a primary action when the preview is the
// dominant on-screen surface (HTML preview hides the code by default).
const [editOpen, setEditOpen] = useState(false);
- // Ask AI on this code block. Chrome-hosted (not the bubble menu),
- // because the block isn't a text selection — the whole fence is the
- // context we want to hand to the agent. Hidden inside an embedded agent
- // host, same as the text bubble menu's Ask AI button.
+ // Ask AI on this code block. Chrome-hosted (not the bubble menu), because
+ // the bubble menu does not show over code — marks do not apply to code text,
+ // so its formatting controls would all be dead. Hidden inside an embedded
+ // agent host, same as the text bubble menu's Ask AI button.
const isEmbedded = useIsEmbedded();
+
+ /**
+ * Does the live selection sit inside THIS block's content?
+ *
+ * `editor.isActive('codeBlock')` is not enough — it answers "some code
+ * block", so with two blocks on screen a pick in the first would suppress
+ * the second's button from selecting itself.
+ */
+ const selectionIsInsideThisBlock = (): boolean => {
+ const pos = typeof getPos === 'function' ? getPos() : undefined;
+ if (typeof pos !== 'number') return false;
+ const { from, to } = editor.state.selection;
+ if (from === to) return false;
+ return from > pos && to <= pos + node.nodeSize - 1;
+ };
// Hovered state — the html preview iframe consumes 100% of the block's
// pointer events, so the CSS `:hover` selector never fires on the wrapper.
// Mirror mouseenter/mouseleave into a data attribute so the chrome-reveal
@@ -635,49 +645,39 @@ export function CodeBlockView({ node, updateAttributes, editor, getPos, selected
<button
type="button"
className="ok-codeblock-chrome-btn"
- aria-label={t`Ask AI about this code block`}
+ aria-label={t`Comment or ask AI about this code block`}
data-testid="ok-codeblock-ask-ai-btn"
onClick={() => {
- // Make this code block the WYSIWYG selection so
- // `serializeWysiwygSelection` emits the canonical fenced form
- // (the code-block-fidelity extension's `fenceLength` outlasts
- // any inner backtick run). `composeSelectionPrompt` then
- // decides inline vs locus against the encoded-URL budget; the
- // dispatch routes through `SessionsHost` which pastes
- // to a live PTY or launches a fresh Claude tab.
- const docName = getEditorDocName(editor);
- const pos = typeof getPos === 'function' ? getPos() : undefined;
- if (typeof pos !== 'number') return;
- try {
- editor.commands.setNodeSelection(pos);
- } catch (err) {
- // Mirrors `handleDelete`'s classification — concurrent remote
- // edits or Observer B re-parse can shift `pos` between
- // getPos() and setNodeSelection, producing a RangeError. The
- // block has moved or vanished, so there is nothing to Ask AI
- // about; keep the error off the boundary for benign races.
- if (!(err instanceof RangeError)) throw err;
- console.warn('[CodeBlockView] Ask AI failed — position race', err);
- return;
- }
- const selectionMarkdown = serializeWysiwygSelection(editor);
- requestAnimationFrame(() => {
- if (docName === null || !selectionMarkdown.trim()) {
- emitOpenAskAiComposer();
+ // The same composer the text bubble menu's Ask AI opens, which
+ // is why this used to be the odd one out: it fired a code block
+ // straight at a fresh CLI session, with no way to file the note
+ // for a later batch. Prose got both choices from one button and
+ // code got neither.
+ //
+ // Selection first, block second. A pick INSIDE this block is the
+ // passage the reader means — node-selecting over it would quietly
+ // widen the comment to the whole fence. Only when nothing is
+ // picked here does the block itself become the subject, matching
+ // the copy / delete buttons beside it.
+ if (!selectionIsInsideThisBlock()) {
+ const pos = typeof getPos === 'function' ? getPos() : undefined;
+ if (typeof pos !== 'number') return;
+ try {
+ editor.commands.setNodeSelection(pos);
+ } catch (err) {
+ // Mirrors `handleDelete`'s classification — concurrent remote
+ // edits or Observer B re-parse can shift `pos` between
+ // getPos() and setNodeSelection, producing a RangeError. The
+ // block has moved or vanished, so there is nothing to ask
+ // about; keep the error off the boundary for benign races.
+ if (!(err instanceof RangeError)) throw err;
+ console.warn('[CodeBlockView] Ask AI failed — position race', err);
return;
}
- requestActiveTerminalInput(
- composeSelectionPrompt({
- relativePath: docNameToRelativePath(docName),
- instruction: '',
- selectionMarkdown,
- target: 'claude-code',
- }),
- // A composed ask, so a fresh session runs it — matching the
- // fresh-CLI behavior this surface has always had.
- { submit: true },
- );
- });
+ }
+ // After the selection transaction has landed, so the composer
+ // captures the range this click just established.
+ requestAnimationFrame(() => emitStartComment());
}}
>
<Sparkles className="size-3.5" aria-hidden="true" />
diff --git a/packages/app/src/editor/table-controls/TableCellHandles.tsx b/packages/app/src/editor/table-controls/TableCellHandles.tsx
index e64a1bd49..4537299c6 100644
--- a/packages/app/src/editor/table-controls/TableCellHandles.tsx
+++ b/packages/app/src/editor/table-controls/TableCellHandles.tsx
@@ -65,6 +65,7 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { getFindReplaceState } from '../find-replace/tiptap-find-replace-extension';
+import { handleAnchorCellPos, selectTableAxis } from './table-axis-selection';
import { useTableDragReorder } from './useTableDragReorder';
type Axis = 'column' | 'row';
@@ -154,13 +155,18 @@ function computeActiveCell(editor: Editor): ActiveCell | null {
if (getFindReplaceState(editor.state).query) return null;
const { state, view } = editor;
- const $from = state.selection.$from;
- let cellPos = -1;
- for (let depth = $from.depth; depth > 0; depth--) {
- const role = $from.node(depth).type.spec.tableRole;
- if (role === 'cell' || role === 'header_cell') {
- cellPos = $from.before(depth);
- break;
+ // A table selection anchors both handles to its top-left cell; `$from` is the
+ // far corner of a selected axis and would fling the sibling handle across the
+ // table. Everything else walks up from the caret as before.
+ let cellPos = handleAnchorCellPos(state.selection) ?? -1;
+ if (cellPos < 0) {
+ const $from = state.selection.$from;
+ for (let depth = $from.depth; depth > 0; depth--) {
+ const role = $from.node(depth).type.spec.tableRole;
+ if (role === 'cell' || role === 'header_cell') {
+ cellPos = $from.before(depth);
+ break;
+ }
}
}
if (cellPos < 0) return null;
@@ -210,7 +216,14 @@ function CellHandle({
editor,
axis,
anchor,
- onClickGesture: () => setOpen(true),
+ // Select before opening: the menu's items all act on this row / column, so
+ // the selection is what the menu is ABOUT — and it leaves the axis
+ // highlighted for the selection-scoped surfaces (copy, comment) that the
+ // handle was previously invisible to.
+ onClickGesture: () => {
+ selectTableAxis(editor, anchor, axis);
+ setOpen(true);
+ },
});
useEffect(() => {
diff --git a/packages/app/src/editor/table-controls/table-axis-selection.test.ts b/packages/app/src/editor/table-controls/table-axis-selection.test.ts
new file mode 100644
index 000000000..0f4bd7a64
--- /dev/null
+++ b/packages/app/src/editor/table-controls/table-axis-selection.test.ts
@@ -0,0 +1,155 @@
+/**
+ * Row / column selection built from a handle's anchor cell.
+ *
+ * The handles used to open a menu and nothing else, so no gesture selected a
+ * whole row or column — a table could only be picked by sweeping the pointer
+ * across its cells. These pin that a handle's cell resolves to a
+ * `CellSelection` covering its entire axis, and that a position outside any
+ * cell declines instead of throwing.
+ */
+
+import { sharedExtensions } from '@inkeep/open-knowledge-core';
+import { getSchema } from '@tiptap/core';
+import type { Node as PmNode } from '@tiptap/pm/model';
+import { EditorState, TextSelection } from '@tiptap/pm/state';
+import { CellSelection, TableMap } from '@tiptap/pm/tables';
+import { describe, expect, test } from 'vitest';
+import { buildAxisSelection, handleAnchorCellPos } from './table-axis-selection';
+
+// Schema from core's shared extensions rather than `@tiptap/extension-*`
+// directly — those are only transitive deps here and importing them trips knip
+// (same setup as table-row-enter.test.ts).
+const schema = getSchema(sharedExtensions);
+
+/** A `rows × cols` table at pos 0; row 0 is header cells. Each cell holds `R{r}C{c}`. */
+function makeTableDoc(rows: number, cols: number): PmNode {
+ const cell = (r: number, c: number) =>
+ (r === 0 ? schema.nodes.tableHeader : schema.nodes.tableCell).createChecked(
+ null,
+ schema.nodes.paragraph.create(null, schema.text(`R${r}C${c}`)),
+ );
+ const tableRows: PmNode[] = [];
+ for (let r = 0; r < rows; r++) {
+ const cells: PmNode[] = [];
+ for (let c = 0; c < cols; c++) cells.push(cell(r, c));
+ tableRows.push(schema.nodes.tableRow.createChecked(null, cells));
+ }
+ return schema.nodes.doc.create(null, schema.nodes.table.createChecked(null, tableRows));
+}
+
+/** Position INSIDE the cell at (row, col) — what `posAtDOM(cell, 0)` returns. */
+function posInsideCell(doc: PmNode, row: number, col: number): number {
+ const table = doc.nodeAt(0);
+ if (!table) throw new Error('no table at pos 0');
+ return 1 + TableMap.get(table).positionAt(row, col, table) + 1;
+}
+
+/** Position OF the cell node at (row, col) — what a CellSelection anchors on. */
+function cellNodePos(doc: PmNode, row: number, col: number): number {
+ return posInsideCell(doc, row, col) - 1;
+}
+
+/**
+ * The `R{r}C{c}` label of every cell the selection covers, in document order.
+ * `forEachCell` walks the grid row-major; `ranges` would report the anchor
+ * cell first, which says nothing about coverage.
+ */
+function selectedLabels(selection: CellSelection | null): string[] {
+ if (!selection) throw new Error('expected a CellSelection');
+ const labels: string[] = [];
+ selection.forEachCell((cell) => labels.push(cell.textContent));
+ return labels;
+}
+
+describe('buildAxisSelection', () => {
+ const doc = makeTableDoc(3, 3);
+
+ test('a row handle selects every cell in its row', () => {
+ const selection = buildAxisSelection(doc, posInsideCell(doc, 1, 0), 'row');
+ expect(selection).not.toBeNull();
+ expect(selectedLabels(selection)).toEqual(['R1C0', 'R1C1', 'R1C2']);
+ });
+
+ test('a column handle selects every cell in its column, header included', () => {
+ const selection = buildAxisSelection(doc, posInsideCell(doc, 0, 2), 'column');
+ expect(selection).not.toBeNull();
+ expect(selectedLabels(selection)).toEqual(['R0C2', 'R1C2', 'R2C2']);
+ });
+
+ test('a row selection spans the row it was asked for, not the one above', () => {
+ const selection = buildAxisSelection(doc, posInsideCell(doc, 2, 1), 'row');
+ expect(selectedLabels(selection)).toEqual(['R2C0', 'R2C1', 'R2C2']);
+ });
+
+ test('a header row selects like any other', () => {
+ const selection = buildAxisSelection(doc, posInsideCell(doc, 0, 0), 'row');
+ expect(selectedLabels(selection)).toEqual(['R0C0', 'R0C1', 'R0C2']);
+ });
+
+ test('a position outside any cell declines', () => {
+ const outside = schema.nodes.doc.create(null, schema.nodes.paragraph.create(null));
+ expect(buildAxisSelection(outside, 1, 'row')).toBeNull();
+ });
+
+ test('an out-of-range position declines rather than throwing', () => {
+ // The anchor cell is read from live DOM, so a remote edit can shrink the
+ // document between the pointer gesture and this call.
+ expect(() => buildAxisSelection(doc, 10_000, 'column')).not.toThrow();
+ expect(buildAxisSelection(doc, 10_000, 'column')).toBeNull();
+ });
+});
+
+describe('handleAnchorCellPos', () => {
+ const doc = makeTableDoc(3, 3);
+ const label = (pos: number | null): string | null =>
+ pos === null ? null : (doc.nodeAt(pos)?.textContent ?? null);
+
+ /** The cell `computeActiveCell` used to land on: walk up from `$from`. */
+ function fromCellLabel(selection: CellSelection): string | null {
+ const $from = selection.$from;
+ for (let depth = $from.depth; depth > 0; depth--) {
+ const role = $from.node(depth).type.spec.tableRole;
+ if (role === 'cell' || role === 'header_cell') return label($from.before(depth));
+ }
+ return null;
+ }
+
+ test('a selected row anchors on its leftmost cell, not the far corner', () => {
+ const selection = buildAxisSelection(doc, posInsideCell(doc, 1, 0), 'row') as CellSelection;
+ // The regression: `$from` is the axis's FAR end, so the column handle
+ // followed it to the last column and lost its header-toggle item.
+ expect(fromCellLabel(selection)).toBe('R1C2');
+ expect(label(handleAnchorCellPos(selection))).toBe('R1C0');
+ });
+
+ test('a selected column anchors on its top cell, not the bottom row', () => {
+ const selection = buildAxisSelection(doc, posInsideCell(doc, 0, 2), 'column') as CellSelection;
+ expect(fromCellLabel(selection)).toBe('R2C2');
+ expect(label(handleAnchorCellPos(selection))).toBe('R0C2');
+ });
+
+ test('the clicked handle keeps its own axis', () => {
+ // Clicking row 2's handle must leave the row handle on row 2 (column 0),
+ // wherever the sibling ends up.
+ const selection = buildAxisSelection(doc, posInsideCell(doc, 2, 1), 'row') as CellSelection;
+ expect(label(handleAnchorCellPos(selection))).toBe('R2C0');
+ });
+
+ test('a dragged cell range anchors on its top-left', () => {
+ const selection = CellSelection.create(
+ doc,
+ cellNodePos(doc, 2, 2),
+ cellNodePos(doc, 1, 1),
+ ) as CellSelection;
+ expect(label(handleAnchorCellPos(selection))).toBe('R1C1');
+ });
+
+ test('a plain caret selection defers to the caller', () => {
+ const state = EditorState.create({
+ schema,
+ doc,
+ selection: TextSelection.near(doc.resolve(posInsideCell(doc, 1, 1))),
+ });
+ expect(handleAnchorCellPos(state.selection)).toBeNull();
+ });
+});
diff --git a/packages/app/src/editor/table-controls/table-axis-selection.ts b/packages/app/src/editor/table-controls/table-axis-selection.ts
new file mode 100644
index 000000000..acd117686
--- /dev/null
+++ b/packages/app/src/editor/table-controls/table-axis-selection.ts
@@ -0,0 +1,90 @@
+/**
+ * Select a whole table row or column.
+ *
+ * The row / column handles opened a menu and nothing else, so a table had no
+ * "pick this row" gesture at all: dragging across cells was the only way to
+ * reach a `CellSelection`, and dragging a column meant sweeping its full
+ * height. Clicking a handle now selects the axis it belongs to, which is what
+ * makes the row visibly highlighted and hands every selection-scoped surface —
+ * copy, delete, the bubble menu's comment entry — a real range to act on.
+ *
+ * Split from `TableCellHandles` so the position arithmetic is testable without
+ * a mounted editor view: `buildAxisSelection` is pure, and only the thin DOM
+ * lookup below needs the view.
+ */
+
+import type { Node as PmNode } from '@tiptap/pm/model';
+import type { Selection } from '@tiptap/pm/state';
+import { CellSelection, cellAround, TableMap } from '@tiptap/pm/tables';
+import type { Editor } from '@tiptap/react';
+
+export type TableAxis = 'column' | 'row';
+
+/**
+ * A `CellSelection` spanning the full row / column through `posInCell`, or null
+ * when that position is not inside a table cell.
+ *
+ * Null rather than throwing: the anchor cell is resolved from live DOM, and a
+ * remote edit can detach it between the pointer gesture and this call.
+ */
+export function buildAxisSelection(
+ doc: PmNode,
+ posInCell: number,
+ axis: TableAxis,
+): CellSelection | null {
+ if (posInCell < 0 || posInCell > doc.content.size) return null;
+ const $cell = cellAround(doc.resolve(posInCell));
+ if (!$cell) return null;
+ return axis === 'row' ? CellSelection.rowSelection($cell) : CellSelection.colSelection($cell);
+}
+
+/**
+ * The cell both handles should anchor to for a table selection, or null when
+ * the selection is not one (the caller then walks up from `$from` as before).
+ *
+ * The selection's TOP-LEFT cell, deliberately. `rowSelection` / `colSelection`
+ * normalise their arguments to the two far corners of the axis, and the
+ * resulting `$from` is the FAR one — so deriving the handles from `$from` sent
+ * the sibling handle to the table's last column (or last row) the moment an
+ * axis was selected, flipping its `isFirst*` flag and silently dropping the
+ * header-toggle item from its menu. Top-left keeps the clicked handle where it
+ * is and puts the sibling at the axis origin.
+ */
+export function handleAnchorCellPos(selection: Selection): number | null {
+ if (!(selection instanceof CellSelection)) return null;
+ const table = selection.$anchorCell.node(-1);
+ if (!table) return null;
+ const tableStart = selection.$anchorCell.start(-1);
+ const map = TableMap.get(table);
+ const rect = map.rectBetween(
+ selection.$anchorCell.pos - tableStart,
+ selection.$headCell.pos - tableStart,
+ );
+ const offset = map.map[rect.top * map.width + rect.left];
+ return offset === undefined ? null : tableStart + offset;
+}
+
+/**
+ * Select the row / column that `anchor` belongs to. No-op when the cell cannot
+ * be located, so a stale handle never throws into the editor's error boundary.
+ */
+export function selectTableAxis(editor: Editor, anchor: HTMLElement, axis: TableAxis): void {
+ const { view, state } = editor;
+ let posInCell: number;
+ try {
+ // Offset 0 lands inside the cell's first child, which is what `cellAround`
+ // needs to walk up from — the cell's own position resolves to its parent
+ // row and would find the wrong node.
+ posInCell = view.posAtDOM(anchor, 0);
+ } catch (err) {
+ // posAtDOM throws on detached/partially-recycled DOM. Declining to select
+ // is the correct fallback, but log so a systematic failure (e.g. after a
+ // ProseMirror upgrade) leaves a signal instead of a handle that silently
+ // stops selecting — matching the sibling catch in markdown-lint-decorations.
+ console.warn('[TableCellHandles] posAtDOM failed on handle anchor; axis not selected', err);
+ return;
+ }
+ const selection = buildAxisSelection(state.doc, posInCell, axis);
+ if (!selection) return;
+ view.dispatch(state.tr.setSelection(selection));
+}
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index a43f0d6d4..9c633314b 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -44,7 +44,6 @@
"-zA2E7": ["Couldn't create the worktree. Try a different name."],
"-zy2Nq": ["Type"],
"0-31GV": ["Removing"],
- "00c7t0": ["Ask AI about this code block"],
"02P3hL": ["Upload failed: ", ["message"]],
"03wKPg": ["A report helps us find the cause. Nothing is sent until you review it."],
"04RA0-": ["Failed to enable sync — ", ["detail"]],
@@ -1533,6 +1532,7 @@
"OdmsFg": ["Failed to delete item"],
"OeAl1e": ["e.g. assets/uploads"],
"OfhWJH": ["Reset"],
+ "Ohpzub": ["Comment or ask AI about this code block"],
"Oi56Cu": ["Cleanup log"],
"OiHJdA": [
"Move through slash, wiki-link, tag, and path suggestions; accept or dismiss the active suggestion."
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index 66a4e57ef..8b109bd6b 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -1487,10 +1487,6 @@ msgstr "Ask AI"
msgid "Ask AI (from selection)"
msgstr "Ask AI (from selection)"
-#: src/editor/extensions/CodeBlockView.tsx
-msgid "Ask AI about this code block"
-msgstr "Ask AI about this code block"
-
#: src/components/ProblemsPanel.tsx
msgid "Ask AI to fix {flatId}"
msgstr "Ask AI to fix {flatId}"
@@ -2349,6 +2345,10 @@ msgstr "Comment on {address}"
msgid "Comment on selection"
msgstr "Comment on selection"
+#: src/editor/extensions/CodeBlockView.tsx
+msgid "Comment or ask AI about this code block"
+msgstr "Comment or ask AI about this code block"
+
#: src/comments/comment-chips.tsx
#: src/comments/CommentsPanel.tsx
#: src/components/DocPanel.tsx
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index f8970f7c7..c6d6aa700 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -44,7 +44,6 @@
"-zA2E7": ["Ćōũĺďń'ţ ćŕēàţē ţĥē ŵōŕķţŕēē. Ţŕŷ à ďĩƒƒēŕēńţ ńàḿē."],
"-zy2Nq": ["Ţŷƥē"],
"0-31GV": ["Ŕēḿōvĩńĝ"],
- "00c7t0": ["Àśķ ÀĨ àƀōũţ ţĥĩś ćōďē ƀĺōćķ"],
"02P3hL": ["Ũƥĺōàď ƒàĩĺēď: ", ["message"]],
"03wKPg": ["À ŕēƥōŕţ ĥēĺƥś ũś ƒĩńď ţĥē ćàũśē. Ńōţĥĩńĝ ĩś śēńţ ũńţĩĺ ŷōũ ŕēvĩēŵ ĩţ."],
"04RA0-": ["Ƒàĩĺēď ţō ēńàƀĺē śŷńć — ", ["detail"]],
@@ -1533,6 +1532,7 @@
"OdmsFg": ["Ƒàĩĺēď ţō ďēĺēţē ĩţēḿ"],
"OeAl1e": ["ē.ĝ. àśśēţś/ũƥĺōàďś"],
"OfhWJH": ["Ŕēśēţ"],
+ "Ohpzub": ["Ćōḿḿēńţ ōŕ àśķ ÀĨ àƀōũţ ţĥĩś ćōďē ƀĺōćķ"],
"Oi56Cu": ["Ćĺēàńũƥ ĺōĝ"],
"OiHJdA": [
"Ḿōvē ţĥŕōũĝĥ śĺàśĥ, ŵĩķĩ-ĺĩńķ, ţàĝ, àńď ƥàţĥ śũĝĝēśţĩōńś; àććēƥţ ōŕ ďĩśḿĩśś ţĥē àćţĩvē śũĝĝēśţĩōń."
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 3fb28a368..95a54d14b 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -1483,10 +1483,6 @@ msgstr ""
msgid "Ask AI (from selection)"
msgstr ""
-#: src/editor/extensions/CodeBlockView.tsx
-msgid "Ask AI about this code block"
-msgstr ""
-
#: src/components/ProblemsPanel.tsx
msgid "Ask AI to fix {flatId}"
msgstr ""
@@ -2345,6 +2341,10 @@ msgstr ""
msgid "Comment on selection"
msgstr ""
+#: src/editor/extensions/CodeBlockView.tsx
+msgid "Comment or ask AI about this code block"
+msgstr ""
+
#: src/comments/comment-chips.tsx
#: src/comments/CommentsPanel.tsx
#: src/components/DocPanel.tsx
diff --git a/packages/core/src/comments/passage-match.test.ts b/packages/core/src/comments/passage-match.test.ts
index 577ca6711..644b4683d 100644
--- a/packages/core/src/comments/passage-match.test.ts
+++ b/packages/core/src/comments/passage-match.test.ts
@@ -155,3 +155,178 @@ describe('links', () => {
expect(findPassage(prose, 'array[0] value', { syntaxIn: 'haystack' })).not.toBeNull();
});
});
+
+describe('lines that render as nothing', () => {
+ // The reported failure: dragging a selection across a code block returned a
+ // bare 400. The fence's backticks were already elastic, but the info string
+ // after them was not, so the match died on the `ts` in ```` ```ts ````.
+ const BODY = `Add \`appearance.language\` to \`ConfigSchema\`:
+
+\`\`\`ts
+language: z
+ .enum(['system', 'en', 'es'])
+\`\`\`
+
+Acceptance: the leaf validates.`;
+
+ /** What the editor hands over: rendered text, blocks joined by a newline. */
+ const rendered = (...lines: string[]): string => lines.join('\n');
+
+ test('a selection running from prose into a tagged code block', () => {
+ const hit = findPassage(
+ BODY,
+ rendered('Add appearance.language to ConfigSchema:', 'language: z'),
+ { syntaxIn: 'haystack' },
+ );
+ expect(BODY.slice(hit?.start, hit?.end)).toContain('```ts');
+ });
+
+ test('a selection running out of a code block back into prose', () => {
+ expect(
+ findPassage(BODY, rendered(" .enum(['system', 'en', 'es'])", 'Acceptance: the leaf'), {
+ syntaxIn: 'haystack',
+ }),
+ ).not.toBeNull();
+ });
+
+ test('a selection swallowing the whole block', () => {
+ expect(
+ findPassage(
+ BODY,
+ rendered(
+ 'to ConfigSchema:',
+ 'language: z',
+ " .enum(['system', 'en', 'es'])",
+ 'Acceptance:',
+ ),
+ { syntaxIn: 'haystack' },
+ ),
+ ).not.toBeNull();
+ });
+
+ test('a code block selected on its own is still an exact substring', () => {
+ const hit = findPassage(BODY, "language: z\n .enum(['system', 'en', 'es'])", {
+ syntaxIn: 'haystack',
+ });
+ expect(BODY.slice(hit?.start, hit?.end)).toBe("language: z\n .enum(['system', 'en', 'es'])");
+ });
+
+ test('a tilde fence carries an info string too', () => {
+ expect(
+ findPassage('before\n\n~~~ts\ncode here\n~~~\n\nafter', rendered('before', 'code here'), {
+ syntaxIn: 'haystack',
+ }),
+ ).not.toBeNull();
+ });
+
+ test('the mirror direction: a stored quote carrying a fence', () => {
+ // The server stores the body slice, fence and all; the editor then re-finds
+ // it against rendered text, so the same line has to be elastic both ways.
+ const editorText = 'to ConfigSchema:language: z';
+ expect(
+ findPassage(editorText, 'to `ConfigSchema`:\n\n```ts\nlanguage: z', { syntaxIn: 'needle' }),
+ ).not.toBeNull();
+ });
+
+ test('crosses a thematic break', () => {
+ expect(
+ findPassage('before\n\n---\n\nafter', rendered('before', 'after'), { syntaxIn: 'haystack' }),
+ ).not.toBeNull();
+ });
+
+ test('crosses a setext heading underline', () => {
+ expect(
+ findPassage('Title\n=====\n\nbody text', rendered('Title', 'body text'), {
+ syntaxIn: 'haystack',
+ }),
+ ).not.toBeNull();
+ });
+
+ test('crosses a table delimiter row and its cell boundaries', () => {
+ expect(
+ findPassage('| a | b |\n| --- | --- |\n| 1 | 2 |', rendered('a b', '1 2'), {
+ syntaxIn: 'haystack',
+ }),
+ ).not.toBeNull();
+ });
+
+ test('crosses task-list checkboxes', () => {
+ expect(
+ findPassage('- [ ] todo one\n- [x] todo two', rendered('todo one', 'todo two'), {
+ syntaxIn: 'haystack',
+ }),
+ ).not.toBeNull();
+ });
+
+ test('a line carrying content is never swallowed whole', () => {
+ // `***bold***` opens like a thematic break, so the needle has to STRADDLE
+ // it: fragments either side, nothing naming the line itself. Treating the
+ // line as invisible would bridge them. A real break is the control — same
+ // shape, same needle, and it must match.
+ const straddle = rendered('head', 'tail');
+ expect(
+ findPassage('head\n\n***bold***\n\ntail', straddle, { syntaxIn: 'haystack' }),
+ ).toBeNull();
+ expect(findPassage('head\n\n---\n\ntail', straddle, { syntaxIn: 'haystack' })).not.toBeNull();
+
+ // Same pair for the table-rule pattern, which `-- dashes` opens like.
+ expect(findPassage('head\n\n-- dashes\n\ntail', straddle, { syntaxIn: 'haystack' })).toBeNull();
+ expect(findPassage('head\n\n-- --\n\ntail', straddle, { syntaxIn: 'haystack' })).not.toBeNull();
+ });
+
+ test('elasticity across a fence still cannot bridge different words', () => {
+ expect(findPassage(BODY, 'ConfigSchema: gochujang', { syntaxIn: 'haystack' })).toBeNull();
+ });
+
+ describe('CRLF documents', () => {
+ // The line slice runs to the `\n`, so on CRLF it carries a trailing `\r`.
+ // The rule patterns' character classes do not admit one, so `$` could not
+ // match and every rule line stayed non-elastic on Windows line endings.
+ const crlf = (...lines: string[]): string => lines.join('\r\n');
+ const straddle = rendered('head', 'tail');
+
+ test('a thematic break', () => {
+ expect(
+ findPassage(crlf('head', '', '---', '', 'tail'), straddle, {
+ syntaxIn: 'haystack',
+ }),
+ ).not.toBeNull();
+ });
+
+ test('a setext heading underline', () => {
+ expect(
+ findPassage(crlf('Title', '=====', '', 'tail'), rendered('Title', 'tail'), {
+ syntaxIn: 'haystack',
+ }),
+ ).not.toBeNull();
+ });
+
+ test('a table delimiter row and its cell boundaries', () => {
+ expect(
+ findPassage(crlf('| a | b |', '| --- | --- |', '| 1 | 2 |'), rendered('a b', '1 2'), {
+ syntaxIn: 'haystack',
+ }),
+ ).not.toBeNull();
+ });
+
+ test('a fenced code block with an info string', () => {
+ expect(
+ findPassage(
+ crlf('before', '', '```ts', 'code here', '```', '', 'after'),
+ rendered('before', 'code here', 'after'),
+ {
+ syntaxIn: 'haystack',
+ },
+ ),
+ ).not.toBeNull();
+ });
+
+ test('a content line is still not swallowed', () => {
+ expect(
+ findPassage(crlf('head', '', '***bold***', '', 'tail'), straddle, {
+ syntaxIn: 'haystack',
+ }),
+ ).toBeNull();
+ });
+ });
+});
diff --git a/packages/core/src/comments/passage-match.ts b/packages/core/src/comments/passage-match.ts
index 1d1972cdc..14de591a9 100644
--- a/packages/core/src/comments/passage-match.ts
+++ b/packages/core/src/comments/passage-match.ts
@@ -52,12 +52,72 @@ const LINK_TAIL = /^\]\([^)]*\)/;
/** Bounds the slice `LINK_TAIL` runs on. Generous — targets can be long URLs. */
const LINK_TAIL_WINDOW = 512;
-/** Heading, blockquote, bullet, and ordered-list markers — line-leading only. */
-const BLOCK_MARKER = /^(?:#{1,6}[ \t]+|>[ \t]?|[-*+][ \t]+|\d{1,9}[.)][ \t]+)/;
+/**
+ * Heading, blockquote, bullet, and ordered-list markers — line-leading only.
+ *
+ * A bullet's optional `[ ]` / `[x]` goes with it: a task item renders as a
+ * checkbox widget, so the brackets carry no text a selection could contain.
+ */
+const BLOCK_MARKER = /^(?:#{1,6}[ \t]+|>[ \t]?|(?:[-*+]|\d{1,9}[.)])[ \t]+(?:\[[ xX]\][ \t]+)?)/;
/** Widest block marker worth considering; bounds the slice the regex runs on. */
const BLOCK_MARKER_WINDOW = 32;
+/**
+ * Table cell boundaries render as the gap between cells, never as a character.
+ * Elastic for the same reason a bullet's `- ` is: a selection crossing two
+ * cells arrives with the cell texts run together.
+ */
+const TABLE_PIPE = '|';
+
+/**
+ * Source lines that render as no text whatsoever, matched whole.
+ *
+ * Unlike a bullet's `- `, these are not a marker in front of content — the
+ * entire line is invisible to anyone selecting rendered text, so skipping one
+ * character at a time cannot get past them. A code fence is the case that
+ * reached users: the delimiter's backticks were already elastic, but the info
+ * string after them (```` ```ts ````) was not, so every selection that crossed
+ * into or out of a language-tagged code block failed to anchor.
+ *
+ * Each alternative must match to end-of-line, so a line carrying real content
+ * can never be swallowed: `***bold***` is not a thematic break, and a paragraph
+ * opening `-- ` is not a table rule.
+ */
+const INVISIBLE_LINE =
+ // Fenced-code delimiter: opener plus its info string, or the closer.
+ /^(?:`{3,}[^`\n]*|~{3,}[^\n]*)$/;
+
+/** Thematic break, setext heading underline, and table delimiter row. */
+const INVISIBLE_RULE_LINE = /^(?:(?:[-*_][ \t]*){3,}|=+[ \t]*|[|\-: \t]*-[|\-: \t]*)$/;
+
+/**
+ * Longest line still worth testing against the whole-line patterns. Past this a
+ * line is prose or minified data, not a fence or a rule, and the scan should not
+ * pay for the slice.
+ */
+const INVISIBLE_LINE_WINDOW = 1024;
+
+/**
+ * Length of the whole-line construct starting at `i`, or 0 when the line
+ * renders as something. Caller must have established that `i` is a line start.
+ */
+function invisibleLineRunAt(text: string, i: number): number {
+ const brk = text.indexOf('\n', i);
+ let end = brk === -1 ? text.length : brk;
+ // A CRLF document leaves the `\r` on this slice, and none of the rule
+ // patterns' character classes admit it — `$` could never match, so a
+ // thematic break or table rule stayed non-elastic on Windows line endings.
+ // Trimmed rather than admitted, so the run stops before the `\r` and the
+ // whitespace rule consumes it like any other space.
+ if (end > i && text[end - 1] === '\r') end -= 1;
+ if (end - i > INVISIBLE_LINE_WINDOW) return 0;
+ const line = text.slice(i, end);
+ if (line.length === 0) return 0;
+ if (!INVISIBLE_LINE.test(line) && !INVISIBLE_RULE_LINE.test(line)) return 0;
+ return line.length;
+}
+
function isSpace(ch: string): boolean {
return ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r' || ch === '\f' || ch === '\v';
}
@@ -76,6 +136,14 @@ function isLineStart(text: string, i: number): boolean {
function syntaxRunAt(text: string, i: number): number {
const ch = text[i];
if (ch === undefined) return 0;
+ // Whole-line constructs first: a fence and a thematic break both open with a
+ // character that is also inline syntax, and consuming it one at a time leaves
+ // the rest of the line (`ts`, `- - -`) looking like content.
+ if (isLineStart(text, i)) {
+ const line = invisibleLineRunAt(text, i);
+ if (line > 0) return line;
+ }
+ if (ch === TABLE_PIPE) return 1;
if (INLINE_SYNTAX.has(ch)) return 1;
// `[label](target)` and `[[target]]` both render as their label alone, so the
// brackets and the whole `](target)` tail are invisible to a caller working
diff --git a/packages/server/src/comments/comment-service.test.ts b/packages/server/src/comments/comment-service.test.ts
index 20071582e..ec816519f 100644
--- a/packages/server/src/comments/comment-service.test.ts
+++ b/packages/server/src/comments/comment-service.test.ts
@@ -181,6 +181,44 @@ describe('CommentService — create / read / list', () => {
);
});
+ test('anchors a selection dragged across a language-tagged code block', async () => {
+ // The reported 400: a fence's backticks were already elastic but the info
+ // string after them was not, so every selection crossing into or out of a
+ // tagged code block died on the `ts`.
+ bodies.set(
+ 'specs/language',
+ 'Add `appearance.language` to `ConfigSchema`:\n\n```ts\nlanguage: z\n .optional(),\n```\n\nAcceptance: the leaf validates.',
+ );
+ const meta = await svc.createThread({
+ docName: 'specs/language',
+ quote: 'to ConfigSchema:\nlanguage: z\n .optional(),\nAcceptance: the leaf validates.',
+ author: 'principal-abc',
+ body: 'is this the right scope?',
+ });
+ expect(meta.state).toBe('anchored');
+ const body = bodies.get('specs/language') ?? '';
+ // The stored range covers the real source, fence and all.
+ expect(body.slice(meta.anchor.start, meta.anchor.end)).toContain('```ts');
+ });
+
+ test('anchors a selected table row', async () => {
+ // Picking a row hands over the cell texts with the pipes and padding gone,
+ // so the row is not a literal substring of the source line.
+ bodies.set(
+ 'notes/freezing',
+ '| Method | Temperature | Hold time |\n| --- | --- | --- |\n| 1 | -4F or below | >= 168 hours |\n| 2 | -31F or below | >= 15 hours |',
+ );
+ const meta = await svc.createThread({
+ docName: 'notes/freezing',
+ quote: '2\n-31F or below\n>= 15 hours',
+ author: 'principal-abc',
+ body: 'is this still current?',
+ });
+ expect(meta.state).toBe('anchored');
+ const body = bodies.get('notes/freezing') ?? '';
+ expect(body.slice(meta.anchor.start, meta.anchor.end)).toBe('2 | -31F or below | >= 15 hours');
+ });
+
test('relaxed matching still refuses different words', async () => {
bodies.set('notes/steps', '## Steps\n\n1. Heat oven to 425F.');
await expect(
diff --git a/scripts/render-release-downloads.mjs b/scripts/render-release-downloads.mjs
new file mode 100644
index 000000000..705bd6a17
--- /dev/null
+++ b/scripts/render-release-downloads.mjs
@@ -0,0 +1,151 @@
+#!/usr/bin/env node
+/**
+ * Render a marker-delimited "Downloads" table into a GitHub Release body,
+ * built from the assets that are ACTUALLY attached to the Release — a row
+ * never appears for an installer that failed to upload.
+ *
+ * Why marker-delimited: the release body is not ours alone. The beta cadence
+ * embeds a hidden `<!-- ok-consumed-set: … -->` marker that
+ * compute-next-beta.mjs reads back from the previous beta's body, and the
+ * Slack/Discord announcements + aggregate-stable-changelog.mjs all consume
+ * the body downstream. Replacing ONLY the span between
+ * `<!-- ok-downloads:start -->` and `<!-- ok-downloads:end -->` keeps every
+ * other byte of the body intact and makes re-renders idempotent; the
+ * downstream consumers strip the block on their side.
+ *
+ * Usage:
+ * gh release view "$TAG" --json body,assets \
+ * | node scripts/render-release-downloads.mjs --tag v0.43.0 --repo inkeep/open-knowledge
+ *
+ * Reads `{body, assets: [{name}]}` JSON on stdin, emits the updated body on
+ * stdout. Download URLs are tag-specific (`releases/download/<tag>/…`), so
+ * the table stays correct after a newer release claims `latest`.
+ */
+import { pathToFileURL } from 'node:url';
+
+export const DOWNLOADS_START = '<!-- ok-downloads:start -->';
+export const DOWNLOADS_END = '<!-- ok-downloads:end -->';
+
+/**
+ * The known user-facing installers, in display order. Update manifests,
+ * blockmaps, and the mac updater zip are deliberately absent — they are
+ * updater plumbing, not human downloads (the versioned mac zip exists only
+ * because Squirrel.Mac requires a zip for the in-place swap).
+ *
+ * `match` is a predicate on the asset name rather than a literal so the one
+ * versioned name shape (none today) or a future arch addition stays a
+ * one-line change.
+ */
+const ROWS = [
+ { platform: 'macOS', arch: 'Apple Silicon', match: (n) => n === 'OpenKnowledge-arm64.dmg' },
+ { platform: 'Windows', arch: 'x64', match: (n) => n === 'OpenKnowledge-Setup-x64.exe' },
+ { platform: 'Windows', arch: 'arm64', match: (n) => n === 'OpenKnowledge-Setup-arm64.exe' },
+ { platform: 'Debian / Ubuntu', arch: 'x64', match: (n) => n === 'OpenKnowledge-amd64.deb' },
+ { platform: 'Debian / Ubuntu', arch: 'arm64', match: (n) => n === 'OpenKnowledge-arm64.deb' },
+ { platform: 'Fedora / RHEL', arch: 'x64', match: (n) => n === 'OpenKnowledge-x86_64.rpm' },
+ { platform: 'Fedora / RHEL', arch: 'arm64', match: (n) => n === 'OpenKnowledge-aarch64.rpm' },
+];
+
+/**
+ * Remove the Downloads block (markers + content) from a body. Exported for
+ * the consumers that must not carry the table forward —
+ * build-slack-release-payload.mjs and aggregate-stable-changelog.mjs keep
+ * inlined VARIANTS of this regex (they are fetched/run standalone in
+ * workflows, so a cross-file import would break there). Deliberately not
+ * byte-identical: this copy alone carries the `\n?` boundary anchors and the
+ * `'\n'` replacement, because only the upsert path must keep the
+ * strip→re-append cycle byte-stable; the consumers replace with `''` and let
+ * their own whitespace collapse absorb the residue. Each site's tests pin
+ * its own behavior.
+ *
+ * @param {string} body
+ * @returns {string}
+ */
+export function stripDownloadsBlock(body) {
+ return body.replace(
+ /\n?<!-- ok-downloads:start -->[\s\S]*?<!-- ok-downloads:end -->\n?/g,
+ '\n',
+ );
+}
+
+/**
+ * @param {{tag: string, repo: string, assetNames: string[]}} input
+ * @returns {string|null} The rendered block, or null when no known installer
+ * is present (a body should not gain an empty Downloads section).
+ */
+export function renderDownloadsBlock({ tag, repo, assetNames }) {
+ const rows = ROWS.flatMap((row) => {
+ const name = assetNames.find((n) => row.match(n));
+ if (!name) return [];
+ const url = `https://github.com/${repo}/releases/download/${encodeURIComponent(tag)}/${encodeURIComponent(name)}`;
+ return [`| ${row.platform} | ${row.arch} | [${name}](${url}) |`];
+ });
+ if (rows.length === 0) return null;
+ return [
+ DOWNLOADS_START,
+ '## Downloads',
+ '',
+ '| Platform | Architecture | Download |',
+ '| --- | --- | --- |',
+ ...rows,
+ DOWNLOADS_END,
+ ].join('\n');
+}
+
+/**
+ * Insert or replace the Downloads block in a release body.
+ *
+ * The block lands at the END of the body — after the changelog and the
+ * consumed-set marker — so everything upstream of it stays byte-identical
+ * and position-sensitive readers of the body are unaffected.
+ *
+ * @param {{body: string, tag: string, repo: string, assetNames: string[]}} input
+ * @returns {string} The updated body (unchanged when there is nothing to render).
+ */
+export function upsertDownloadsBlock({ body, tag, repo, assetNames }) {
+ const block = renderDownloadsBlock({ tag, repo, assetNames });
+ const withoutOld = stripDownloadsBlock(body);
+ if (block == null) return withoutOld === body ? body : withoutOld;
+ const trimmed = withoutOld.replace(/\s+$/, '');
+ return trimmed.length > 0 ? `${trimmed}\n\n${block}\n` : `${block}\n`;
+}
+
+function parseArgs(argv) {
+ const args = { tag: '', repo: '' };
+ for (let i = 0; i < argv.length; i += 1) {
+ if (argv[i] === '--tag') args.tag = argv[i + 1] ?? '';
+ if (argv[i] === '--repo') args.repo = argv[i + 1] ?? '';
+ }
+ return args;
+}
+
+function main() {
+ const { tag, repo } = parseArgs(process.argv.slice(2));
+ if (!tag || !repo) {
+ process.stderr.write('usage: render-release-downloads.mjs --tag <vX.Y.Z> --repo <owner/name> (release JSON on stdin)\n');
+ process.exitCode = 1;
+ return;
+ }
+ const chunks = [];
+ process.stdin.on('data', (c) => chunks.push(c));
+ process.stdin.on('end', () => {
+ let release;
+ try {
+ release = JSON.parse(Buffer.concat(chunks).toString('utf8'));
+ } catch (error) {
+ process.stderr.write(`render-release-downloads: stdin is not valid JSON (${error.message})\n`);
+ process.exitCode = 1;
+ return;
+ }
+ const body = typeof release.body === 'string' ? release.body : '';
+ const assetNames = Array.isArray(release.assets)
+ ? release.assets.map((a) => a?.name).filter((n) => typeof n === 'string')
+ : [];
+ process.stdout.write(upsertDownloadsBlock({ body, tag, repo, assetNames }));
+ });
+}
+
+// Run main() only as a CLI, not when imported by the test file.
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+ main();
+}
diff --git a/scripts/render-release-downloads.test.mjs b/scripts/render-release-downloads.test.mjs
new file mode 100644
index 000000000..b045240eb
--- /dev/null
+++ b/scripts/render-release-downloads.test.mjs
@@ -0,0 +1,152 @@
+import { describe, expect, test } from 'vitest';
+import {
+ DOWNLOADS_END,
+ DOWNLOADS_START,
+ renderDownloadsBlock,
+ stripDownloadsBlock,
+ upsertDownloadsBlock,
+} from './render-release-downloads.mjs';
+
+const REPO = 'inkeep/open-knowledge';
+const TAG = 'v0.43.0';
+
+const ALL_INSTALLERS = [
+ 'OpenKnowledge-arm64.dmg',
+ 'OpenKnowledge-Setup-x64.exe',
+ 'OpenKnowledge-Setup-arm64.exe',
+ 'OpenKnowledge-amd64.deb',
+ 'OpenKnowledge-arm64.deb',
+ 'OpenKnowledge-x86_64.rpm',
+ 'OpenKnowledge-aarch64.rpm',
+];
+
+// The full asset set a release carries — installers plus updater plumbing
+// that must NOT get table rows.
+const ALL_ASSETS = [
+ ...ALL_INSTALLERS,
+ 'OpenKnowledge-arm64.dmg.blockmap',
+ 'OpenKnowledge-0.43.0-arm64-mac.zip',
+ 'OpenKnowledge-0.43.0-arm64-mac.zip.blockmap',
+ 'latest-mac.yml',
+ 'latest.yml',
+ 'latest-linux.yml',
+ 'latest-linux-arm64.yml',
+];
+
+// A beta body shaped like the cadence produces: lead, changelog section, and
+// the hidden consumed-set marker compute-next-beta.mjs reads back.
+const BETA_BODY = 'Delta since previous beta v0.43.0-beta.4\n\n### Patch Changes\n\n- fix a thing\n\n<!-- ok-consumed-set: ["abc"] -->\n';
+
+describe('renderDownloadsBlock', () => {
+ test('renders one row per present installer, none for updater plumbing', () => {
+ const block = renderDownloadsBlock({ tag: TAG, repo: REPO, assetNames: ALL_ASSETS });
+ for (const name of ALL_INSTALLERS) {
+ expect(block).toContain(`[${name}](https://github.com/${REPO}/releases/download/${TAG}/${name})`);
+ }
+ expect(block).not.toContain('mac.zip');
+ expect(block).not.toContain('.blockmap');
+ expect(block).not.toContain('.yml');
+ });
+
+ test('omits rows for absent installers instead of rendering dead links', () => {
+ const block = renderDownloadsBlock({
+ tag: TAG,
+ repo: REPO,
+ assetNames: ['OpenKnowledge-arm64.dmg', 'OpenKnowledge-amd64.deb'],
+ });
+ expect(block).toContain('OpenKnowledge-arm64.dmg');
+ expect(block).toContain('OpenKnowledge-amd64.deb');
+ expect(block).not.toContain('Setup-x64');
+ expect(block).not.toContain('.rpm');
+ });
+
+ test('returns null when no known installer is attached', () => {
+ expect(renderDownloadsBlock({ tag: TAG, repo: REPO, assetNames: ['latest.yml'] })).toBeNull();
+ expect(renderDownloadsBlock({ tag: TAG, repo: REPO, assetNames: [] })).toBeNull();
+ });
+
+ test('URLs are tag-pinned, never latest/download', () => {
+ const block = renderDownloadsBlock({ tag: TAG, repo: REPO, assetNames: ALL_ASSETS });
+ expect(block).toContain(`/releases/download/${TAG}/`);
+ expect(block).not.toContain('/releases/latest/');
+ });
+});
+
+describe('upsertDownloadsBlock', () => {
+ test('appends the block after the existing body, preserving it byte-for-byte', () => {
+ const out = upsertDownloadsBlock({
+ body: BETA_BODY,
+ tag: TAG,
+ repo: REPO,
+ assetNames: ALL_ASSETS,
+ });
+ // Everything before the block is the original body (modulo the trailing
+ // whitespace the append normalizes).
+ expect(out.startsWith(BETA_BODY.trimEnd())).toBe(true);
+ // The consumed-set marker survives — compute-next-beta.mjs reads it back.
+ expect(out).toContain('<!-- ok-consumed-set: ["abc"] -->');
+ expect(out).toContain(DOWNLOADS_START);
+ expect(out).toContain(DOWNLOADS_END);
+ });
+
+ test('is idempotent: re-rendering replaces the previous block, never stacks', () => {
+ const once = upsertDownloadsBlock({ body: BETA_BODY, tag: TAG, repo: REPO, assetNames: ALL_ASSETS });
+ const twice = upsertDownloadsBlock({ body: once, tag: TAG, repo: REPO, assetNames: ALL_ASSETS });
+ expect(twice).toBe(once);
+ expect(twice.split(DOWNLOADS_START).length).toBe(2); // exactly one occurrence
+ });
+
+ test('a re-render with fewer assets drops the missing rows', () => {
+ const once = upsertDownloadsBlock({ body: BETA_BODY, tag: TAG, repo: REPO, assetNames: ALL_ASSETS });
+ const rerender = upsertDownloadsBlock({
+ body: once,
+ tag: TAG,
+ repo: REPO,
+ assetNames: ['OpenKnowledge-arm64.dmg'],
+ });
+ expect(rerender).toContain('OpenKnowledge-arm64.dmg');
+ expect(rerender).not.toContain('Setup-x64');
+ });
+
+ test('no installers → the body stays unchanged (no empty Downloads section)', () => {
+ expect(
+ upsertDownloadsBlock({ body: BETA_BODY, tag: TAG, repo: REPO, assetNames: ['latest.yml'] }),
+ ).toBe(BETA_BODY);
+ });
+
+ test('a re-render with NO installers strips a previously-rendered block', () => {
+ // A stale table left behind here would carry dead links to assets that
+ // were never uploaded — the strip-on-empty path is load-bearing, not a
+ // formality of the null-block branch.
+ const withBlock = upsertDownloadsBlock({ body: BETA_BODY, tag: TAG, repo: REPO, assetNames: ALL_ASSETS });
+ const rerender = upsertDownloadsBlock({
+ body: withBlock,
+ tag: TAG,
+ repo: REPO,
+ assetNames: ['latest.yml'],
+ });
+ expect(rerender).not.toContain(DOWNLOADS_START);
+ expect(rerender).not.toContain('## Downloads');
+ expect(rerender).toContain('<!-- ok-consumed-set: ["abc"] -->');
+ });
+
+ test('works on an empty body (manual releases have none)', () => {
+ const out = upsertDownloadsBlock({ body: '', tag: TAG, repo: REPO, assetNames: ALL_ASSETS });
+ expect(out.startsWith(DOWNLOADS_START)).toBe(true);
+ });
+});
+
+describe('stripDownloadsBlock', () => {
+ test('removes the block and leaves the rest of the body intact', () => {
+ const withBlock = upsertDownloadsBlock({ body: BETA_BODY, tag: TAG, repo: REPO, assetNames: ALL_ASSETS });
+ const stripped = stripDownloadsBlock(withBlock);
+ expect(stripped).not.toContain(DOWNLOADS_START);
+ expect(stripped).not.toContain('## Downloads');
+ expect(stripped).toContain('<!-- ok-consumed-set: ["abc"] -->');
+ expect(stripped).toContain('fix a thing');
+ });
+
+ test('passes through a body with no block untouched', () => {
+ expect(stripDownloadsBlock(BETA_BODY)).toBe(BETA_BODY);
+ });
+});