Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Comments feature (#2944)

shagun-singh-inkeep88cab6e67c21
diff --git a/.changeset/comments-v1.md b/.changeset/comments-v1.md
new file mode 100644
index 000000000..8d1a0167a
--- /dev/null
+++ b/.changeset/comments-v1.md
@@ -0,0 +1,19 @@
+---
+'@inkeep/open-knowledge': minor
+---
+
+Comments are the queue for your agent. Highlight a passage, say what's wrong, keep reading — the comment is filed against the exact words you picked, and nothing is sent until you decide the pass is done.
+
+| Before | After |
+| --- | --- |
+| Five things to fix meant five trips to a chat window | Comment on each, send once |
+| Retype the passage so the agent can find it again | The comment carries the words it points at |
+| Lose your place in the doc every time | Never leave it |
+
+**The queue spans files.** Comment on three passages here, open another file, comment on two more, then send. One agent turn, edits landing in both documents. Uncheck anything you changed your mind about before it goes.
+
+**Send now or send later.** Writing a comment offers both: *Add Comment* files it for the batch, *Send to AI* hands it over immediately. Either way the comment box takes `@` mentions of files, the same as the Ask AI composer, and mentions reach the agent as real paths.
+
+**Sends find the conversation you're already in.** With a chat open, the queue lands in it rather than starting a detached one; with none open, it starts one. The send button says which before you click it.
+
+Comments are stored per-machine next to your content and are not committed — a comment here is a note to your own agent, not a message to a teammate.
diff --git a/packages/app/package.json b/packages/app/package.json
index 34a897110..51523868f 100644
--- a/packages/app/package.json
+++ b/packages/app/package.json
@@ -52,7 +52,7 @@
{
"name": "all JS chunks combined (gzipped)",
"path": "dist/assets/*.js",
- "limit": "3.62 MB",
+ "limit": "3.7 MB",
"gzip": true,
"running": false
},
diff --git a/packages/app/src/comments/CommentBubbleButton.tsx b/packages/app/src/comments/CommentBubbleButton.tsx
new file mode 100644
index 000000000..504c57930
--- /dev/null
+++ b/packages/app/src/comments/CommentBubbleButton.tsx
@@ -0,0 +1,39 @@
+/**
+ * "Ask AI" button for the WYSIWYG selection toolbar (bubble menu).
+ *
+ * Named for what the composer it opens can do, not for the storage that backs
+ * it. That composer offers both filing the note for a later batch and handing it
+ * to an agent now — labelling the entry "Comment" advertised only the first, so
+ * reaching for an agent on a passage looked unsupported from the one toolbar
+ * where you would look for it.
+ *
+ * Clicking emits the start-comment intent; `CommentSelectionAffordance` opens
+ * the composer on the current selection.
+ */
+
+import { Trans } from '@lingui/react/macro';
+import { Sparkles } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Separator } from '@/components/ui/separator';
+import { emitStartComment } from './store';
+
+export function CommentBubbleButton() {
+ return (
+ <>
+ <Separator orientation="vertical" className="mx-0.5 h-5 data-vertical:self-center" />
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ data-testid="comment-bubble-button"
+ className="gap-1 px-2 text-sm font-medium text-accent-foreground/80"
+ onClick={() => emitStartComment()}
+ >
+ <Sparkles className="size-3.5" aria-hidden="true" />
+ <span>
+ <Trans>Ask AI</Trans>
+ </span>
+ </Button>
+ </>
+ );
+}
diff --git a/packages/app/src/comments/CommentMarginRail.tsx b/packages/app/src/comments/CommentMarginRail.tsx
new file mode 100644
index 000000000..4d5c799a0
--- /dev/null
+++ b/packages/app/src/comments/CommentMarginRail.tsx
@@ -0,0 +1,245 @@
+/**
+ * Comment scrubber rail.
+ *
+ * A thin right-edge rail of small comment ICONS — one per open thread — each
+ * sitting BESIDE the line it is anchored to. Clicking one scrolls to the passage
+ * and opens its thread (via the shared open-thread bus → the click-at-text
+ * popover).
+ *
+ * Position comes from `view.coordsAtPos`, i.e. where the text actually is on
+ * screen, so an icon lines up with its own sentence. It deliberately does NOT
+ * map a document fraction onto the pane: the scroll container also holds the
+ * cover and the frontmatter table, which ProseMirror knows nothing about, so a
+ * fraction of the BODY drawn over the whole PANE puts every marker above its
+ * text by however tall the properties happen to be.
+ *
+ * Two adjustments keep it readable. Icons that would overlap are pushed down in
+ * document order, so a cluster stacks instead of piling on one point. A comment
+ * scrolled out of view clamps to the nearest edge and dims — it stops claiming
+ * to point at a line, while still saying "there is more this way".
+ *
+ * Recomputes on scroll, thread changes, doc edits, and container resize.
+ */
+
+import { useLingui } from '@lingui/react/macro';
+import type { Editor } from '@tiptap/react';
+import { MessageSquare } from 'lucide-react';
+import { useEffect, useState } from 'react';
+import { createPortal } from 'react-dom';
+import { Button } from '@/components/ui/button';
+import { getEditorView } from '@/editor/utils/get-editor-view';
+import { cn } from '@/lib/utils';
+import { buildTextIndex, findQuoteRange, findRangeInIndex } from './anchor-search';
+import {
+ propertyRowRect,
+ revealPropertyValueRange,
+ scrollPropertyRowIntoView,
+} from './property-row-rect';
+import { findScrollContainer, scrollAnchorIntoView } from './scroll-to-anchor';
+import {
+ clearActiveThread,
+ emitOpenThreadPopover,
+ setActiveThread,
+ subscribeOpenThreadPopover,
+ useCommentThreads,
+} from './store';
+
+const RAIL_WIDTH = 34;
+const ICON_H = 30;
+const GAP = 4;
+
+interface RailBox {
+ top: number;
+ height: number;
+ left: number;
+}
+
+interface MarkerPosition {
+ id: string;
+ top: number;
+ /** The anchored line is scrolled out of view; the icon is clamped to an edge. */
+ offscreen: boolean;
+}
+
+/**
+ * Place each marker beside its line, in viewport coordinates.
+ *
+ * Exported for test: this is the geometry that was wrong before — a marker's y
+ * has to come from where the TEXT is, and everything here is about what happens
+ * once it does. Pure so it can be checked without a laid-out editor.
+ */
+export function layoutMarkers(
+ targets: readonly { id: string; y: number }[],
+ railTop: number,
+ railHeight: number,
+): MarkerPosition[] {
+ const ordered = [...targets].sort((a, b) => a.y - b.y);
+ const maxTop = railTop + railHeight - ICON_H;
+ const out: MarkerPosition[] = [];
+ let prevBottom = railTop - GAP;
+ for (const item of ordered) {
+ const offscreen = item.y < railTop || item.y > railTop + railHeight;
+ // Center on the line rather than hanging below its baseline.
+ const wanted = item.y - ICON_H / 2;
+ const top = Math.min(maxTop, Math.max(wanted, prevBottom + GAP, railTop));
+ out.push({ id: item.id, top, offscreen });
+ prevBottom = top + ICON_H;
+ }
+ return out;
+}
+
+export function CommentMarginRail({ editor, docName }: { editor: Editor; docName: string }) {
+ const { t } = useLingui();
+ const threads = useCommentThreads(docName);
+ const [activeId, setActiveId] = useState<string | null>(null);
+ const [rail, setRail] = useState<RailBox | null>(null);
+ const [positions, setPositions] = useState<MarkerPosition[]>([]);
+
+ useEffect(() => subscribeOpenThreadPopover((id) => setActiveId(id)), []);
+
+ useEffect(() => {
+ const view = getEditorView(editor);
+ if (!view) return;
+ const container = findScrollContainer(view.dom);
+ if (!container) return;
+ // Both kinds, placed from different sources in one pass. A body thread's y
+ // comes from ProseMirror; a property's comes from its row in the properties
+ // table, which lives in this same scroll container. What a property must
+ // never do is fall through to the quote search — its key would match
+ // ordinary prose and put the marker on a passage nobody commented on.
+ const open = threads.filter(
+ (thread) =>
+ thread.status === 'open' && (thread.target.kind === 'property' || thread.anchor !== null),
+ );
+
+ const compute = () => {
+ const rect = container.getBoundingClientRect();
+ const targets: { id: string; y: number }[] = [];
+ if (open.length > 0) {
+ // ONE index for the whole pass. `findQuoteRange` builds one internally,
+ // so calling it per thread walked the entire document once per comment
+ // — and this runs on every scroll frame and every edit. Measured at 40
+ // comments in a 100k-character document that was ~35 ms a frame, about
+ // twenty times what resolving them against a shared index costs.
+ const index = buildTextIndex(editor.state.doc);
+ for (const thread of open) {
+ let y: number;
+ if (thread.target.kind === 'property') {
+ // Null when the properties disclosure is collapsed or the key is
+ // gone — nothing on screen to sit beside, so no marker.
+ const rect = propertyRowRect(thread.target.key);
+ if (rect === null) continue;
+ y = rect.top + rect.height / 2;
+ } else {
+ if (thread.anchor === null) continue;
+ const range = findRangeInIndex(index, thread.anchor.quote, thread.anchor);
+ if (range === null) continue;
+ try {
+ // Viewport coords of the anchored text itself. Throws for a position
+ // ProseMirror has not laid out (mid-remount); skip rather than guess.
+ y = view.coordsAtPos(range.from).top;
+ } catch {
+ continue;
+ }
+ }
+ targets.push({ id: thread.id, y });
+ }
+ }
+ setRail({ top: rect.top, height: rect.height, left: rect.right - RAIL_WIDTH });
+ setPositions(layoutMarkers(targets, rect.top, rect.height));
+ };
+
+ compute();
+ let frame = 0;
+ const onChange = () => {
+ // Scroll fires per frame; coalesce so a fast flick does one layout pass.
+ if (frame !== 0) return;
+ frame = requestAnimationFrame(() => {
+ frame = 0;
+ compute();
+ });
+ };
+ window.addEventListener('resize', onChange);
+ container.addEventListener('scroll', onChange, { passive: true });
+ const observer = new ResizeObserver(onChange);
+ observer.observe(container);
+ editor.on('update', onChange);
+ return () => {
+ if (frame !== 0) cancelAnimationFrame(frame);
+ window.removeEventListener('resize', onChange);
+ container.removeEventListener('scroll', onChange);
+ observer.disconnect();
+ editor.off('update', onChange);
+ };
+ }, [editor, threads]);
+
+ function jumpTo(threadId: string) {
+ // Second click on the marker you are already reading closes it. The rail
+ // mirrors the popover's own state, so this stays right when the popover was
+ // dismissed some other way (Escape, a click in the document).
+ if (activeId === threadId) {
+ emitOpenThreadPopover(null);
+ return;
+ }
+ const thread = threads.find((x) => x.id === threadId);
+ if (thread?.target.kind === 'property') {
+ // Selecting the words is the only highlight a `<textarea>` can show. A
+ // whole-field comment has no words, and a value passage whose text has
+ // moved on falls back to the same place — the row itself.
+ const revealed =
+ thread.anchor !== null &&
+ revealPropertyValueRange({
+ key: thread.target.key,
+ path: thread.target.path,
+ quote: thread.anchor.quote,
+ start: thread.anchor.start,
+ end: thread.anchor.end,
+ });
+ if (!revealed) scrollPropertyRowIntoView(thread.target.key);
+ } else if (thread && thread.anchor !== null) {
+ const range = findQuoteRange(editor.state.doc, thread.anchor.quote, thread.anchor);
+ if (range) scrollAnchorIntoView(editor, range);
+ }
+ emitOpenThreadPopover(threadId);
+ }
+
+ if (rail === null || positions.length === 0) return null;
+
+ return createPortal(
+ <div
+ className="pointer-events-none fixed z-30"
+ style={{ top: rail.top, height: rail.height, left: rail.left, width: RAIL_WIDTH }}
+ >
+ {positions.map((pos) => {
+ const thread = threads.find((x) => x.id === pos.id);
+ if (!thread) return null;
+ const active = pos.id === activeId;
+ return (
+ <Button
+ key={pos.id}
+ type="button"
+ variant="ghost"
+ aria-label={active ? t`Close comment` : t`Open comment`}
+ aria-expanded={active}
+ className={cn(
+ 'pointer-events-auto absolute left-0 size-7 rounded-full border bg-background p-0 shadow-sm transition-colors hover:bg-muted',
+ // Dimmed: it is parked at the edge, not pointing at the line beside it.
+ pos.offscreen && 'opacity-40 hover:opacity-100',
+ active && 'border-amber-500 bg-amber-50',
+ )}
+ style={{ top: pos.top - rail.top }}
+ data-comment-thread={thread.id}
+ onClick={() => jumpTo(thread.id)}
+ // Which line a marker belongs to is otherwise a guess when several
+ // stack up — hovering it deepens that comment's passage.
+ onPointerEnter={() => setActiveThread(thread.id)}
+ onPointerLeave={() => clearActiveThread(thread.id)}
+ >
+ <MessageSquare className="size-3.5 text-amber-500" />
+ </Button>
+ );
+ })}
+ </div>,
+ document.body,
+ );
+}
diff --git a/packages/app/src/comments/CommentQueuePanel.tsx b/packages/app/src/comments/CommentQueuePanel.tsx
new file mode 100644
index 000000000..b6d486745
--- /dev/null
+++ b/packages/app/src/comments/CommentQueuePanel.tsx
@@ -0,0 +1,261 @@
+/**
+ * The dispatch queue as a doc-panel tab.
+ *
+ * Project-scoped (comments across every file), shown under the Comments tab's
+ * "Queue" scope — the same batch the composer's comments chip carries. Every
+ * queued comment is pre-selected; deselect any to exclude it, then Send hands
+ * the checked threads to an agent and removes them (deselected ones stay for a
+ * later batch).
+ *
+ * Cards sit under a per-file heading rather than each carrying a file badge —
+ * the queue spans documents, and with several comments on the same file the
+ * badge repeated the same name down the rail while stealing the width the ✕
+ * needed.
+ *
+ * The actions sit in a pinned footer rather than after the list, so a queue of
+ * twenty scrolls UNDER them instead of pushing Send off the bottom.
+ */
+
+import { Trans, useLingui } from '@lingui/react/macro';
+import { FileText, X } from 'lucide-react';
+import { RegisteredAgentIcon } from '@/components/acp/RegisteredAgentIcon';
+import { AgentSplitButton } from '@/components/handoff/AgentSplitButton';
+import { TargetIcon } from '@/components/handoff/OpenInAgentMenuItem';
+import { cliIconTargetId } from '@/components/handoff/terminal-cli-display';
+import { useReusableSession } from '@/components/reusable-session-store';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { Checkbox } from '@/components/ui/checkbox';
+import {
+ Panel,
+ PanelBody,
+ PanelCount,
+ PanelEmpty,
+ PanelFooter,
+ PanelHeader,
+ PanelTitle,
+} from '@/components/ui/panel';
+import { openAgentSettings } from '@/lib/use-settings-route';
+import { appendQueueToOpenSession } from './append-to-open-session';
+import { docBasename, revealThread, ThreadTargetLine } from './comment-chips';
+import { QueueNewChatRow } from './QueueNewChatRow';
+import { groupByDoc } from './queue-grouping';
+import {
+ clearQueue,
+ dispatchComments,
+ getThreadById,
+ removeFromQueue,
+ toggleQueueSelection,
+ useQueue,
+ useQueueSelection,
+} from './store';
+import { useCommentAgentPicker } from './use-comment-agent-picker';
+import { useCommentDispatch } from './use-comment-delivery';
+
+export function CommentQueuePanel() {
+ const { t } = useLingui();
+ const picker = useCommentAgentPicker();
+ const composeFreshTurn = useCommentDispatch();
+ const queue = useQueue();
+ const selectedIds = useQueueSelection();
+ const items = queue.map((id) => getThreadById(id)).filter((thread) => thread !== null);
+ const selectedCount = items.filter((thread) => selectedIds.includes(thread.id)).length;
+ // The send picks its own destination: a live chat takes the batch, and with
+ // none open it starts one. Published by the dock itself, so the button can
+ // never promise an append the host would then refuse — and not keyed on the
+ // dock's position, which hosts the same sessions bottom or right.
+ const openSession = useReusableSession();
+ /**
+ * The mark for where a send actually goes.
+ *
+ * Drawn from the OPEN SESSION when there is one — not from the agent
+ * preference, which is what a fresh turn would use. The two disagree the
+ * moment you switch tabs, and the icon claiming Claude while the button
+ * points at a Cursor tab is exactly that disagreement.
+ */
+ const destinationIcon =
+ openSession === null ? (
+ picker.isThreadSelected ? (
+ <RegisteredAgentIcon
+ agentId={picker.threadAgent?.id ?? ''}
+ iconUrl={picker.threadAgent?.iconUrl}
+ className="size-4"
+ />
+ ) : picker.cli !== null ? (
+ <TargetIcon id={cliIconTargetId(picker.cli)} className="size-4" aria-hidden />
+ ) : picker.target ? (
+ <TargetIcon id={picker.target.id} className="size-4" aria-hidden />
+ ) : undefined
+ ) : openSession.kind === 'thread' ? (
+ <RegisteredAgentIcon
+ agentId={openSession.agentId}
+ iconUrl={openSession.iconUrl}
+ className="size-4"
+ />
+ ) : (
+ <TargetIcon id={cliIconTargetId(openSession.cli)} className="size-4" aria-hidden />
+ );
+ /**
+ * Send to the chat that is open, or start one.
+ *
+ * The two halves behave differently on purpose. A fresh turn RUNS the batch,
+ * so it resolves what ships. An append lands in the live session's input
+ * UNSENT — a thread takes it as a staged draft, a live CLI as a
+ * no-carriage-return write — so the human presses enter, nothing has shipped,
+ * and the queue is left intact.
+ */
+ function sendQueue(): void {
+ if (openSession === null) {
+ // A fresh turn RUNS the batch, so it resolves what ships.
+ void dispatchComments({ compose: composeFreshTurn });
+ return;
+ }
+ // An append lands UNSENT in the live session's input, so nothing resolves —
+ // the human still has to press enter.
+ void appendQueueToOpenSession();
+ }
+
+ return (
+ <Panel>
+ <PanelHeader>
+ <PanelTitle>
+ <Trans>Queue</Trans>
+ </PanelTitle>
+ <PanelCount>{queue.length}</PanelCount>
+ </PanelHeader>
+ <PanelBody className="flex flex-col gap-4">
+ {items.length === 0 ? (
+ <PanelEmpty>
+ <Trans>Nothing queued. Comment on a passage to add it here.</Trans>
+ </PanelEmpty>
+ ) : (
+ groupByDoc(items).map((group) => (
+ <section key={group.docName} aria-label={group.docName} className="flex flex-col gap-2">
+ {/* The file names the group once instead of riding every card.
+ Basename, not the full path: the rail is narrow and a nested
+ path pushes the row past the panel edge; the full path stays
+ reachable as the tooltip. Not sticky — PanelBody's scroll-fade
+ mask fades whatever sits at its top edge, so a pinned header
+ would sit there half-faded. */}
+ <h3
+ className="flex items-center gap-1.5 text-[11px] text-muted-foreground"
+ title={group.docName}
+ >
+ <FileText className="size-3 shrink-0" />
+ <span className="truncate">{docBasename(group.docName)}</span>
+ <Badge variant="outline" className="shrink-0 px-1 py-0 text-[10px] tabular-nums">
+ {group.threads.length}
+ </Badge>
+ </h3>
+ {group.threads.map((thread) => (
+ <div key={thread.id} className="flex gap-2 rounded-md border p-2">
+ <Checkbox
+ checked={selectedIds.includes(thread.id)}
+ onCheckedChange={() => toggleQueueSelection(thread.id)}
+ aria-label={t`Include in dispatch`}
+ className="mt-0.5"
+ />
+ {/* The quote + body are the jump target: click to open that
+ document and scroll to the anchored passage. The checkbox
+ and ✕ stay separate controls so selecting or removing an
+ item never navigates away from the queue. */}
+ <Button
+ type="button"
+ variant="ghost"
+ aria-label={t`Go to this comment in ${docBasename(thread.docName)}`}
+ onClick={() => revealThread(thread)}
+ className="h-auto min-h-0 min-w-0 flex-1 flex-col items-start gap-1 px-0 py-0 text-left font-normal hover:bg-transparent"
+ >
+ <ThreadTargetLine thread={thread} className="text-xs" />
+ <span className="line-clamp-2 w-full text-sm whitespace-normal text-foreground">
+ {thread.body}
+ </span>
+ </Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ className="size-5 shrink-0 p-0 text-muted-foreground hover:text-foreground"
+ aria-label={t`Remove from queue`}
+ onClick={() => removeFromQueue(thread.id)}
+ >
+ <X className="size-3" />
+ </Button>
+ </div>
+ ))}
+ </section>
+ ))
+ )}
+ </PanelBody>
+ {/* Outside PanelBody so a long queue scrolls UNDER the actions rather than
+ pushing them off the bottom. */}
+ {items.length > 0 && (
+ <PanelFooter>
+ <Button size="sm" variant="ghost" className="min-w-0" onClick={clearQueue}>
+ <span className="truncate">
+ <Trans>Clear</Trans>
+ </span>
+ </Button>
+ {/* The shared split button, so the agent picker here is the same
+ standing preference (In app / Terminal / Configure agents) every
+ other send surface uses — with the queue's own destination rows
+ injected above it via `menuLeading`. */}
+ <AgentSplitButton
+ primary={
+ <>
+ {destinationIcon}
+ {/* The destination is IN the button, not just the menu: this
+ batch spans documents and cannot be un-sent, so "where is
+ this going" is exactly what you check before committing, and
+ a bare "Send" never said. */}
+ {/* The icon names the destination; the words say what the click
+ does. Spelling the agent out too made the button rename
+ itself on every tab switch, which reads as the control
+ changing rather than the target. */}
+ <span className="truncate">
+ {openSession !== null ? (
+ <Trans>Send to chat</Trans>
+ ) : (
+ <Trans>Start a new chat</Trans>
+ )}
+ </span>
+ </>
+ }
+ onPrimary={sendQueue}
+ primaryDisabled={selectedCount === 0}
+ // With no chat open the button already starts one, so an override
+ // row would just duplicate it — the menu is then the plain agent
+ // picker it has always been.
+ menuLeading={
+ openSession !== null ? (
+ <QueueNewChatRow
+ onStartNewChat={() => void dispatchComments({ compose: composeFreshTurn })}
+ />
+ ) : undefined
+ }
+ onOpenSettings={openAgentSettings}
+ menuEmptyState={
+ <p className="px-2 py-1.5 text-sm text-muted-foreground" aria-live="polite">
+ {picker.probePending ? (
+ <Trans>Checking for agents</Trans>
+ ) : (
+ <Trans>No agents enabled</Trans>
+ )}
+ </p>
+ }
+ triggerAriaLabel={t`Choose where to send the queue`}
+ testIds={{
+ primary: 'comment-queue-send',
+ trigger: 'comment-queue-send-trigger',
+ menu: 'comment-queue-send-menu',
+ option: (id) => `comment-queue-agent-option-${id}`,
+ threadAgent: (key) => `comment-queue-agent-option-thread-${key}`,
+ settings: 'comment-queue-agent-option-settings',
+ terminal: (cli) => `comment-queue-agent-option-terminal-${cli}`,
+ }}
+ {...picker.rows}
+ />
+ </PanelFooter>
+ )}
+ </Panel>
+ );
+}
diff --git a/packages/app/src/comments/CommentSelectionAffordance.tsx b/packages/app/src/comments/CommentSelectionAffordance.tsx
new file mode 100644
index 000000000..a15e9e821
--- /dev/null
+++ b/packages/app/src/comments/CommentSelectionAffordance.tsx
@@ -0,0 +1,289 @@
+/**
+ * Selection composer — where a comment is written.
+ *
+ * The "Comment" button in the selection toolbar (next to "Ask AI", see
+ * CommentBubbleButton) opens this composer on the current selection. Posting a
+ * comment adds it to the project-wide QUEUE — it does NOT dispatch to an
+ * agent immediately; the user batches comments and dispatches the queue in one
+ * action. Living in the toolbar (rather than a second floating pill) means it
+ * can't be occluded by the native formatting bar.
+ *
+ * The captured passage is marked in the DOCUMENT (see `setCommentDraftRange`)
+ * rather than echoed back inside this card. Focus moving here drops the browser
+ * selection, so without that mark a multi-line pick lost its end; with it, a
+ * quote preview would be saying twice what the page already shows.
+ *
+ * Positioning clones the BubbleMenuBar recipe (posToDOMRect virtual element +
+ * floating-ui autoUpdate/computePosition) anchored to the captured range so the
+ * card stays put while you type. Rendered above the native bar (z-60).
+ */
+
+import { autoUpdate, computePosition, flip, offset, shift } from '@floating-ui/dom';
+import { Trans, useLingui } from '@lingui/react/macro';
+import { posToDOMRect } from '@tiptap/core';
+import type { Editor } from '@tiptap/react';
+import { X } from 'lucide-react';
+import { useEffect, useRef, useState } from 'react';
+import { createPortal } from 'react-dom';
+import { Button } from '@/components/ui/button';
+import {
+ ComposerMentionInput,
+ type ComposerMentionInputHandle,
+} from '@/editor/ComposerMentionInput';
+import { getEditorView } from '@/editor/utils/get-editor-view';
+import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';
+import { setCommentDraftRange } from './anchor-decorations';
+import { captureSelectionContext } from './anchor-search';
+import { appendQueueToOpenSession } from './append-to-open-session';
+import { createThread, emitStartComment, subscribeStartComment } from './store';
+
+interface Captured {
+ from: number;
+ to: number;
+ quote: string;
+ /** Rendered text either side of the pick — says which occurrence, when the quote repeats. */
+ prefix: string;
+ suffix: string;
+}
+
+export function CommentSelectionAffordance({
+ editor,
+ docName,
+ shortcutEnabled,
+}: {
+ editor: Editor;
+ docName: string;
+ /** Only the foreground document answers the keyboard shortcut. */
+ shortcutEnabled: boolean;
+}) {
+ const { t } = useLingui();
+ const [captured, setCaptured] = useState<Captured | null>(null);
+ const [empty, setEmpty] = useState(true);
+ const inputRef = useRef<ComposerMentionInputHandle>(null);
+ const floatingRef = useRef<HTMLDivElement>(null);
+
+ // The keyboard route to the same intent the toolbar button emits. Lives here
+ // rather than on the button: the bubble menu only mounts while its own
+ // selection UI is showing, whereas this component is mounted for the editor's
+ // whole life, so the chord works the moment there is a selection.
+ useEffect(() => {
+ if (!shortcutEnabled) return;
+ const onKeyDown = (event: KeyboardEvent): void => {
+ if (!matchesKeyboardShortcut(event, 'add-comment')) return;
+ // A caret in a real form field (rename box, search) keeps its own keys.
+ const target = event.target;
+ if (target instanceof HTMLElement && /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName)) return;
+ if (editor.state.selection.empty) return;
+ event.preventDefault();
+ emitStartComment();
+ };
+ window.addEventListener('keydown', onKeyDown);
+ return () => window.removeEventListener('keydown', onKeyDown);
+ }, [shortcutEnabled, editor]);
+
+ // Open the composer when the toolbar "Comment" button fires — capturing the
+ // 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;
+ // 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
+ // "- 3 tbsp peanut butter" for a source line reading
+ // "- **Peanut sauce:** 3 tbsp peanut butter" — a quote that is in no
+ // document. The server matches rendered text against the markdown body
+ // with syntax treated as elastic, so the plain text is what it wants.
+ const quote = editor.state.doc.textBetween(from, to, '\n').trim();
+ if (quote.length === 0) return;
+ // Captured HERE, at the moment of the pick — this component is the only
+ // place that knows which occurrence of a repeated passage was selected.
+ const { prefix, suffix } = captureSelectionContext(editor.state.doc, from, to);
+ setCaptured({ from, to, quote, prefix, suffix });
+ // Focus moves into the composer, which drops the browser selection. Mark
+ // the passage instead, so it stays visibly picked while you type.
+ setCommentDraftRange(editor, { from, to });
+ });
+ }, [editor]);
+
+ // Keep the floating card pinned to the captured range across scroll/layout.
+ useEffect(() => {
+ if (captured === null) return;
+ const floating = floatingRef.current;
+ if (!floating) return;
+ const view = getEditorView(editor);
+ if (!view) return;
+ const virtualEl = {
+ getBoundingClientRect: () => {
+ try {
+ return posToDOMRect(view, captured.from, captured.to);
+ } catch {
+ return new DOMRect();
+ }
+ },
+ contextElement: view.dom,
+ };
+ return autoUpdate(virtualEl, floating, () => {
+ computePosition(virtualEl, floating, {
+ placement: 'bottom-start',
+ strategy: 'fixed',
+ middleware: [offset(8), flip(), shift({ padding: 8 })],
+ }).then(({ x, y }) => {
+ floating.style.position = 'fixed';
+ floating.style.left = `${x}px`;
+ floating.style.top = `${y}px`;
+ });
+ });
+ }, [captured, editor]);
+
+ // The mention field is an editor, not an input, so there is no `autoFocus` to
+ // set — focus is a method call once it has mounted for this capture.
+ useEffect(() => {
+ if (captured === null) return;
+ inputRef.current?.focus();
+ }, [captured]);
+
+ function reset() {
+ inputRef.current?.clear();
+ setEmpty(true);
+ setCaptured(null);
+ setCommentDraftRange(editor, null);
+ }
+
+ /**
+ * A click anywhere else discards the draft.
+ *
+ * Pointer-DOWN rather than click, so the composer is gone before the click
+ * lands — otherwise pressing a toolbar button would act on a selection the
+ * composer was still holding. Capture phase for the same reason: handlers that
+ * stop propagation (the bubble menu's own) must not be able to keep it open.
+ *
+ * Escape does the same thing from the keyboard; this is the pointer twin, and
+ * both route through `reset` so a dismissed draft always clears the document's
+ * draft mark with it.
+ */
+ useEffect(() => {
+ if (captured === null) return;
+ const onPointerDown = (event: PointerEvent): void => {
+ const card = floatingRef.current;
+ if (card === null) return;
+ const target = event.target;
+ if (!(target instanceof Node)) return;
+ if (card.contains(target)) return;
+ // The `@`-mention results are portaled to `document.body`, so they are
+ // outside the card by DOM but not by intent — picking a file must not read
+ // as clicking away.
+ if (target instanceof Element && target.closest('[data-suggestion-popup]') !== null) return;
+ reset();
+ };
+ document.addEventListener('pointerdown', onPointerDown, true);
+ return () => document.removeEventListener('pointerdown', onPointerDown, true);
+ });
+
+ /**
+ * File the comment. `dispatch` decides which of the two buttons ran it:
+ * queue it for a later batch, or hand it to an agent now.
+ *
+ * Both write the same thread — sending is not a different KIND of comment,
+ * just a comment that does not wait. That is why one function takes a flag
+ * rather than there being two creation paths to keep in step.
+ */
+ function post(dispatch: boolean) {
+ if (captured === null) return;
+ // `getContent` renders each mention chip inline as its `@path`, so the
+ // comment an agent reads names files the same way the Ask AI composer does.
+ const body = inputRef.current?.getContent().instruction.trim() ?? '';
+ if (body.length === 0) return;
+ // Posted straight into the queue by the store — no separate addToQueue.
+ createThread({
+ docName,
+ quote: captured.quote,
+ prefix: captured.prefix,
+ suffix: captured.suffix,
+ body,
+ // Reuse-or-launch is the same decision the queue's own send makes, and it
+ // is made by the sessions dock, not here: a live chat takes the comment,
+ // and with none open one starts. Deliberately NOT the `deliver` hook the
+ // queue batch uses — that is only installed while the Comments tab is
+ // mounted, so a send from the editor with the panel closed did nothing.
+ onCreated: dispatch
+ ? (threadId) => {
+ // `resolve` so it does not also land in the queue: this was a send,
+ // not a review item filed for later, and leaving it open would mean
+ // the reviewer's next batch carried the same note a second time.
+ void appendQueueToOpenSession({
+ threadIds: [threadId],
+ submit: true,
+ resolve: true,
+ });
+ }
+ : undefined,
+ });
+ // Collapse the picked range: the passage has been filed, so it is no longer
+ // "selected for whatever you do next". Left selected it re-pins itself in
+ // the composer the moment anything re-reads the editor selection.
+ if (!editor.isDestroyed) {
+ editor.commands.setTextSelection(Math.min(captured.to, editor.state.doc.content.size));
+ }
+ reset();
+ }
+
+ if (captured === null) return null;
+
+ return createPortal(
+ <div
+ ref={floatingRef}
+ className="z-[60] flex w-80 flex-col gap-2 rounded-lg border bg-popover p-3 shadow-lg"
+ style={{ position: 'fixed', top: 0, left: 0 }}
+ data-testid="comment-composer"
+ >
+ {/* Dismiss sits in the corner rather than the action row: the row is for
+ the two things that FILE the comment, and a third button beside them
+ made discarding look like a peer of sending.
+
+ Its own row rather than absolute positioning — overlaying the card
+ floated it on top of the textarea's rounded corner, and any offset that
+ clears the corner is a magic number that breaks the moment the field's
+ radius or padding changes. A row cannot overlap by construction; the
+ negative margins only pull it tight into the corner. */}
+ <div className="-mt-1 -mr-1 -mb-1 flex justify-end">
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ aria-label={t`Discard this comment`}
+ onClick={reset}
+ className="size-6 shrink-0 p-0 text-muted-foreground hover:text-foreground"
+ >
+ <X className="size-3.5" />
+ </Button>
+ </div>
+ {/* The Ask AI composer's field, not a plain textarea — so `@` mentions a
+ file here exactly as it does there, and the comment an agent receives
+ carries real paths rather than a name it has to go find.
+
+ Enter files the comment. Sending is a click: the field cannot tell this
+ host whether a modifier was held (Enter and ⌘Enter reach `onSubmit`
+ identically), so a keyboard shortcut for the irreversible action would
+ have to be guessed at. */}
+ <ComposerMentionInput
+ ref={inputRef}
+ ariaLabel={t`Add a comment`}
+ placeholder={t`Add a comment`}
+ onEmptyChange={setEmpty}
+ onSubmit={() => post(false)}
+ onEscape={reset}
+ className="max-h-40 min-h-16 overflow-y-auto rounded-md border px-2 py-1 text-sm"
+ />
+ <div className="flex items-center justify-end gap-1.5">
+ <Button size="sm" variant="outline" onClick={() => post(false)} disabled={empty}>
+ <Trans>Add Comment</Trans>
+ </Button>
+ <Button size="sm" onClick={() => post(true)} disabled={empty}>
+ <Trans>Send to AI</Trans>
+ </Button>
+ </div>
+ </div>,
+ document.body,
+ );
+}
diff --git a/packages/app/src/comments/CommentThreadPopover.tsx b/packages/app/src/comments/CommentThreadPopover.tsx
new file mode 100644
index 000000000..81bd51616
--- /dev/null
+++ b/packages/app/src/comments/CommentThreadPopover.tsx
@@ -0,0 +1,130 @@
+/**
+ * In-doc thread popover.
+ *
+ * Clicking a highlighted passage (or its margin dot) pops the thread up as a
+ * floating card anchored to the text — the Google-Docs / Notion gesture — rather
+ * than opening the side panel. Reuses the panel's `ThreadCard`, so edit, queue,
+ * and resolve behave identically in both places, and the BubbleMenuBar floating
+ * recipe for positioning.
+ *
+ * Only open threads are anchored in the doc, so the popover auto-closes when its
+ * thread resolves (its highlight disappears) or is removed.
+ */
+
+import { autoUpdate, computePosition, flip, offset, shift } from '@floating-ui/dom';
+import { posToDOMRect } from '@tiptap/core';
+import type { Editor } from '@tiptap/react';
+import { useEffect, useRef, useState } from 'react';
+import { createPortal } from 'react-dom';
+import { getEditorView } from '@/editor/utils/get-editor-view';
+import { findQuoteRange } from './anchor-search';
+import { ThreadCard } from './CommentsPanel';
+import { propertyRowRect } from './property-row-rect';
+import { emitOpenThreadPopover, subscribeOpenThreadPopover, useCommentThreads } from './store';
+
+export function CommentThreadPopover({ editor, docName }: { editor: Editor; docName: string }) {
+ const [threadId, setThreadId] = useState<string | null>(null);
+ const [now] = useState(() => Date.now());
+ const floatingRef = useRef<HTMLDivElement>(null);
+ const threads = useCommentThreads(docName);
+ const thread = threadId ? (threads.find((t) => t.id === threadId) ?? null) : null;
+
+ // Open on highlight/marker click.
+ useEffect(() => {
+ return subscribeOpenThreadPopover((id) => setThreadId(id));
+ }, []);
+
+ // Auto-close when the thread is gone or no longer anchored (resolved/orphaned).
+ // Announced rather than set locally: the margin rail mirrors this state and
+ // would otherwise keep the marker lit for a popover that closed itself.
+ useEffect(() => {
+ if (threadId !== null && (thread === null || thread.status !== 'open')) {
+ emitOpenThreadPopover(null);
+ }
+ }, [threadId, thread]);
+
+ // Pin the card to the anchored text.
+ useEffect(() => {
+ if (thread === null) return;
+ const floating = floatingRef.current;
+ if (!floating) return;
+ const view = getEditorView(editor);
+ if (!view) return;
+ // Two rect sources, one positioner. A passage measures through ProseMirror;
+ // a property measures its row in the properties table, which sits in the
+ // same scroll container. Resolved live inside `getBoundingClientRect` rather
+ // than captured once, so `autoUpdate` keeps following the target as the
+ // reader scrolls or the row reflows.
+ const propertyKey = thread.target.kind === 'property' ? thread.target.key : null;
+ const range =
+ propertyKey === null && thread.anchor !== null
+ ? findQuoteRange(editor.state.doc, thread.anchor.quote, thread.anchor)
+ : null;
+ if (propertyKey === null && range === null) return;
+ const virtualEl = {
+ getBoundingClientRect: () => {
+ if (propertyKey !== null) return propertyRowRect(propertyKey) ?? new DOMRect();
+ if (range === null) return new DOMRect();
+ try {
+ return posToDOMRect(view, range.from, range.to);
+ } catch {
+ return new DOMRect();
+ }
+ },
+ contextElement: view.dom,
+ };
+ return autoUpdate(virtualEl, floating, () => {
+ computePosition(virtualEl, floating, {
+ placement: 'bottom-start',
+ strategy: 'fixed',
+ middleware: [offset(8), flip(), shift({ padding: 8 })],
+ }).then(({ x, y }) => {
+ floating.style.position = 'fixed';
+ floating.style.left = `${x}px`;
+ floating.style.top = `${y}px`;
+ });
+ });
+ }, [thread, editor]);
+
+ // Dismiss on outside click / Escape. Clicks on a highlight or a rail marker
+ // are ignored here — both carry `data-comment-thread` and drive this popover
+ // through the bus, so letting mousedown close first would make a marker's
+ // toggle-to-close immediately reopen.
+ useEffect(() => {
+ if (thread === null) return;
+ const onDown = (event: MouseEvent) => {
+ const target = event.target as HTMLElement | null;
+ if (floatingRef.current?.contains(target)) return;
+ if (target?.closest('[data-comment-thread]')) return;
+ emitOpenThreadPopover(null);
+ };
+ const onKey = (event: KeyboardEvent) => {
+ if (event.key === 'Escape') emitOpenThreadPopover(null);
+ };
+ document.addEventListener('mousedown', onDown);
+ document.addEventListener('keydown', onKey);
+ return () => {
+ document.removeEventListener('mousedown', onDown);
+ document.removeEventListener('keydown', onKey);
+ };
+ }, [thread]);
+
+ if (thread === null) return null;
+
+ return createPortal(
+ <div
+ ref={floatingRef}
+ className="z-50 w-80 rounded-lg bg-popover shadow-lg"
+ style={{ position: 'fixed', top: 0, left: 0 }}
+ >
+ <ThreadCard
+ thread={thread}
+ now={now}
+ focused={false}
+ cardRef={() => {}}
+ onClose={() => emitOpenThreadPopover(null)}
+ />
+ </div>,
+ document.body,
+ );
+}
diff --git a/packages/app/src/comments/CommentedDocContext.tsx b/packages/app/src/comments/CommentedDocContext.tsx
new file mode 100644
index 000000000..d88a2ba06
--- /dev/null
+++ b/packages/app/src/comments/CommentedDocContext.tsx
@@ -0,0 +1,34 @@
+/**
+ * Which document the property panel is editing — for the comment affordances
+ * inside it.
+ *
+ * A sibling to `FrontmatterBindingContext`, which is deliberately scoped to the
+ * binding handle alone. Nested object and array rows are recursive widgets
+ * several layers below the panel, and every one of them can host a comment
+ * button; threading a `docName` prop through each would touch widgets that have
+ * nothing else to do with comments.
+ *
+ * `null` is the ordinary case for the other panels built from the same rows —
+ * templates, skills, folder cards. Only a real document has comment threads, so
+ * a button that finds no doc name renders nothing rather than posting somewhere
+ * that cannot receive it.
+ */
+
+import { createContext, type ReactNode, use } from 'react';
+
+const CommentedDocContext = createContext<string | null>(null);
+
+export function CommentedDocProvider({
+ docName,
+ children,
+}: {
+ docName: string | null;
+ children: ReactNode;
+}) {
+ return <CommentedDocContext value={docName}>{children}</CommentedDocContext>;
+}
+
+/** The document whose properties are being edited, or null when there isn't one. */
+export function useCommentedDocName(): string | null {
+ return use(CommentedDocContext);
+}
diff --git a/packages/app/src/comments/CommentsBoundary.tsx b/packages/app/src/comments/CommentsBoundary.tsx
new file mode 100644
index 000000000..e876d1e79
--- /dev/null
+++ b/packages/app/src/comments/CommentsBoundary.tsx
@@ -0,0 +1,15 @@
+/**
+ * Error boundary isolating the comment UI from the document.
+ *
+ * Comment surfaces render inside the editor's React tree, so without this a bug
+ * in any of them bubbles to the editor's `DocumentErrorBoundary` and BLANKS the
+ * whole document. Contained here, a comment-side failure costs the comment UI
+ * and nothing else — the document keeps rendering and stays editable.
+ */
+
+import type { ReactNode } from 'react';
+import { ErrorBoundary } from 'react-error-boundary';
+
+export function CommentsBoundary({ children }: { children: ReactNode }) {
+ return <ErrorBoundary fallbackRender={() => null}>{children}</ErrorBoundary>;
+}
diff --git a/packages/app/src/comments/CommentsPanel.tsx b/packages/app/src/comments/CommentsPanel.tsx
new file mode 100644
index 000000000..e5afd36ae
--- /dev/null
+++ b/packages/app/src/comments/CommentsPanel.tsx
@@ -0,0 +1,489 @@
+/**
+ * The comments panel: one card per thread on the open document.
+ *
+ * Thread lifecycle rendered from the store: anchored cards carrying one
+ * comment, editable in place, plus queue / resolve and the explicit
+ * orphaned-"re-place" state.
+ *
+ * A thread holds ONE comment rather than a discussion. Comments go to an agent,
+ * not to teammates, so there is nobody to reply to yet — revising what you asked
+ * for is the move that actually comes up. An edit therefore REPLACES the comment
+ * server-side; the superseded text is not kept.
+ */
+
+import { Trans, useLingui } from '@lingui/react/macro';
+import {
+ Check,
+ CircleDot,
+ MapPin,
+ Pencil,
+ RotateCcw,
+ Sparkles,
+ Trash2,
+ Unlink,
+ X,
+} from 'lucide-react';
+import { useEffect, useRef, useState } from 'react';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import {
+ Panel,
+ PanelBody,
+ PanelCount,
+ PanelEmpty,
+ PanelHeader,
+ PanelTitle,
+} from '@/components/ui/panel';
+import { Textarea } from '@/components/ui/textarea';
+import { getEditorForDoc } from '@/editor/active-editor';
+import { ProfilerBoundary } from '@/lib/perf';
+import { cn } from '@/lib/utils';
+import { captureSelectionContext, findQuoteRange } from './anchor-search';
+import { propertyAddress } from './comment-chips';
+import { revealPropertyValueRange } from './property-row-rect';
+import { scrollAnchorIntoView } from './scroll-to-anchor';
+import {
+ clearActiveThread,
+ deleteThread,
+ editComment,
+ refresh,
+ reopenThread,
+ replaceOrphan,
+ resolveThread,
+ setActiveThread,
+ subscribeFocusThread,
+ toggleQueue,
+ useCommentThreads,
+} from './store';
+import type { CommentThread } from './types';
+
+function relativeTime(at: number, now: number): string {
+ const secs = Math.max(1, Math.round((now - at) / 1000));
+ if (secs < 60) return `${secs}s`;
+ const mins = Math.round(secs / 60);
+ if (mins < 60) return `${mins}m`;
+ const hours = Math.round(mins / 60);
+ return `${hours}h`;
+}
+
+export function ThreadCard({
+ thread,
+ now,
+ cardRef,
+ focused,
+ onClose,
+}: {
+ thread: CommentThread;
+ now: number;
+ cardRef: (el: HTMLElement | null) => void;
+ focused: boolean;
+ /** When set, renders a close button in the header (used by the popover). */
+ onClose?: () => void;
+}) {
+ const { t } = useLingui();
+ // The edit field opens on demand from the icon in the action row, seeded with
+ // the current text — this revises the comment rather than adding to it.
+ const [draft, setDraft] = useState(thread.body);
+ const [editing, setEditing] = useState(false);
+ const editFieldRef = useRef<HTMLTextAreaElement>(null);
+ const isOrphaned = thread.status === 'orphaned';
+ const isResolved = thread.status === 'resolved';
+
+ // Focus the edit field with the caret AFTER the existing text. `autoFocus`
+ // alone lands it at offset 0, so you open an edit standing in front of your
+ // own sentence and have to travel to the end before typing.
+ useEffect(() => {
+ if (!editing) return;
+ const field = editFieldRef.current;
+ if (field === null) return;
+ field.focus();
+ const end = field.value.length;
+ field.setSelectionRange(end, end);
+ }, [editing]);
+
+ function jumpToQuote(quote: string) {
+ if (thread.anchor === null) return;
+ // A value comment lives in a `<textarea>`, which no editor command can
+ // reach — selecting the words in the field is the only highlight it has.
+ if (thread.target.kind === 'property') {
+ revealPropertyValueRange({
+ key: thread.target.key,
+ path: thread.target.path,
+ quote,
+ start: thread.anchor.start,
+ end: thread.anchor.end,
+ });
+ return;
+ }
+ const editor = getEditorForDoc(thread.docName);
+ if (!editor) return;
+ const range = findQuoteRange(editor.state.doc, quote, thread.anchor);
+ if (!range) return;
+ // Select without ProseMirror's own scroll, then place it ourselves — its
+ // minimal scroll lands the passage under the floating toolbar.
+ editor.chain().focus().setTextSelection(range).run();
+ scrollAnchorIntoView(editor, range);
+ }
+
+ function rePlaceOnSelection() {
+ const editor = getEditorForDoc(thread.docName);
+ if (!editor) return;
+ const { from, to, empty } = editor.state.selection;
+ if (empty) return;
+ const quote = editor.state.doc.textBetween(from, to, ' ').trim();
+ // Same context the create path sends: re-placing onto one of two identical
+ // passages has to land on the one selected, not the first in the file.
+ if (quote.length > 0) {
+ replaceOrphan(thread.id, quote, captureSelectionContext(editor.state.doc, from, to));
+ }
+ }
+
+ return (
+ <article
+ ref={cardRef}
+ // Reading a card deepens its passage in the document. With two comments
+ // on the same words that is the only thing saying which is which, so it
+ // follows the pointer and keyboard focus rather than waiting for a click.
+ onPointerEnter={() => setActiveThread(thread.id)}
+ onPointerLeave={() => clearActiveThread(thread.id)}
+ onFocusCapture={() => setActiveThread(thread.id)}
+ onBlurCapture={() => clearActiveThread(thread.id)}
+ className={cn(
+ 'flex flex-col gap-1.5 rounded-lg border p-2.5 transition-shadow',
+ isResolved && 'opacity-70',
+ isOrphaned && 'border-amber-500/40 bg-amber-500/5',
+ focused && 'ring-2 ring-primary',
+ )}
+ >
+ {/* Timestamp leads, the way the author chip used to — with the row pinned
+ right, dropping the author left a hole on the left of every card. */}
+ <div className="flex items-center justify-between gap-2">
+ <span className="shrink-0 text-[10px] text-muted-foreground">
+ {relativeTime(thread.createdAt, now)}
+ </span>
+ <div className="flex min-w-0 items-center gap-1.5">
+ {isResolved && (
+ <Badge
+ variant="outline"
+ className="gap-1 border-green-600/40 text-green-700 dark:text-green-500"
+ >
+ <Check className="size-2.5" />
+ <Trans>Resolved</Trans>
+ </Badge>
+ )}
+ {isOrphaned && (
+ <Badge
+ variant="outline"
+ className="gap-1 border-amber-500/50 text-amber-600 dark:text-amber-500"
+ >
+ <Unlink className="size-2.5" />
+ <Trans>Orphaned</Trans>
+ </Badge>
+ )}
+ {/* No confirm step: a comment is one line of your own text, it has
+ gone nowhere but the queue, and re-adding it costs a selection and
+ a sentence. An interstitial would cost more than the mistake. */}
+ <Button
+ size="sm"
+ variant="ghost"
+ className="size-6 p-0 text-muted-foreground hover:text-destructive"
+ aria-label={t`Delete this comment`}
+ title={t`Delete this comment`}
+ onClick={() => deleteThread(thread.id)}
+ >
+ <Trash2 className="size-3.5" />
+ </Button>
+ {onClose && (
+ <Button
+ size="sm"
+ variant="ghost"
+ className="-mr-1 size-6 p-0 text-muted-foreground hover:text-foreground"
+ aria-label={t`Close`}
+ onClick={onClose}
+ >
+ <X className="size-3.5" />
+ </Button>
+ )}
+ </div>
+ </div>
+
+ {/* Anchor quote */}
+ {isOrphaned ? (
+ <p className="rounded border-l-2 border-amber-500/60 bg-amber-500/10 px-2 py-1 text-xs text-amber-700 dark:text-amber-400">
+ <Trans>The anchored text is gone. You can re-place it on selected text.</Trans>
+ </p>
+ ) : (
+ <Button
+ type="button"
+ variant="ghost"
+ // Inert only when there are no words to reveal — a comment on a whole
+ // field. The row still renders, so the thread keeps saying what it is
+ // on rather than showing nothing.
+ disabled={thread.anchor === null}
+ onClick={() => jumpToQuote(thread.anchor?.quote ?? '')}
+ title={
+ thread.anchor === null
+ ? t`This comment is on the whole property`
+ : thread.target.kind === 'property'
+ ? t`Select this text in the property`
+ : t`Jump to the anchored text`
+ }
+ className="h-auto w-full justify-start truncate rounded border-l-2 border-muted-foreground/40 bg-muted/40 px-2 py-1 text-left text-xs font-normal text-muted-foreground hover:bg-muted/70 disabled:opacity-100"
+ >
+ <span className="truncate">
+ {thread.target.kind === 'property' ? (
+ <span className="font-mono">
+ {propertyAddress(thread.target.key, thread.target.path)}:
+ {thread.anchor === null ? '' : ` “${thread.anchor.quote}”`}
+ </span>
+ ) : (
+ <>“{thread.anchor?.quote ?? ''}”</>
+ )}
+ </span>
+ </Button>
+ )}
+
+ <p className="text-sm text-foreground/90">{thread.body}</p>
+
+ {/* Actions */}
+ {isOrphaned ? (
+ <Button size="sm" variant="outline" className="min-w-0" onClick={rePlaceOnSelection}>
+ <MapPin className="size-3.5 shrink-0" />
+ <span className="truncate">
+ <Trans>Re-place on selected text</Trans>
+ </span>
+ </Button>
+ ) : (
+ <>
+ {/* The field appears only once you ask for it — most cards are being
+ read, not revised, so an always-present box costs every card height
+ for an action taken on few of them. Enter saves, Shift+Enter is a
+ newline, Escape discards the revision. */}
+ {editing && (
+ <Textarea
+ ref={editFieldRef}
+ rows={1}
+ value={draft}
+ onChange={(e) => setDraft(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Escape') {
+ setDraft(thread.body);
+ setEditing(false);
+ return;
+ }
+ if (e.key !== 'Enter' || e.shiftKey) return;
+ // Mid-composition Enter belongs to the IME, not to saving.
+ if (e.nativeEvent.isComposing) return;
+ e.preventDefault();
+ const next = draft.trim();
+ if (next.length === 0 || next === thread.body) {
+ setEditing(false);
+ return;
+ }
+ editComment(thread.id, next);
+ setEditing(false);
+ }}
+ placeholder={t`Edit this comment`}
+ className="min-h-0 resize-none px-2 py-1 text-sm leading-5"
+ />
+ )}
+ {/* One row, never wrapped: wrapping made the queued and un-queued
+ states different heights (the longer label bumped Resolve onto a
+ second line). Labels are short and `truncate`-capable instead, so
+ the row holds its shape in both states. */}
+ <div className="flex min-w-0 flex-nowrap items-center justify-end gap-1.5">
+ {!isResolved && (
+ <Button
+ size="sm"
+ variant="ghost"
+ aria-label={t`Edit this comment`}
+ title={t`Edit this comment`}
+ aria-expanded={editing}
+ className={cn(
+ 'size-7 shrink-0 p-0',
+ editing ? 'text-foreground' : 'text-muted-foreground hover:text-foreground',
+ )}
+ onClick={() => {
+ setDraft(thread.body);
+ setEditing((open) => !open);
+ }}
+ >
+ <Pencil className="size-3.5" />
+ </Button>
+ )}
+ {/* Queue toggle — the round trip out of and back into the batch.
+ Removing a comment from the queue never destroys it, so this is
+ how it gets back in. One model: everything ships via the
+ composer's batch, not a second per-thread dispatch path. */}
+ {!isResolved &&
+ (thread.queued ? (
+ /* Queued reads as a settled state (✓ Queued) and turns into its
+ own undo on hover — the ✕ says what the click will do without
+ spending a second control on it. Same cross-fade the composer's
+ file chips use, `group-focus-within` included so it is not a
+ pointer-only affordance. The label does NOT change with the
+ icon: swapping to "Unqueue" moves the text under the cursor
+ mid-hover. */
+ <Button
+ size="sm"
+ variant="outline"
+ aria-label={t`Remove from the queue`}
+ className="group/queued min-w-0 border-primary/40 text-primary hover:bg-primary/10 hover:text-primary"
+ onClick={() => toggleQueue(thread.id)}
+ >
+ <span className="relative inline-flex size-3.5 shrink-0">
+ <Check
+ className="absolute inset-0 size-3.5 opacity-100 transition-opacity duration-150 ease-out group-hover/queued:opacity-0 group-focus-within/queued:opacity-0 motion-reduce:transition-none"
+ aria-hidden
+ />
+ <X
+ className="absolute inset-0 size-3.5 opacity-0 transition-opacity duration-150 ease-out group-hover/queued:opacity-100 group-focus-within/queued:opacity-100 motion-reduce:transition-none"
+ aria-hidden
+ />
+ </span>
+ <span className="truncate">
+ <Trans>Queued</Trans>
+ </span>
+ </Button>
+ ) : (
+ <Button
+ size="sm"
+ variant="ghost"
+ className="min-w-0 text-muted-foreground hover:text-foreground"
+ onClick={() => toggleQueue(thread.id)}
+ >
+ <Sparkles className="size-3.5 shrink-0" />
+ <span className="truncate">
+ <Trans>Queue</Trans>
+ </span>
+ </Button>
+ ))}
+ {isResolved ? (
+ // Reopening has to be one click: dispatching auto-resolves a
+ // thread on send, so this is the correction when the agent didn't
+ // actually settle it. A static "Done" label left no way back.
+ <Button
+ size="sm"
+ variant="outline"
+ className="min-w-0"
+ onClick={() => reopenThread(thread.id)}
+ >
+ <RotateCcw className="size-3.5 shrink-0" />
+ <span className="truncate">
+ <Trans>Reopen</Trans>
+ </span>
+ </Button>
+ ) : (
+ <Button
+ size="sm"
+ variant="outline"
+ className="min-w-0"
+ onClick={() => resolveThread(thread.id)}
+ >
+ <Check className="size-3.5 shrink-0" />
+ <span className="truncate">
+ <Trans>Resolve</Trans>
+ </span>
+ </Button>
+ )}
+ </div>
+ </>
+ )}
+ </article>
+ );
+}
+
+function CommentsPanelInner({ docName }: { docName: string }) {
+ const { t } = useLingui();
+ const threads = useCommentThreads(docName);
+ const [showResolved, setShowResolved] = useState(false);
+ const [focusedId, setFocusedId] = useState<string | null>(null);
+ const cardRefs = useRef(new Map<string, HTMLElement>());
+ // Captured once on mount — relative timestamps don't need to tick live, and
+ // calling Date.now() during render violates the React Compiler purity rule.
+ const [now] = useState(() => Date.now());
+
+ // Load this doc's threads when the panel opens — it can open before (or
+ // without) the editor's anchor layer having mounted.
+ useEffect(() => {
+ void refresh(docName).catch(() => undefined);
+ }, [docName]);
+
+ // Clicking an in-doc highlight scrolls the panel to its thread + rings it.
+ //
+ // The ring's timer is held so it can be cancelled. Left dangling it fired
+ // after unmount, and every focus event queued another — clicking through ten
+ // highlights left ten timers racing to clear a ring only one of them owns.
+ const ringTimer = useRef<number | null>(null);
+ useEffect(() => {
+ const stop = subscribeFocusThread((threadId) => {
+ setFocusedId(threadId);
+ cardRefs.current.get(threadId)?.scrollIntoView({ block: 'center', behavior: 'smooth' });
+ if (ringTimer.current !== null) window.clearTimeout(ringTimer.current);
+ ringTimer.current = window.setTimeout(() => {
+ ringTimer.current = null;
+ setFocusedId((cur) => (cur === threadId ? null : cur));
+ }, 1_600);
+ });
+ return () => {
+ stop();
+ if (ringTimer.current !== null) window.clearTimeout(ringTimer.current);
+ };
+ }, []);
+
+ const active = threads.filter((thread) => thread.status !== 'resolved');
+ const resolved = threads.filter((thread) => thread.status === 'resolved');
+ const visible = showResolved ? threads : active;
+
+ return (
+ <Panel>
+ <PanelHeader>
+ <PanelTitle>
+ <Trans>Comments</Trans>
+ </PanelTitle>
+ <div className="flex items-center gap-2">
+ {resolved.length > 0 && (
+ <Button
+ size="sm"
+ variant="ghost"
+ className="h-6 gap-1 px-1.5 text-xs"
+ onClick={() => setShowResolved((v) => !v)}
+ >
+ {showResolved ? <CircleDot className="size-3" /> : <Check className="size-3" />}
+ {showResolved ? t`Hide resolved` : t`Show resolved (${resolved.length})`}
+ </Button>
+ )}
+ <PanelCount>{active.length}</PanelCount>
+ </div>
+ </PanelHeader>
+ <PanelBody className="flex flex-col gap-3">
+ {visible.length === 0 ? (
+ <PanelEmpty>
+ <Trans>No comments yet. Select text in the document to add one.</Trans>
+ </PanelEmpty>
+ ) : (
+ visible.map((thread) => (
+ <ThreadCard
+ key={thread.id}
+ thread={thread}
+ now={now}
+ focused={focusedId === thread.id}
+ cardRef={(el) => {
+ if (el) cardRefs.current.set(thread.id, el);
+ else cardRefs.current.delete(thread.id);
+ }}
+ />
+ ))
+ )}
+ </PanelBody>
+ </Panel>
+ );
+}
+
+export function CommentsPanel({ docName }: { docName: string }) {
+ return (
+ <ProfilerBoundary name="comments-panel">
+ <CommentsPanelInner docName={docName} />
+ </ProfilerBoundary>
+ );
+}
diff --git a/packages/app/src/comments/CommentsTab.tsx b/packages/app/src/comments/CommentsTab.tsx
new file mode 100644
index 000000000..90566162a
--- /dev/null
+++ b/packages/app/src/comments/CommentsTab.tsx
@@ -0,0 +1,36 @@
+/**
+ * Comments tab shell — one tab with a "This doc / Queue" scope toggle, reusing
+ * the header Problems uses for per-doc vs. project scope (PanelScopeHeader).
+ * "This doc" shows the current document's threads; "Queue" shows the batch
+ * waiting to be sent, which spans every file.
+ */
+
+import { useLingui } from '@lingui/react/macro';
+import { useEffect, useState } from 'react';
+import { type PanelScope, PanelScopeHeader } from '@/components/PanelScopeHeader';
+import { CommentQueuePanel } from './CommentQueuePanel';
+import { CommentsPanel } from './CommentsPanel';
+import { consumePendingQueueScope, subscribeQueueScopeRequests } from './reveal-queue';
+
+export function CommentsTab({ docName }: { docName: string }) {
+ const { t } = useLingui();
+ const [scope, setScope] = useState<PanelScope>('doc');
+ // Posting a comment flips this tab to the queue — the scope lives here, so the
+ // reveal has to reach it through an event rather than a prop. The pending
+ // check covers the mount the reveal itself caused, which fires its event
+ // before this component exists to hear it.
+ useEffect(() => {
+ if (consumePendingQueueScope()) setScope('project');
+ return subscribeQueueScopeRequests(() => setScope('project'));
+ }, []);
+ return (
+ <div className="flex h-full min-h-0 flex-col pt-2">
+ {/* "Queue", not "Project": this side isn't every comment in the project,
+ it's the batch waiting to be sent. */}
+ <PanelScopeHeader scope={scope} onScopeChange={setScope} projectLabel={t`Queue`} />
+ <div className="min-h-0 flex-1">
+ {scope === 'doc' ? <CommentsPanel docName={docName} /> : <CommentQueuePanel />}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/app/src/comments/PropertyCommentButton.tsx b/packages/app/src/comments/PropertyCommentButton.tsx
new file mode 100644
index 000000000..75bf21adc
--- /dev/null
+++ b/packages/app/src/comments/PropertyCommentButton.tsx
@@ -0,0 +1,156 @@
+/**
+ * Comment on a frontmatter property.
+ *
+ * The passage flow captures a selection and floats a composer beside it. A
+ * property has no selection to capture — the row IS the target — so this is the
+ * same composer hung off the row's own control instead, in a popover that
+ * anchors itself.
+ *
+ * It lives in `comments/` rather than beside the row it renders in:
+ * `FrontmatterRow` is shared by documents, templates, skills, and folder cards,
+ * and only a document has comment threads. Passing this in as a slot keeps the
+ * row from importing a subsystem three of its four callers cannot use.
+ */
+
+import { Trans, useLingui } from '@lingui/react/macro';
+import { MessageSquarePlus } from 'lucide-react';
+import { useState } from 'react';
+import { Button } from '@/components/ui/button';
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
+import { Textarea } from '@/components/ui/textarea';
+import { useCommentedDocName } from './CommentedDocContext';
+import { propertyAddress } from './comment-chips';
+import { capturePropertyValueSelection } from './property-value-selection';
+import { createPropertyThread } from './store';
+
+export function PropertyCommentButton({
+ propertyKey,
+ propertyPath = [],
+}: {
+ /** The TOP-LEVEL frontmatter key. Steps below it go in `propertyPath`. */
+ propertyKey: string;
+ /** Steps into the value — `['name']` for a nested field, `[2]` for a list item. */
+ propertyPath?: readonly (string | number)[];
+}) {
+ const { t } = useLingui();
+ // From context rather than a prop: the nested object and array rows that host
+ // this button are recursive widgets several layers below the panel, and none
+ // of them otherwise know or care which document they belong to.
+ const docName = useCommentedDocName();
+ const [open, setOpen] = useState(false);
+ const [draft, setDraft] = useState('');
+ // What was highlighted in the value when the button was pressed. Held in state
+ // rather than re-read at post time: by then the popover's own textarea owns
+ // the selection, and the value's is long gone.
+ const [quote, setQuote] = useState<string | null>(null);
+
+ const address = propertyAddress(propertyKey, propertyPath);
+
+ function post() {
+ const body = draft.trim();
+ if (body.length === 0 || docName === null) return;
+ createPropertyThread({
+ docName,
+ propertyKey,
+ propertyPath: [...propertyPath],
+ quote: quote ?? undefined,
+ body,
+ });
+ setDraft('');
+ setOpen(false);
+ }
+
+ // Templates, skills, and folder cards render the same rows with no document
+ // behind them. No thread can exist there, so offer no way to start one.
+ if (docName === null) return null;
+
+ return (
+ <Popover
+ open={open}
+ onOpenChange={(next) => {
+ setOpen(next);
+ // Closing discards the draft. A comment half-written against a row you
+ // have navigated away from is worse than gone: it would reappear on
+ // whatever row the button next rendered for.
+ if (!next) {
+ setDraft('');
+ setQuote(null);
+ }
+ }}
+ >
+ <PopoverTrigger asChild>
+ <Button
+ type="button"
+ data-testid="property-comment-button"
+ data-key={address}
+ aria-label={t`Comment on ${address}`}
+ // Pointer-down, not click: the click blurs the value field, and after
+ // that nothing distinguishes "the user highlighted this" from "focus
+ // moved on".
+ onPointerDown={(event) => setQuote(capturePropertyValueSelection(event.currentTarget))}
+ variant="ghost"
+ size="icon-sm"
+ // Same reveal-on-hover treatment as the row's remove control, so the
+ // two read as one set rather than one permanent and one appearing.
+ className="flex shrink-0 items-center justify-center rounded text-muted-foreground/0 hover:bg-muted hover:text-foreground focus-visible:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring group-hover:text-muted-foreground"
+ >
+ <MessageSquarePlus className="size-3.5" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="end" className="flex w-80 flex-col gap-2 p-3">
+ {/* Say WHICH of the two this is before the reviewer types. The same
+ button does both, so the header is the only thing that distinguishes
+ a note about the whole field from one about the sentence they
+ highlighted. */}
+ {quote === null ? (
+ <p className="truncate text-[11px] text-muted-foreground">
+ <Trans>
+ On <span className="font-mono">{address}</span>
+ </Trans>
+ </p>
+ ) : (
+ <div className="flex flex-col gap-1">
+ <p className="truncate text-[11px] text-muted-foreground">
+ <Trans>
+ On selected text in <span className="font-mono">{address}</span>
+ </Trans>
+ </p>
+ <p
+ className="line-clamp-2 rounded border-l-2 border-muted-foreground/40 bg-muted/40 px-2 py-1 font-mono text-[11px] text-muted-foreground"
+ data-testid="property-comment-quote"
+ >
+ {quote}
+ </p>
+ </div>
+ )}
+ <Textarea
+ autoFocus
+ value={draft}
+ onChange={(e) => setDraft(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Escape') {
+ setOpen(false);
+ return;
+ }
+ if (e.key !== 'Enter' || e.shiftKey) return;
+ // Mid-composition Enter is the IME confirming a candidate, not the
+ // reviewer submitting — the same guard the passage composer uses.
+ if (e.nativeEvent.isComposing) return;
+ e.preventDefault();
+ post();
+ }}
+ placeholder={t`Add a comment`}
+ className="min-h-16 resize-none text-sm"
+ />
+ <div className="flex items-center justify-end gap-1.5">
+ <Button size="sm" variant="ghost" onClick={() => setOpen(false)}>
+ <Trans>Cancel</Trans>
+ </Button>
+ <Button size="sm" onClick={post} disabled={draft.trim().length === 0}>
+ <Trans>Add to queue</Trans>
+ </Button>
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/packages/app/src/comments/QueueNewChatRow.dom.test.tsx b/packages/app/src/comments/QueueNewChatRow.dom.test.tsx
new file mode 100644
index 000000000..f1d4d9143
--- /dev/null
+++ b/packages/app/src/comments/QueueNewChatRow.dom.test.tsx
@@ -0,0 +1,64 @@
+/**
+ * The queue send's one override row.
+ *
+ * The send is automatic — a live chat takes the batch, none open starts one —
+ * so this row exists solely for the case the automatic answer gets wrong: a
+ * chat is open, but this batch belongs in a clean one. Without it, having any
+ * chat open would make a fresh turn unreachable.
+ */
+
+import * as actualLinguiMacro from '@lingui/react/macro';
+import { cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { QueueNewChatRow } from './QueueNewChatRow';
+
+vi.doMock('@lingui/react/macro', () => ({
+ ...actualLinguiMacro,
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useLingui: () => ({
+ t: (strings: TemplateStringsArray, ...values: unknown[]) =>
+ strings.reduce((acc, part, index) => `${acc}${part}${values[index] ?? ''}`, ''),
+ }),
+}));
+
+afterEach(() => cleanup());
+
+/** Mounted in an open menu — it is a menu item and needs the menu's context. */
+function renderRow(onStartNewChat = () => {}) {
+ return render(
+ <DropdownMenu defaultOpen>
+ <DropdownMenuTrigger>menu</DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <QueueNewChatRow onStartNewChat={onStartNewChat} />
+ </DropdownMenuContent>
+ </DropdownMenu>,
+ );
+}
+
+describe('the new-chat override row', () => {
+ test('names the act, matching the verb the dock uses', async () => {
+ // "Start" is what the dock's own primary says ("Start an agent") and what
+ // the send button says with no chat open — one verb for one act.
+ renderRow();
+ const row = await screen.findByTestId('comment-queue-send-new');
+ expect(row.textContent).toContain('Start a new chat');
+ });
+
+ test('starts a fresh turn', async () => {
+ const user = userEvent.setup();
+ let started = 0;
+ renderRow(() => {
+ started += 1;
+ });
+
+ await user.click(await screen.findByTestId('comment-queue-send-new'));
+ expect(started).toBe(1);
+ });
+});
diff --git a/packages/app/src/comments/QueueNewChatRow.tsx b/packages/app/src/comments/QueueNewChatRow.tsx
new file mode 100644
index 000000000..97cc61fe1
--- /dev/null
+++ b/packages/app/src/comments/QueueNewChatRow.tsx
@@ -0,0 +1,35 @@
+/**
+ * "Start a new chat" — the queue send's one override row.
+ *
+ * The send decides its own destination: a live chat takes the batch, and with
+ * none open it starts one. That is the answer in almost every case, so it is
+ * the button's behavior rather than a choice to make each time.
+ *
+ * This row exists for the case the automatic answer gets wrong: a chat is open,
+ * but this batch is unrelated to it and belongs in a clean one. Without it,
+ * having any chat open would make a fresh turn unreachable — a capability lost
+ * to a default. It renders ONLY when a chat is open; with none, "start a new
+ * chat" is what the button already does and the row would be a duplicate.
+ */
+
+import { Trans, useLingui } from '@lingui/react/macro';
+import { Plus } from 'lucide-react';
+import { DropdownMenuGroup, DropdownMenuItem } from '@/components/ui/dropdown-menu';
+
+export function QueueNewChatRow({ onStartNewChat }: { onStartNewChat: () => void }) {
+ const { t } = useLingui();
+ return (
+ <DropdownMenuGroup aria-label={t`Send queue to`}>
+ <DropdownMenuItem
+ onSelect={onStartNewChat}
+ className="gap-2"
+ data-testid="comment-queue-send-new"
+ >
+ <Plus className="size-4" />
+ <span className="flex-1 truncate">
+ <Trans>Start a new chat</Trans>
+ </span>
+ </DropdownMenuItem>
+ </DropdownMenuGroup>
+ );
+}
diff --git a/packages/app/src/comments/active-thread.test.ts b/packages/app/src/comments/active-thread.test.ts
new file mode 100644
index 000000000..dc080d03f
--- /dev/null
+++ b/packages/app/src/comments/active-thread.test.ts
@@ -0,0 +1,56 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ clearActiveThread,
+ emitOpenThreadPopover,
+ getActiveThread,
+ setActiveThread,
+ subscribeActiveThread,
+} from './store';
+
+beforeEach(() => {
+ setActiveThread(null);
+ emitOpenThreadPopover(null);
+});
+
+describe('active thread', () => {
+ it('starts on nothing', () => {
+ expect(getActiveThread()).toBeNull();
+ });
+
+ it('follows the pointer', () => {
+ setActiveThread('a');
+ expect(getActiveThread()).toBe('a');
+ clearActiveThread('a');
+ expect(getActiveThread()).toBeNull();
+ });
+
+ it('ignores a stale leave from the card the pointer already left', () => {
+ setActiveThread('a');
+ setActiveThread('b');
+ // 'a' loses the pointer only after 'b' has taken it.
+ clearActiveThread('a');
+ expect(getActiveThread()).toBe('b');
+ });
+
+ it('keeps the open popover active underneath the pointer', () => {
+ emitOpenThreadPopover('p');
+ expect(getActiveThread()).toBe('p');
+ setActiveThread('a');
+ expect(getActiveThread()).toBe('a');
+ clearActiveThread('a');
+ expect(getActiveThread()).toBe('p');
+ emitOpenThreadPopover(null);
+ expect(getActiveThread()).toBeNull();
+ });
+
+ it('notifies subscribers only when the answer changes', () => {
+ const listener = vi.fn();
+ const unsubscribe = subscribeActiveThread(listener);
+ setActiveThread('a');
+ setActiveThread('a');
+ expect(listener).toHaveBeenCalledTimes(1);
+ unsubscribe();
+ setActiveThread('b');
+ expect(listener).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/app/src/comments/anchor-decorations.tsx b/packages/app/src/comments/anchor-decorations.tsx
new file mode 100644
index 000000000..6d74a0ac5
--- /dev/null
+++ b/packages/app/src/comments/anchor-decorations.tsx
@@ -0,0 +1,242 @@
+/**
+ * Anchor-highlight layer — the marks on the passages that carry comments.
+ *
+ * Content-addressed: each thread re-finds its passage by matching its stored
+ * quote against the live doc text on every redraw, never by a saved position. A
+ * quote that no longer matches produces no decoration, which is how an orphaned
+ * thread renders un-highlighted while still living in the panel.
+ *
+ * Pure-ProseMirror plugin plus a thin React host that registers it, mirroring
+ * the deferred `editor.registerPlugin` pattern in TiptapEditor's agent-flash
+ * effect.
+ */
+
+import type { Node as PMNode } from '@tiptap/pm/model';
+import { Plugin, PluginKey } from '@tiptap/pm/state';
+import { Decoration, DecorationSet } from '@tiptap/pm/view';
+import type { Editor } from '@tiptap/react';
+import { useEffect } from 'react';
+import { buildAnchorSegments, type PlacedAnchor } from './anchor-layers';
+import { buildTextIndex, findRangeInIndex } from './anchor-search';
+import {
+ emitOpenThreadPopover,
+ getActiveThread,
+ getThreads,
+ refresh,
+ subscribe,
+ subscribeActiveThread,
+} from './store';
+
+const commentAnchorKey = new PluginKey('okCommentAnchors');
+
+// Only open threads are anchored in the doc — resolved threads drop their
+// highlight + marker (they stay in the panel under "Show resolved"), so a
+// clean document isn't littered with highlights on settled discussions.
+
+/**
+ * The passage a comment is being written ABOUT, held while the composer is open.
+ *
+ * Opening the composer moves focus into it, which drops the browser's selection
+ * — so the words you picked stopped being visible at exactly the moment you were
+ * describing them, and a multi-line pick gave no clue where it ended. This keeps
+ * the same highlight a landed comment gets, so the passage reads as already
+ * marked while you type.
+ */
+interface DraftRange {
+ from: number;
+ to: number;
+}
+
+/**
+ * Highlight (or clear) the passage the comment composer is open on. Pass null on
+ * cancel or post — the landed comment's own decoration takes over from there.
+ */
+export function setCommentDraftRange(editor: Editor, range: DraftRange | null): void {
+ if (editor.isDestroyed) return;
+ editor.view.dispatch(editor.state.tr.setMeta(commentAnchorKey, { draft: range }));
+}
+
+function openThread(threadId: string): void {
+ emitOpenThreadPopover(threadId);
+}
+
+/**
+ * Resolve every open thread (plus the pending draft) to a live range. The draft
+ * joins the same list rather than being layered on top, so commenting on text
+ * that already carries a comment is styled as the overlap it is.
+ */
+function placeAnchors(docName: string, doc: PMNode, draft: DraftRange | null): PlacedAnchor[] {
+ const placed: PlacedAnchor[] = [];
+ // Property threads are excluded, not merely skipped downstream: they point at
+ // a frontmatter key, which has no range in the body this decorates. Letting one
+ // through would send its key name into the text search, where a key like
+ // `title` matches ordinary prose and highlights a passage nobody commented on.
+ const threads = getThreads(docName).filter(
+ (t) => t.status === 'open' && t.target.kind === 'body' && t.anchor !== null,
+ );
+ if (threads.length > 0) {
+ const index = buildTextIndex(doc);
+ for (const thread of threads) {
+ if (thread.anchor === null) continue;
+ const range = findRangeInIndex(index, thread.anchor.quote, thread.anchor);
+ if (range === null) continue;
+ placed.push({ id: thread.id, from: range.from, to: range.to });
+ }
+ }
+ if (draft !== null && draft.from < draft.to) {
+ placed.push({ id: null, from: draft.from, to: draft.to });
+ }
+ return placed;
+}
+
+function buildDecorations(docName: string, doc: PMNode, draft: DraftRange | null): DecorationSet {
+ const placed = placeAnchors(docName, doc, draft);
+ if (placed.length === 0) return DecorationSet.empty;
+ const decos: Decoration[] = buildAnchorSegments(placed, getActiveThread()).map((segment) =>
+ Decoration.inline(
+ segment.from,
+ segment.to,
+ segment.threadId === null
+ ? { style: segment.style }
+ : { style: segment.style, 'data-comment-thread': segment.threadId },
+ ),
+ );
+ return DecorationSet.create(doc, decos);
+}
+
+/**
+ * The decorations are held in plugin state rather than rebuilt from the
+ * `decorations` prop, so a transaction that cannot have moved a highlight can
+ * hand back the previous set untouched.
+ *
+ * That is most of them. Every arrow key, click, and focus change dispatches a
+ * transaction, and resolving every thread against a freshly built character
+ * index on each one is real work — on a large document with a thread whose
+ * quote no longer matches, re-resolving runs three full-document scans per
+ * thread, per transaction.
+ */
+interface AnchorPluginState {
+ draft: DraftRange | null;
+ decorations: DecorationSet;
+}
+
+/**
+ * What a transaction obliges the anchor layer to do.
+ *
+ * - `draft` — the composer set or cleared its pending highlight.
+ * - `rebuild` — the document changed, or the store pinged us. Thread state lives
+ * outside editor state, so an edit, a resolve, or a change of active thread
+ * reaches this plugin only as a meta transaction and cannot be inferred.
+ * - `reuse` — nothing that can move a highlight. Selection moves, clicks, and
+ * focus changes all land here, and they are the majority of transactions.
+ */
+export function anchorTransactionEffect(
+ tr: { docChanged: boolean },
+ meta: unknown,
+): 'draft' | 'rebuild' | 'reuse' {
+ if (typeof meta === 'object' && meta !== null && 'draft' in meta) return 'draft';
+ if (tr.docChanged) return 'rebuild';
+ return meta === undefined ? 'reuse' : 'rebuild';
+}
+
+function createCommentAnchorPlugin(docName: string): Plugin<AnchorPluginState> {
+ return new Plugin<AnchorPluginState>({
+ key: commentAnchorKey,
+ state: {
+ init: (_config, state) => ({
+ draft: null,
+ decorations: buildDecorations(docName, state.doc, null),
+ }),
+ apply(tr, previous, _oldState, newState) {
+ const meta = tr.getMeta(commentAnchorKey);
+ switch (anchorTransactionEffect(tr, meta)) {
+ case 'reuse':
+ return previous;
+ case 'draft': {
+ const draft = (meta as { draft: DraftRange | null }).draft;
+ return { draft, decorations: buildDecorations(docName, newState.doc, draft) };
+ }
+ default: {
+ // Follow edits made while the composer is open rather than
+ // highlighting whatever text has since slid into those positions.
+ // A no-doc-change rebuild maps through an identity mapping.
+ const draft =
+ previous.draft === null
+ ? null
+ : {
+ from: tr.mapping.map(previous.draft.from),
+ to: tr.mapping.map(previous.draft.to),
+ };
+ return { draft, decorations: buildDecorations(docName, newState.doc, draft) };
+ }
+ }
+ },
+ },
+ props: {
+ decorations(state) {
+ return commentAnchorKey.getState(state)?.decorations;
+ },
+ handleClick(view, pos) {
+ // Narrowest wins: clicking where two comments overlap opens the more
+ // specific one rather than whichever thread the store happened to list
+ // first.
+ let hit: PlacedAnchor | null = null;
+ for (const anchor of placeAnchors(docName, view.state.doc, null)) {
+ if (anchor.id === null) continue;
+ if (pos < anchor.from || pos > anchor.to) continue;
+ if (hit === null || anchor.to - anchor.from < hit.to - hit.from) hit = anchor;
+ }
+ if (hit?.id == null) return false;
+ openThread(hit.id);
+ return true;
+ },
+ },
+ });
+}
+
+/**
+ * Registers the anchor plugin on the editor and re-triggers a redraw whenever
+ * the comment store mutates (new thread, resolve, orphan re-place). Nothing
+ * renders — it's a behavior-only host, like the agent-flash effect.
+ */
+export function CommentAnchorLayer({ editor, docName }: { editor: Editor; docName: string }) {
+ useEffect(() => {
+ let disposed = false;
+ // Defer out of React's commit phase — registerPlugin reconfigures editor
+ // state and can flushSync inside a lifecycle otherwise (same reason the
+ // agent-flash effect uses queueMicrotask).
+ queueMicrotask(() => {
+ if (disposed || editor.isDestroyed) return;
+ editor.registerPlugin(createCommentAnchorPlugin(docName));
+ // Threads load from the server on first read; redraw once they land.
+ void refresh(docName)
+ .then(() => {
+ if (disposed || editor.isDestroyed) return;
+ editor.view.dispatch(editor.state.tr.setMeta(commentAnchorKey, { refresh: true }));
+ })
+ .catch(() => undefined);
+ });
+
+ // Force a decoration recompute on any store change (thread state is not
+ // part of editor state, so a no-op meta transaction is how we redraw).
+ // Which thread is active rides its own signal: pointing at a comment
+ // restyles the document without disturbing anything reading the list.
+ const redraw = () => {
+ if (disposed || editor.isDestroyed) return;
+ const view = (editor as unknown as { editorView?: typeof editor.view }).editorView;
+ if (!view) return;
+ view.dispatch(view.state.tr.setMeta(commentAnchorKey, { refresh: true }));
+ };
+ const unsubscribe = subscribe(redraw);
+ const unsubscribeActive = subscribeActiveThread(redraw);
+
+ return () => {
+ disposed = true;
+ unsubscribe();
+ unsubscribeActive();
+ if (!editor.isDestroyed) editor.unregisterPlugin(commentAnchorKey);
+ };
+ }, [editor, docName]);
+
+ return null;
+}
diff --git a/packages/app/src/comments/anchor-layers.test.ts b/packages/app/src/comments/anchor-layers.test.ts
new file mode 100644
index 000000000..c80a1976c
--- /dev/null
+++ b/packages/app/src/comments/anchor-layers.test.ts
@@ -0,0 +1,102 @@
+import { describe, expect, it } from 'vitest';
+import { buildAnchorSegments, type PlacedAnchor } from './anchor-layers';
+
+const at = (id: string | null, from: number, to: number): PlacedAnchor => ({ id, from, to });
+
+const RESTING =
+ 'border-radius:2px;padding-bottom:1px;cursor:pointer;background-color:rgba(245,158,11,0.22);box-shadow:inset 0 -2px 0 rgba(245,158,11,0.7);';
+const ACTIVE =
+ 'border-radius:2px;padding-bottom:1px;cursor:pointer;background-color:rgba(245,158,11,0.45);box-shadow:inset 0 -2px 0 rgba(245,158,11,1);';
+
+describe('buildAnchorSegments', () => {
+ it('leaves a lone unattended highlight on its original style', () => {
+ expect(buildAnchorSegments([at('t1', 4, 12)])).toEqual([
+ { from: 4, to: 12, threadId: 't1', style: RESTING },
+ ]);
+ });
+
+ it('deepens the active thread and leaves the rest resting', () => {
+ const segments = buildAnchorSegments([at('t1', 0, 5), at('t2', 9, 14)], 't2');
+ expect(segments[0].style).toBe(RESTING);
+ expect(segments[1].style).toBe(ACTIVE);
+ });
+
+ it('splits overlapping highlights into three segments', () => {
+ const segments = buildAnchorSegments([at('t1', 0, 10), at('t2', 6, 16)]);
+ expect(segments.map((s) => [s.from, s.to])).toEqual([
+ [0, 6],
+ [6, 10],
+ [10, 16],
+ ]);
+ });
+
+ it('gives the shared span to the active thread, not to whoever came last', () => {
+ const placed = [at('t1', 0, 10), at('t2', 6, 16)];
+ // The shared span [6,10) follows whichever thread is being read.
+ expect(buildAnchorSegments(placed, 't1').map((s) => s.style)).toEqual([
+ ACTIVE,
+ ACTIVE,
+ RESTING,
+ ]);
+ expect(buildAnchorSegments(placed, 't2').map((s) => s.style)).toEqual([
+ RESTING,
+ ACTIVE,
+ ACTIVE,
+ ]);
+ });
+
+ it('reads as one unbroken wash when nothing is active', () => {
+ const styles = buildAnchorSegments([at('t1', 0, 10), at('t2', 6, 16)]).map((s) => s.style);
+ expect(new Set(styles).size).toBe(1);
+ });
+
+ it('separates the active thread nested inside a wider one', () => {
+ const segments = buildAnchorSegments([at('wide', 0, 30), at('narrow', 10, 20)], 'narrow');
+ expect(segments.map((s) => s.style)).toEqual([RESTING, ACTIVE, RESTING]);
+ });
+
+ it('opens the narrower comment where two overlap', () => {
+ const [, shared] = buildAnchorSegments([at('wide', 0, 20), at('narrow', 6, 10)]);
+ expect(shared.threadId).toBe('narrow');
+ });
+
+ it('treats the composer draft as active and drops the pointer cursor', () => {
+ const [segment] = buildAnchorSegments([at(null, 0, 8)]);
+ expect(segment.threadId).toBeNull();
+ expect(segment.style).not.toContain('cursor:pointer');
+ expect(segment.style).toContain('rgba(245,158,11,0.45)');
+ });
+
+ it('stands the draft out from the comment it overlaps', () => {
+ const segments = buildAnchorSegments([at('t1', 0, 10), at(null, 6, 16)]);
+ expect(segments[0].style).toBe(RESTING);
+ expect(segments[1].style).toContain('rgba(245,158,11,0.45)');
+ expect(segments[2].threadId).toBeNull();
+ });
+
+ it('drops empty and orphaned ranges', () => {
+ expect(buildAnchorSegments([])).toEqual([]);
+ expect(buildAnchorSegments([at('t1', 5, 5)])).toEqual([]);
+ });
+
+ it('ignores an active id that is not on this document', () => {
+ const segments = buildAnchorSegments([at('t1', 0, 10)], 'elsewhere');
+ expect(segments[0].style).toBe(RESTING);
+ });
+
+ it('does not split a range the active thread covers end to end', () => {
+ const segments = buildAnchorSegments([at('t1', 0, 30), at('t2', 10, 20)], 't1');
+ expect(segments.map((s) => [s.from, s.to])).toEqual([
+ [0, 10],
+ [10, 20],
+ [20, 30],
+ ]);
+ expect(new Set(segments.map((s) => s.style)).size).toBe(1);
+ });
+
+ it('is stable regardless of the order the store lists threads in', () => {
+ const forward = buildAnchorSegments([at('t1', 0, 10), at('t2', 6, 16)], 't1');
+ const reversed = buildAnchorSegments([at('t2', 6, 16), at('t1', 0, 10)], 't1');
+ expect(reversed).toEqual(forward);
+ });
+});
diff --git a/packages/app/src/comments/anchor-layers.ts b/packages/app/src/comments/anchor-layers.ts
new file mode 100644
index 000000000..5e21a70f9
--- /dev/null
+++ b/packages/app/src/comments/anchor-layers.ts
@@ -0,0 +1,138 @@
+/**
+ * Overlap-aware styling for the anchor-highlight layer.
+ *
+ * ProseMirror concatenates the `style` attribute of overlapping inline
+ * decorations onto the one span it splits out, so two comments on the same
+ * words collapse to whichever decoration is emitted last — the second comment
+ * silently vanishes from the document while still sitting in the panel. This
+ * cuts the ranges into non-overlapping segments up front and emits a single
+ * style per segment, so a passage two comments share can be styled for one of
+ * them without the other's decoration overwriting it.
+ *
+ * Which one it's styled for is the active thread: the pale wash means "a
+ * comment covers this", and deepening it on the thread you're reading is what
+ * separates the two. One hue throughout — intensity, not color, carries the
+ * distinction, so a document with many comments reads as one mark type.
+ */
+
+export interface PlacedAnchor {
+ /** Thread this range belongs to; null for the composer's pending draft. */
+ id: string | null;
+ from: number;
+ to: number;
+}
+
+export interface AnchorSegment {
+ from: number;
+ to: number;
+ style: string;
+ /** Narrowest thread covering the segment — what a click on it opens. */
+ threadId: string | null;
+}
+
+/**
+ * Amber, as `r,g,b` for interpolation into `rgba()`.
+ *
+ * Exported because a property value's highlight cannot be a decoration — it is
+ * painted as the field's own `::selection`, in `property-row-rect.ts`. Two
+ * highlights meaning the same thing in two different colours would read as two
+ * different states, so the colour has exactly one definition.
+ */
+export const COMMENT_HUE = '245,158,11';
+const HUE = COMMENT_HUE;
+
+/** Held at its pre-overlap value, so an unattended highlight is unchanged. */
+const RESTING = { fill: 0.22, line: 0.7 };
+
+/** Deep enough to read as a distinct band where it abuts a resting highlight. */
+const ACTIVE = { fill: 0.45, line: 1 };
+
+/** The active fill, for the `::selection` twin that cannot read this object. */
+export const COMMENT_ACTIVE_FILL = 0.45;
+
+function style(anchor: PlacedAnchor, active: boolean): string {
+ const hue = HUE;
+ const { fill, line } = active ? ACTIVE : RESTING;
+ return [
+ 'border-radius:2px',
+ 'padding-bottom:1px',
+ ...(anchor.id === null ? [] : ['cursor:pointer']),
+ `background-color:rgba(${hue},${fill})`,
+ `box-shadow:inset 0 -2px 0 rgba(${hue},${line})`,
+ '',
+ ].join(';');
+}
+
+function coverKey(covering: PlacedAnchor[]): string {
+ return covering.map((a) => a.id ?? '·').join('|');
+}
+
+function narrowestThread(covering: PlacedAnchor[]): string | null {
+ let best: PlacedAnchor | null = null;
+ for (const anchor of covering) {
+ if (anchor.id === null) continue;
+ if (best === null || anchor.to - anchor.from < best.to - best.from) best = anchor;
+ }
+ return best?.id ?? null;
+}
+
+/**
+ * The passage being composed on counts as active: while the composer is open
+ * it's the thing under discussion, so it stands out from comments already made.
+ */
+function isActive(anchor: PlacedAnchor, activeId: string | null): boolean {
+ return anchor.id === null || anchor.id === activeId;
+}
+
+/**
+ * Split the placed ranges at every start/end boundary, keeping only the spans
+ * some comment actually covers and merging back the neighbours that ended up
+ * with an identical cover set.
+ */
+export function buildAnchorSegments(
+ placed: PlacedAnchor[],
+ activeId: string | null = null,
+): AnchorSegment[] {
+ const anchors = [...placed]
+ .filter((a) => a.from < a.to)
+ .sort((a, b) => a.from - b.from || a.to - b.to || (a.id ?? '').localeCompare(b.id ?? ''));
+ if (anchors.length === 0) return [];
+
+ const edges = [...new Set(anchors.flatMap((a) => [a.from, a.to]))].sort((x, y) => x - y);
+ const segments: AnchorSegment[] = [];
+ let open: { from: number; to: number; covering: PlacedAnchor[] } | null = null;
+
+ const close = () => {
+ if (open === null) return;
+ // The active thread paints the span it shares with others; without an
+ // active one the earliest-starting comment does, which for a lone highlight
+ // is simply itself.
+ const lead = open.covering.find((a) => isActive(a, activeId));
+ segments.push({
+ from: open.from,
+ to: open.to,
+ style: style(lead ?? open.covering[0], lead !== undefined),
+ threadId: narrowestThread(open.covering),
+ });
+ open = null;
+ };
+
+ for (let i = 0; i < edges.length - 1; i++) {
+ const from = edges[i];
+ const to = edges[i + 1];
+ const covering = anchors.filter((a) => a.from <= from && a.to >= to);
+ if (covering.length === 0) {
+ close();
+ continue;
+ }
+ if (open !== null && open.to === from && coverKey(open.covering) === coverKey(covering)) {
+ open.to = to;
+ continue;
+ }
+ close();
+ open = { from, to, covering };
+ }
+ close();
+
+ return segments;
+}
diff --git a/packages/app/src/comments/anchor-search.test.ts b/packages/app/src/comments/anchor-search.test.ts
new file mode 100644
index 000000000..190580329
--- /dev/null
+++ b/packages/app/src/comments/anchor-search.test.ts
@@ -0,0 +1,158 @@
+/**
+ * Anchor resolution against a repeated quote.
+ *
+ * The bug this pins: `indexOf` returns the FIRST match, so a phrase that appears
+ * twice in a document highlighted and scrolled to the wrong occurrence. The
+ * stored prefix/suffix have to break the tie.
+ *
+ * Exercises `findRangeInIndex` against a hand-built index rather than a real
+ * ProseMirror doc — the disambiguation logic is what's under test, and the index
+ * shape (`text` + per-character positions) is trivially constructible.
+ */
+
+import { describe, expect, test } from 'vitest';
+import { findRangeInIndex } from './anchor-search';
+
+/** Build the index `buildTextIndex` would produce, with PM positions offset by 1. */
+function indexOf(text: string): { text: string; positions: number[] } {
+ return { text, positions: Array.from({ length: text.length }, (_, i) => i + 1) };
+}
+
+const DOC = 'Add the garlic and cook 1 min. Stir the sauce. Add the garlic and serve.';
+const FIRST = DOC.indexOf('Add the garlic');
+const SECOND = DOC.indexOf('Add the garlic', FIRST + 1);
+
+describe('findRangeInIndex — repeated quote', () => {
+ test('the fixture really does repeat (guards the guard)', () => {
+ expect(FIRST).toBeGreaterThanOrEqual(0);
+ expect(SECOND).toBeGreaterThan(FIRST);
+ });
+
+ test('suffix context selects the SECOND occurrence', () => {
+ const range = findRangeInIndex(indexOf(DOC), 'Add the garlic', {
+ prefix: 'Stir the sauce. ',
+ suffix: ' and serve.',
+ });
+ // positions are 1-based in the fixture, matching buildTextIndex's offset
+ expect(range).toEqual({ from: SECOND + 1, to: SECOND + 1 + 'Add the garlic'.length });
+ });
+
+ test('prefix context selects the FIRST occurrence', () => {
+ const range = findRangeInIndex(indexOf(DOC), 'Add the garlic', {
+ prefix: '',
+ suffix: ' and cook 1 min.',
+ });
+ expect(range).toEqual({ from: FIRST + 1, to: FIRST + 1 + 'Add the garlic'.length });
+ });
+
+ test('without context it falls back to the first match (the old behavior)', () => {
+ const range = findRangeInIndex(indexOf(DOC), 'Add the garlic');
+ expect(range?.from).toBe(FIRST + 1);
+ });
+
+ test('identical context on both hits falls back to the nearest position hint', () => {
+ const doc = 'x TARGET y x TARGET y';
+ const second = doc.indexOf('TARGET', doc.indexOf('TARGET') + 1);
+ const range = findRangeInIndex(indexOf(doc), 'TARGET', {
+ prefix: 'x ',
+ suffix: ' y',
+ start: second,
+ });
+ expect(range?.from).toBe(second + 1);
+ });
+
+ test('a quote that is gone resolves to null', () => {
+ expect(findRangeInIndex(indexOf(DOC), 'text that is not there')).toBeNull();
+ });
+
+ test('a unique quote needs no context', () => {
+ const range = findRangeInIndex(indexOf(DOC), 'Stir the sauce');
+ expect(range?.from).toBe(DOC.indexOf('Stir the sauce') + 1);
+ });
+});
+
+describe('findRangeInIndex — a markdown quote against rendered text', () => {
+ // The stored quote is a slice of the markdown BODY, so a passage with any
+ // formatting is not literally present in the editor's rendered text. Before
+ // the elastic pass, every such comment silently failed to highlight or scroll.
+ const RENDERED = 'Peanut sauce: 3 tbsp peanut butter, 2 tbsp soy sauce, water to loosen';
+
+ test('locates a quote carrying emphasis markers the editor does not render', () => {
+ const range = findRangeInIndex(indexOf(RENDERED), 'Peanut sauce:** 3 tbsp peanut butter');
+ const start = RENDERED.indexOf('Peanut sauce: 3 tbsp peanut butter');
+ expect(range).toEqual({
+ from: start + 1,
+ to: start + 1 + 'Peanut sauce: 3 tbsp peanut butter'.length,
+ });
+ });
+
+ test('locates a quote carrying a list marker', () => {
+ const range = findRangeInIndex(indexOf(RENDERED), '- **Peanut sauce:** 3 tbsp');
+ expect(range?.from).toBe(1);
+ });
+
+ test('still returns null when the words are absent', () => {
+ expect(findRangeInIndex(indexOf(RENDERED), '**Chili crisp:** 1 tbsp')).toBeNull();
+ });
+});
+
+describe('findRangeInIndex — the passage was edited, not removed', () => {
+ // The reported bug: comment on "needs space", edit it to "needs more space",
+ // highlight vanishes. The server only re-finds on queue/dispatch, so the
+ // document view has to recover the range itself.
+ const DOC = 'Intro line. The layout needs space around the header. Outro line.';
+
+ test('follows an insertion inside the passage', () => {
+ const edited = DOC.replace('needs space', 'needs more space');
+ const range = findRangeInIndex(indexOf(edited), 'needs space', {
+ prefix: 'The layout ',
+ suffix: ' around the header.',
+ });
+ const at = edited.indexOf('needs more space');
+ expect(range).toEqual({ from: at + 1, to: at + 1 + 'needs more space'.length });
+ });
+
+ test('follows a deletion inside the passage', () => {
+ const edited = DOC.replace('needs space around', 'needs space near');
+ const range = findRangeInIndex(indexOf(edited), 'needs space around', {
+ prefix: 'The layout ',
+ suffix: ' the header.',
+ });
+ const at = edited.indexOf('needs space near');
+ expect(range).toEqual({ from: at + 1, to: at + 1 + 'needs space near'.length });
+ });
+
+ test('an intact passage never reaches the bracket path', () => {
+ const range = findRangeInIndex(indexOf(DOC), 'needs space', {
+ prefix: 'The layout ',
+ suffix: ' around the header.',
+ });
+ const at = DOC.indexOf('needs space');
+ expect(range).toEqual({ from: at + 1, to: at + 1 + 'needs space'.length });
+ });
+
+ test('declines when the brackets are ambiguous', () => {
+ const twice = 'A x B and later A y B';
+ expect(findRangeInIndex(indexOf(twice), 'gone', { prefix: 'A ', suffix: ' B' })).toBeNull();
+ });
+
+ test('declines a wholesale replacement between the brackets', () => {
+ const edited = DOC.replace('needs space', 'z'.repeat(400));
+ expect(
+ findRangeInIndex(indexOf(edited), 'needs space', {
+ prefix: 'The layout ',
+ suffix: ' around the header.',
+ }),
+ ).toBeNull();
+ });
+
+ test('declines when the passage was deleted outright', () => {
+ const edited = DOC.replace('needs space ', '');
+ expect(
+ findRangeInIndex(indexOf(edited), 'needs space', {
+ prefix: 'The layout ',
+ suffix: 'around the header.',
+ }),
+ ).toBeNull();
+ });
+});
diff --git a/packages/app/src/comments/anchor-search.ts b/packages/app/src/comments/anchor-search.ts
new file mode 100644
index 000000000..bf81f366f
--- /dev/null
+++ b/packages/app/src/comments/anchor-search.ts
@@ -0,0 +1,241 @@
+/**
+ * Shared anchor resolver — locate a comment's passage in the live document.
+ *
+ * Flattens the doc's text nodes into a string carrying each character's
+ * ProseMirror position, then finds the quote. The quote is a slice of the
+ * markdown BODY and this index is RENDERED text, so a literal search runs
+ * first and a markdown-syntax-elastic search (`findAllPassages`) second — the
+ * latter is what locates a passage that carries `**`, a `- `, or a `##` the
+ * editor no longer shows. Neither pass is fuzzy: every rendered character must
+ * still match, in order.
+ *
+ * A REPEATED quote is the case that matters: `indexOf` alone always returns the
+ * first match, so a phrase appearing twice highlights and scrolls to the wrong
+ * one. The stored `prefix`/`suffix` (widened at create time until the passage
+ * was unique) disambiguate, mirroring how the server re-finds it — score each
+ * candidate by how much surrounding context still matches, then fall back to
+ * whichever sits nearest the last known position.
+ *
+ * The server's `start`/`end` can't be used directly here: those are offsets into
+ * the markdown BODY, while this index is over RENDERED text, so markdown syntax
+ * characters make the two disagree. Context matching works on text content and
+ * degrades gracefully when the surroundings have also changed.
+ */
+
+import { findAllPassages, type PassageMatch } from '@inkeep/open-knowledge-core';
+import type { Node as PMNode } from '@tiptap/pm/model';
+
+interface TextIndex {
+ text: string;
+ positions: number[];
+}
+
+/** The stored context around a passage, used only to disambiguate repeats. */
+export interface AnchorContext {
+ prefix?: string;
+ suffix?: string;
+ /** Last known offset — a weak final tie-break when context can't separate hits. */
+ start?: number;
+}
+
+export function buildTextIndex(doc: PMNode): TextIndex {
+ let text = '';
+ const positions: number[] = [];
+ doc.descendants((node, pos) => {
+ if (node.isText && node.text) {
+ for (let i = 0; i < node.text.length; i++) {
+ text += node.text[i];
+ positions.push(pos + i);
+ }
+ }
+ return true;
+ });
+ return { text, positions };
+}
+
+function allOccurrences(haystack: string, needle: string): number[] {
+ const out: number[] = [];
+ if (needle === '') return out;
+ let i = haystack.indexOf(needle);
+ while (i !== -1) {
+ out.push(i);
+ i = haystack.indexOf(needle, i + 1);
+ }
+ return out;
+}
+
+/** Length of the longest common suffix of `a` and `b`. */
+function commonSuffixLen(a: string, b: string): number {
+ const n = Math.min(a.length, b.length);
+ let i = 0;
+ while (i < n && a[a.length - 1 - i] === b[b.length - 1 - i]) i += 1;
+ return i;
+}
+
+/** Length of the longest common prefix of `a` and `b`. */
+function commonPrefixLen(a: string, b: string): number {
+ const n = Math.min(a.length, b.length);
+ let i = 0;
+ while (i < n && a[i] === b[i]) i += 1;
+ return i;
+}
+
+/**
+ * How much the passage may grow when recovered from its brackets.
+ *
+ * DRIFT WARNING: mirrors `MAX_REWRITE_GROWTH` / `REWRITE_GROWTH_FLOOR` in the
+ * server's `anchor.ts`. The two run on different substrates — rendered text here,
+ * the markdown body there — so they cannot share an implementation, but they
+ * must agree on the policy or a passage recovers in the document and orphans on
+ * dispatch, or the reverse.
+ */
+const MAX_REWRITE_GROWTH = 4;
+const REWRITE_GROWTH_FLOOR = 64;
+
+/**
+ * Locate a passage whose text changed, by the context still surrounding it.
+ *
+ * Both brackets must match exactly once and in order; whatever sits between
+ * them is the passage. Ambiguity or runaway growth declines rather than guesses
+ * — the same rule the quote search follows.
+ */
+function findBetweenBrackets(
+ text: string,
+ quote: string,
+ context?: AnchorContext,
+): PassageMatch | null {
+ const prefix = context?.prefix ?? '';
+ const suffix = context?.suffix ?? '';
+ // Both empty means there is no bracket to recover from.
+ if (prefix === '' && suffix === '') return null;
+
+ const starts =
+ prefix === ''
+ ? [0]
+ : findAllPassages(text, prefix, { syntaxIn: 'needle' }).map((hit) => hit.end);
+ const ends =
+ suffix === ''
+ ? [text.length]
+ : findAllPassages(text, suffix, { syntaxIn: 'needle' }).map((hit) => hit.start);
+ if (starts.length !== 1 || ends.length !== 1) return null;
+
+ // Whitespace at the bracket seams belongs to neither side. The matcher never
+ // begins a match on whitespace, so a suffix that starts with a space matches a
+ // character late and the span would otherwise swallow the gap.
+ let start = starts[0];
+ let end = ends[0];
+ while (start < end && /\s/.test(text[start] ?? '')) start += 1;
+ while (end > start && /\s/.test(text[end - 1] ?? '')) end -= 1;
+ if (end <= start) return null;
+ const ceiling = Math.max(quote.length * MAX_REWRITE_GROWTH, quote.length + REWRITE_GROWTH_FLOOR);
+ if (end - start > ceiling) return null;
+ return { start, end };
+}
+
+function toRange(index: TextIndex, hit: PassageMatch): { from: number; to: number } | null {
+ const from = index.positions[hit.start];
+ const to = index.positions[hit.end - 1];
+ if (from == null || to == null) return null;
+ return { from, to: to + 1 };
+}
+
+export function findRangeInIndex(
+ index: TextIndex,
+ quote: string,
+ context?: AnchorContext,
+): { from: number; to: number } | null {
+ if (quote.length === 0) return null;
+ // The stored quote is a slice of the markdown BODY, so a passage carrying any
+ // formatting (`**Peanut sauce:**`, a list item's `- `) is not literally
+ // present in the rendered text. Literal hits first — they're exact and the
+ // common case — then the same passage with markdown syntax treated as
+ // elastic.
+ let hits: PassageMatch[] = allOccurrences(index.text, quote).map((at) => ({
+ start: at,
+ end: at + quote.length,
+ }));
+ if (hits.length === 0) hits = findAllPassages(index.text, quote, { syntaxIn: 'needle' });
+ // Still nothing: the passage may have been EDITED rather than removed. Recover
+ // it from its brackets, the same way the server's `refind` does — the server
+ // only re-finds on queue/dispatch, so without this the highlight disappears
+ // the moment you edit the words you commented on.
+ if (hits.length === 0) {
+ const recovered = findBetweenBrackets(index.text, quote, context);
+ return recovered === null ? null : toRange(index, recovered);
+ }
+ if (hits.length === 1) return toRange(index, hits[0]);
+
+ // Repeated quote: prefer the hit whose surrounding text best matches the
+ // context captured when the comment was written.
+ const prefix = context?.prefix ?? '';
+ const suffix = context?.suffix ?? '';
+ let best: PassageMatch[] = [];
+ let bestScore = -1;
+ for (const hit of hits) {
+ const score =
+ commonSuffixLen(prefix, index.text.slice(0, hit.start)) +
+ commonPrefixLen(suffix, index.text.slice(hit.end));
+ if (score > bestScore) {
+ bestScore = score;
+ best = [hit];
+ } else if (score === bestScore) {
+ best.push(hit);
+ }
+ }
+ if (best.length === 1) return toRange(index, best[0]);
+
+ // Context couldn't separate them — take the one nearest the last known
+ // position. Body and rendered offsets aren't identical, but both advance
+ // monotonically through the document, so "nearest" still orders correctly.
+ const hint = context?.start;
+ if (hint === undefined) return toRange(index, best[0]);
+ let nearest = best[0];
+ let nearestDist = Number.POSITIVE_INFINITY;
+ for (const hit of best) {
+ const dist = Math.abs(hit.start - hint);
+ if (dist < nearestDist) {
+ nearestDist = dist;
+ nearest = hit;
+ }
+ }
+ return toRange(index, nearest);
+}
+
+/**
+ * How much rendered text to capture either side of a selection. Enough to
+ * separate two occurrences of a passage; not so much that it carries the
+ * document.
+ */
+const SELECTION_CONTEXT_LEN = 64;
+
+/**
+ * The rendered text immediately around `[from, to)` — what tells the server
+ * WHICH occurrence was selected when the quoted words repeat.
+ *
+ * Without it the server can only take the first match, so commenting on the
+ * second of two identical passages anchors the thread to the first, and the
+ * create-time context widening then makes that wrong choice unambiguous. The
+ * editor is the only place that knows which one the user actually picked, and
+ * `quote` alone throws that away.
+ *
+ * Rendered text, like the quote it accompanies: the server scores it against
+ * markdown and tolerates the difference.
+ */
+export function captureSelectionContext(
+ doc: PMNode,
+ from: number,
+ to: number,
+): { prefix: string; suffix: string } {
+ return {
+ prefix: doc.textBetween(Math.max(0, from - SELECTION_CONTEXT_LEN), from, '\n'),
+ suffix: doc.textBetween(to, Math.min(doc.content.size, to + SELECTION_CONTEXT_LEN), '\n'),
+ };
+}
+
+export function findQuoteRange(
+ doc: PMNode,
+ quote: string,
+ context?: AnchorContext,
+): { from: number; to: number } | null {
+ return findRangeInIndex(buildTextIndex(doc), quote, context);
+}
diff --git a/packages/app/src/comments/anchor-transaction-effect.test.ts b/packages/app/src/comments/anchor-transaction-effect.test.ts
new file mode 100644
index 000000000..be97698c1
--- /dev/null
+++ b/packages/app/src/comments/anchor-transaction-effect.test.ts
@@ -0,0 +1,57 @@
+/**
+ * Which transactions are allowed to skip a decoration rebuild.
+ *
+ * Every arrow key, click, and focus change dispatches a ProseMirror
+ * transaction. Rebuilding the anchor decorations on all of them means building
+ * a character-position index and re-resolving every open thread against it —
+ * and for a thread whose quote no longer matches the document, re-resolving
+ * costs three full-document scans. Measured on a 100k-character document with
+ * 40 such threads, that was ~76 ms of work for pressing an arrow key.
+ *
+ * A regression here is invisible: the highlights stay correct, they just cost
+ * far more than they should. So the classification itself is the assertion.
+ */
+
+import { describe, expect, test } from 'vitest';
+import { anchorTransactionEffect } from './anchor-decorations';
+
+const idle = { docChanged: false };
+const edited = { docChanged: true };
+
+describe('anchorTransactionEffect', () => {
+ test('a selection-only transaction reuses the existing decorations', () => {
+ // The case the whole change exists for: cursor moves, clicks, focus.
+ expect(anchorTransactionEffect(idle, undefined)).toBe('reuse');
+ });
+
+ test('a document edit rebuilds', () => {
+ expect(anchorTransactionEffect(edited, undefined)).toBe('rebuild');
+ });
+
+ test("the store's redraw ping rebuilds even though the document is unchanged", () => {
+ // Thread state is not part of editor state, so a resolve, an edit, or a
+ // change of active thread reaches the plugin ONLY as this meta. Treating it
+ // as idle would freeze the highlights.
+ expect(anchorTransactionEffect(idle, { refresh: true })).toBe('rebuild');
+ });
+
+ test('setting the composer draft is its own effect', () => {
+ expect(anchorTransactionEffect(idle, { draft: { from: 3, to: 9 } })).toBe('draft');
+ });
+
+ test('clearing the composer draft still counts as a draft change', () => {
+ // `{ draft: null }` is how cancel and post clear the pending highlight —
+ // a null payload must not be mistaken for "no meta".
+ expect(anchorTransactionEffect(idle, { draft: null })).toBe('draft');
+ });
+
+ test('a draft change during an edit is handled as a draft change', () => {
+ expect(anchorTransactionEffect(edited, { draft: null })).toBe('draft');
+ });
+
+ test('an unrelated meta value does not reuse', () => {
+ // Anything we do not recognise is treated as a reason to rebuild rather
+ // than a reason to skip — wrong-but-cheap beats wrong-and-stale.
+ expect(anchorTransactionEffect(idle, 'something-else')).toBe('rebuild');
+ });
+});
diff --git a/packages/app/src/comments/append-to-open-session.ts b/packages/app/src/comments/append-to-open-session.ts
new file mode 100644
index 000000000..9b7eb3787
--- /dev/null
+++ b/packages/app/src/comments/append-to-open-session.ts
@@ -0,0 +1,94 @@
+/**
+ * Send the queue INTO the conversation already open, instead of starting one.
+ *
+ * The dispatch path always begins a fresh turn — a new agent thread, a new CLI
+ * launch, a deep link. That is wrong when you have been working with an agent
+ * and the comments are follow-up for it: the batch arrives detached from
+ * everything already discussed.
+ *
+ * The reuse machinery already exists for the editor's Ask AI affordances.
+ * `requestActiveTerminalInput` hands text to `TerminalSessionsHost`, which
+ * writes it into the live session — a thread takes it as a staged composer
+ * draft, a live CLI tab as a no-carriage-return write into its input — and only
+ * launches something new when there is nothing to reuse.
+ *
+ * **The queue's own send leaves everything queued and unsent.** The human
+ * presses enter, and this side cannot know whether the agent ever ran — marking
+ * work done that nobody has acted on is the failure the queue exists to prevent.
+ *
+ * `resolve` opts out of that caution, for the one caller where it does not
+ * apply: the selection composer's "Send to AI" writes a comment and hands it
+ * over in a single gesture, so it was never a queued review item to begin with.
+ * Leaving it open would put it in the batch the reviewer sends LATER, and they
+ * would send the same note twice.
+ */
+
+import { requestActiveTerminalInput } from '@/components/handoff/terminal-input-events';
+import { composeCommentBatchInstruction, toCommentBatchItem } from './comment-chips';
+import { dispatchComments } from './store';
+
+/**
+ * Compose the checked queue and write it into the active session's input.
+ * Returns how many comments were staged (0 when nothing was checked, the
+ * prepare failed, or every thread had gone).
+ *
+ * Goes through `prepareDispatchBatch` rather than the local store: the server
+ * re-anchors on prepare, so a passage that moved is reported as lost HERE, and
+ * it is the only side that knows whether a quote repeats in its document — the
+ * two facts that stop an agent editing the wrong passage.
+ */
+export async function appendQueueToOpenSession({
+ sharedInstruction = '',
+ threadIds,
+ submit = false,
+ resolve = false,
+}: {
+ sharedInstruction?: string;
+ /**
+ * Send exactly these instead of the checked queue.
+ *
+ * The composer's "Send to AI" hands over the ONE comment just written, which
+ * is not in the checked set yet and must not drag the rest of the queue along
+ * with it.
+ */
+ threadIds?: readonly string[];
+ /**
+ * Run it on a FRESH session instead of staging a draft there.
+ *
+ * Only reaches the fresh-launch fallback: reuse writes into a live input and
+ * has never pressed enter, by design. So "Send to AI" with a chat already open
+ * stages the batch for you to send, and with none open runs it — which is the
+ * same asymmetry every other Ask AI surface has.
+ */
+ submit?: boolean;
+ /**
+ * Close the threads once handed over, instead of leaving them queued.
+ *
+ * Resolving is also what takes them OUT of the queue — the two are one state
+ * change, so this cannot leave a thread resolved-but-still-listed.
+ */
+ resolve?: boolean;
+} = {}): Promise<number> {
+ // Routed through the ONE dispatch path rather than reimplementing it: that is
+ // what gives this the re-entrancy guard (a second click used to start a second
+ // hand-off), the re-anchor-on-prepare, and the single resolve call site. All
+ // this contributes is WHERE the batch goes.
+ const shipped = await dispatchComments({
+ threadIds,
+ resolve,
+ compose: async (items) => {
+ requestActiveTerminalInput(
+ composeCommentBatchInstruction(
+ items.map((item) => toCommentBatchItem(item.payload)),
+ sharedInstruction,
+ ),
+ // `newTab: false` is the whole point — reuse the session you are in.
+ { newTab: false, submit },
+ );
+ // The write into a live input is synchronous and unacknowledged; there is
+ // nothing to fail. Reporting success is what lets `resolve` mean anything.
+ return true;
+ },
+ });
+ return shipped.length;
+}
diff --git a/packages/app/src/comments/comment-chips.dom.test.tsx b/packages/app/src/comments/comment-chips.dom.test.tsx
new file mode 100644
index 000000000..4b71fa5d5
--- /dev/null
+++ b/packages/app/src/comments/comment-chips.dom.test.tsx
@@ -0,0 +1,151 @@
+/**
+ * The ✕ on the queued-comments chip is a DISMISS, not a clear.
+ *
+ * It used to call `clearQueue()` — a server round-trip that unqueued every
+ * thread in the project, with no confirmation and no undo — while wearing the
+ * same affordance as the file chip's ✕ and the selection pill's ✕, both of which
+ * only stop carrying context. Destroying the batch belongs to the Queue panel's
+ * labelled Clear. These pin the three controls apart.
+ */
+
+import * as actualLinguiMacro from '@lingui/react/macro';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+
+vi.doMock('@lingui/react/macro', () => ({
+ ...actualLinguiMacro,
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ Plural: ({ value }: { value: number }) => <>{value}</>,
+ useLingui: () => ({
+ t: (strings: TemplateStringsArray, ...values: unknown[]) =>
+ strings.reduce((acc, part, index) => `${acc}${part}${values[index] ?? ''}`, ''),
+ }),
+}));
+
+afterEach(() => cleanup());
+
+async function renderChip(
+ props: Partial<{
+ count: number;
+ attached: boolean;
+ expanded: boolean;
+ onAttach: () => void;
+ onToggleExpanded: () => void;
+ onDismiss: () => void;
+ }> = {},
+) {
+ const { QueuedCommentsChip } = await import('./comment-chips');
+ return render(
+ <QueuedCommentsChip
+ count={props.count ?? 3}
+ // Attached by default: the ✕/peek distinction these pin down only exists
+ // in that state.
+ attached={props.attached ?? true}
+ expanded={props.expanded ?? false}
+ onAttach={props.onAttach ?? (() => {})}
+ onToggleExpanded={props.onToggleExpanded ?? (() => {})}
+ onDismiss={props.onDismiss ?? (() => {})}
+ />,
+ );
+}
+
+describe('the queued-comments chip', () => {
+ test('the ✕ dismisses and does nothing else', async () => {
+ let dismissed = 0;
+ let expanded = 0;
+ await renderChip({
+ onDismiss: () => {
+ dismissed += 1;
+ },
+ onToggleExpanded: () => {
+ expanded += 1;
+ },
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: /leave these comments out/i }));
+ expect(dismissed).toBe(1);
+ expect(expanded).toBe(0);
+ });
+
+ test('its name says it affects the message, not the queue', async () => {
+ await renderChip();
+ // A name like "Clear queued comments" would promise destruction; this button
+ // only takes the batch out of this one send.
+ expect(
+ screen.getByRole('button', { name: /leave these comments out of this message/i }),
+ ).toBeTruthy();
+ expect(screen.queryByRole('button', { name: /clear/i })).toBeNull();
+ });
+
+ test('peeking is a separate control from dismissing', async () => {
+ let dismissed = 0;
+ let expanded = 0;
+ await renderChip({
+ onDismiss: () => {
+ dismissed += 1;
+ },
+ onToggleExpanded: () => {
+ expanded += 1;
+ },
+ });
+
+ fireEvent.click(screen.getByTestId('composer-comments-peek'));
+ expect(expanded).toBe(1);
+ expect(dismissed).toBe(0);
+ });
+
+ test('an empty queue renders no chip', async () => {
+ await renderChip({ count: 0 });
+ expect(screen.queryByTestId('composer-context-chip-comments')).toBeNull();
+ });
+
+ test('attached, the chip drops the add affordance', async () => {
+ await renderChip({ attached: true });
+ // A `+` on a chip that is already carried would read as "add another".
+ expect(
+ screen.getByTestId('composer-context-chip-comments').querySelector('svg.lucide-plus'),
+ ).toBeNull();
+ });
+
+ test('detached, the chip is the attach control', async () => {
+ let attached = 0;
+ let expanded = 0;
+ await renderChip({
+ attached: false,
+ onAttach: () => {
+ attached += 1;
+ },
+ onToggleExpanded: () => {
+ expanded += 1;
+ },
+ });
+
+ // Attaching is opt-in, so something has to say a queue exists before you opt
+ // in — the chip's presence is that signal, and it names the source it would
+ // pull from rather than the count it would carry.
+ const chip = screen.getByTestId('composer-context-chip-comments');
+ expect(chip.textContent).toContain('Queue');
+ expect(chip.getAttribute('aria-pressed')).toBe('false');
+ // The two states occupy the same slot at different times, so the icon is what
+ // distinguishes them — there is never a second chip to compare a fill against.
+ expect(chip.querySelector('svg.lucide-plus')).not.toBeNull();
+
+ fireEvent.click(chip);
+ expect(attached).toBe(1);
+ // One control, one bit: the detached chip neither peeks nor dismisses.
+ expect(expanded).toBe(0);
+ expect(screen.queryByRole('button', { name: /leave these comments out/i })).toBeNull();
+ expect(screen.queryByTestId('composer-comments-peek')).toBeNull();
+ });
+
+ test('attaching is not sending — the chip only says what rides the message', async () => {
+ await renderChip({ attached: false });
+ // A name like "Send comments" would promise dispatch; this puts the batch on
+ // the message and leaves the send to the send button.
+ expect(
+ screen.getByRole('button', { name: /add the queued comments to this message/i }),
+ ).toBeTruthy();
+ expect(screen.queryByRole('button', { name: /send/i })).toBeNull();
+ });
+});
diff --git a/packages/app/src/comments/comment-chips.tsx b/packages/app/src/comments/comment-chips.tsx
new file mode 100644
index 000000000..31f9d6b30
--- /dev/null
+++ b/packages/app/src/comments/comment-chips.tsx
@@ -0,0 +1,546 @@
+/**
+ * Queued comments as a context chip in the persistent "Ask AI" composer.
+ *
+ * The queue lives where you already are rather than behind a panel tab: posting
+ * a comment adds it to the composer as a chip, typing gives the whole batch a
+ * shared instruction, and the composer's existing send button + agent picker
+ * dispatch it. Commenting and asking become one gesture, which is the point of
+ * the feature — a separate "dispatch" surface split them again.
+ *
+ * One send = ONE agent turn carrying every queued comment, so an agent handling
+ * several related notes sees them together. (The alternative — a turn per
+ * comment — isolates failures but fragments the conversation.)
+ */
+
+import { Plural, Trans, useLingui } from '@lingui/react/macro';
+import { ChevronDown, FileText, MessageSquare, Plus, Unlink, X } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Checkbox } from '@/components/ui/checkbox';
+import { cn } from '@/lib/utils';
+import type { DispatchPayload } from './comments-client';
+import { revealPropertyValueRange } from './property-row-rect';
+import { revealComment } from './reveal-comment';
+import {
+ getThreadById,
+ removeFromQueue,
+ toggleQueueSelection,
+ useQueue,
+ useQueueSelection,
+} from './store';
+import type { CommentThread } from './types';
+
+/** The queued comments backing the composer chip, in queue order. */
+export function useQueuedComments(): CommentThread[] {
+ const ids = useQueue();
+ const threads: CommentThread[] = [];
+ for (const id of ids) {
+ const thread = getThreadById(id);
+ if (thread !== null) threads.push(thread);
+ }
+ return threads;
+}
+
+/**
+ * How many queued comments are actually checked — what a send would carry.
+ *
+ * The chip counts this rather than the whole queue: unchecking an item has to
+ * change the number, or the control gives no feedback and the count promises
+ * more than the send delivers.
+ */
+export function useSelectedCommentCount(): number {
+ return useQueueSelection().length;
+}
+
+/**
+ * One chip standing for the whole batch (`3 comments`), matching how the
+ * selection pill reads — a count plus a remove control, never raw content.
+ *
+ * The chip is also the ATTACH control, which is why it renders whenever
+ * anything is queued rather than only once the batch is riding the message.
+ * Attaching is opt-in, so something has to say a queue exists — and the count
+ * is that something. Behind a `+` menu it was one click deep and invisible until
+ * you went looking, which made a queue you had just built read as lost.
+ *
+ * Unattached it is a single toggle: click to put the batch on this message.
+ * Attached it grows the two controls the other context chips carry — a peek
+ * (what am I about to send) and a ✕ (stop carrying it).
+ */
+export function QueuedCommentsChip({
+ count,
+ attached,
+ expanded,
+ onAttach,
+ onToggleExpanded,
+ onDismiss,
+}: {
+ count: number;
+ /** The batch is riding this message. Unattached, the chip is an add button. */
+ attached: boolean;
+ expanded: boolean;
+ /** Put the queue ON this message. The queue itself is untouched either way. */
+ onAttach: () => void;
+ onToggleExpanded: () => void;
+ /**
+ * Take the queue OUT of this message — it does not touch the queue itself.
+ *
+ * The sibling controls in this row (a file chip's ✕, the selection pill's ✕)
+ * all mean "stop carrying this", so an ✕ here that emptied the batch would be
+ * the one destructive button wearing a dismiss affordance. Destroying the
+ * queue is the Queue panel's labelled Clear.
+ */
+ onDismiss: () => void;
+}) {
+ const { t } = useLingui();
+ if (count === 0) return null;
+ if (!attached) {
+ return (
+ // The leading `+` carries the state, not the border. The two chips sit in
+ // the same row at different times rather than side by side, so a fill or
+ // outline difference has nothing to be read against — `+` vs. the comment
+ // mark is legible with no second chip to compare to, and says which way the
+ // click goes. Dashed border reinforces it for anyone who reads the shape
+ // before the icon.
+ //
+ // Detached it names the SOURCE ("Queue"), attached the CONTENT ("2
+ // comments"): one is what you are about to pick up, the other what this
+ // message carries, and the sibling chips already name content that way.
+ // No count while detached — the chip's presence is the signal that a queue
+ // is waiting, and the number only becomes a fact about this message once
+ // the batch is on it.
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ aria-pressed={false}
+ aria-label={t`Add the queued comments to this message`}
+ onClick={onAttach}
+ data-testid="composer-context-chip-comments"
+ className={cn(
+ 'h-auto min-h-0 gap-1 rounded-md border border-dashed bg-transparent px-1.5 py-0.5',
+ 'text-xs font-normal text-muted-foreground hover:bg-muted/60 hover:text-foreground',
+ )}
+ >
+ <Plus className="size-3" />
+ <Trans>Queue</Trans>
+ </Button>
+ );
+ }
+ return (
+ <span
+ data-testid="composer-context-chip-comments"
+ className={cn(
+ 'inline-flex items-center gap-1 rounded-md border bg-muted/60 py-0.5 pr-0.5 pl-1.5',
+ 'text-xs text-muted-foreground',
+ )}
+ >
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ aria-expanded={expanded}
+ aria-label={expanded ? t`Hide queued comments` : t`Show queued comments`}
+ onClick={onToggleExpanded}
+ data-testid="composer-comments-peek"
+ className="h-auto min-h-0 gap-1 px-0.5 py-0 text-xs font-normal text-muted-foreground hover:text-foreground"
+ >
+ <MessageSquare className="size-3" />
+ <Plural value={count} one="# comment" other="# comments" />
+ <ChevronDown className={cn('size-3 transition-transform', expanded && 'rotate-180')} />
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ aria-label={t`Leave these comments out of this message`}
+ onClick={onDismiss}
+ className="size-4 p-0 text-muted-foreground hover:text-foreground"
+ >
+ <X className="size-3" />
+ </Button>
+ </span>
+ );
+}
+
+/** Last path segment — the compact file label, matching the file chips. */
+export function docBasename(docName: string): string {
+ const slash = docName.lastIndexOf('/');
+ return slash >= 0 ? docName.slice(slash + 1) : docName;
+}
+
+/**
+ * `tags`, `tags[2]`, `author.name` — a property address as a human reads it.
+ *
+ * Mirrors the server's `describeTarget`, which builds the same string for the
+ * agent prompt. Two copies rather than one over the wire because the thread
+ * listing has the target already and a round trip to render a label would be
+ * absurd; they are pinned together by tests on both sides.
+ */
+export function propertyAddress(key: string, path: readonly (string | number)[]): string {
+ let out = key;
+ for (const step of path) out += typeof step === 'number' ? `[${step}]` : `.${step}`;
+ return out;
+}
+
+/**
+ * The one line that says what a thread is ON — shared by every list that shows
+ * threads (the composer peek, the queue panel, the comments panel) so the three
+ * can't drift into describing the same thread differently.
+ *
+ * A whole property renders as `tags:` in the same monospace the quote uses. That
+ * reads as the YAML it is, which distinguishes it from a passage without needing
+ * a label saying "property" — and the trailing colon is the whole difference,
+ * because a bare key and a short quote otherwise look identical.
+ *
+ * A passage inside a value shows BOTH — `description: “ships in Q3”` — because
+ * neither half identifies it alone: several comments can sit on one field, and
+ * the same words can appear in more than one.
+ */
+export function ThreadTargetLine({
+ thread,
+ className,
+}: {
+ thread: CommentThread;
+ className?: string;
+}) {
+ const base = 'w-full truncate font-mono text-[11px] text-muted-foreground';
+ const quote = thread.anchor?.quote ?? '';
+ if (thread.target.kind === 'property') {
+ const address = propertyAddress(thread.target.key, thread.target.path);
+ return (
+ <span className={cn(base, className)}>
+ {address}:{quote === '' ? '' : ` “${quote}”`}
+ </span>
+ );
+ }
+ return <span className={cn(base, className)}>“{quote}”</span>;
+}
+
+/**
+ * Reveal a thread wherever it lives. A passage scrolls the body to its words; a
+ * property has no body range, so it opens the document and lets the properties
+ * panel be where the reader looks — jumping the body to an arbitrary offset
+ * would be worse than not moving at all.
+ */
+export function revealThread(thread: CommentThread): void {
+ revealComment({
+ docName: thread.docName,
+ quote: thread.target.kind === 'property' ? '' : (thread.anchor?.quote ?? ''),
+ threadId: thread.id,
+ context: thread.anchor ?? undefined,
+ });
+ const { target, anchor } = thread;
+ if (target.kind !== 'property' || anchor === null) return;
+ // The queue spans documents, so the call above may have just navigated — the
+ // property panel of the doc we are going to does not exist yet. Retry for a
+ // short window rather than once, and give up quietly: a comment whose words
+ // are gone from the value has nothing to select, and that is already said by
+ // the card's orphaned state.
+ let attempts = 0;
+ const attempt = (): void => {
+ const done = revealPropertyValueRange({
+ key: target.key,
+ path: target.path,
+ quote: anchor.quote,
+ start: anchor.start,
+ end: anchor.end,
+ });
+ if (done) return;
+ attempts += 1;
+ if (attempts >= REVEAL_FRAME_BUDGET) return;
+ requestAnimationFrame(attempt);
+ };
+ requestAnimationFrame(attempt);
+}
+
+/** ~half a second of frames — long enough for a doc switch, short enough to stop. */
+const REVEAL_FRAME_BUDGET = 30;
+
+/**
+ * The expanded queue: one row per comment — check to include it in the next
+ * send, ✕ to drop it entirely. Shows the file, the quoted passage, and what the
+ * reviewer wrote, so the batch can be reviewed without leaving the composer.
+ *
+ * Carries `basis-full` so it drops onto its own line beneath the chip row (the
+ * same mechanism the expanded selection preview uses).
+ */
+export function QueuedCommentsList({ threads }: { threads: readonly CommentThread[] }) {
+ const { t } = useLingui();
+ // USE the subscription's value — do not just call it for the side effect.
+ //
+ // React Compiler memoizes this component's rows on the dependencies it can
+ // see. An imperative store read is not one, and a hook whose result is
+ // discarded contributes no dependency — so toggling a checkbox updated the
+ // store, re-ran this function, and handed back the previous rows. The checkbox
+ // looked dead. Reading through `selectedIds` is what puts the selection inside
+ // React's data flow, and is what the queue panel already did.
+ const selectedIds = useQueueSelection();
+ if (threads.length === 0) return null;
+ return (
+ <ul
+ data-testid="composer-comments-list"
+ className="mt-1 flex max-h-64 basis-full list-none flex-col gap-1 overflow-y-auto subtle-scrollbar"
+ >
+ {threads.map((thread) => {
+ const orphaned = thread.status === 'orphaned';
+ const selected = selectedIds.includes(thread.id);
+ return (
+ <li
+ key={thread.id}
+ className={cn(
+ 'flex items-start gap-2 rounded-md border bg-background/60 px-2 py-1.5',
+ // Unchecked = not going in this send. Dim it so the row's state is
+ // legible at a glance, not only from the checkbox.
+ !selected && 'opacity-50',
+ )}
+ >
+ <Checkbox
+ checked={selected}
+ onCheckedChange={() => toggleQueueSelection(thread.id)}
+ aria-label={t`Include this comment in the next send`}
+ className="mt-0.5"
+ />
+ <div className="flex min-w-0 flex-1 flex-col gap-1">
+ <div className="flex min-w-0 items-center gap-1.5">
+ {/* `min-w-0` on both the row and the chip — a flex child won't
+ compress below its content without it, so `truncate` alone
+ would still overflow. */}
+ <span
+ className="inline-flex min-w-0 items-center gap-1 rounded border px-1 py-px text-[10px] text-muted-foreground"
+ title={thread.docName}
+ >
+ <FileText className="size-2.5 shrink-0" />
+ <span className="truncate">{docBasename(thread.docName)}</span>
+ </span>
+ {orphaned && (
+ <span
+ className="inline-flex shrink-0 items-center gap-1 text-[10px] text-amber-600 dark:text-amber-500"
+ title={t`The quoted text is no longer in the document — the agent will be told.`}
+ >
+ <Unlink className="size-2.5" />
+ <Trans>gone</Trans>
+ </span>
+ )}
+ </div>
+ {/* Click the quote/body to open that document and scroll to the
+ passage — the queue spans files, so this is how you check what
+ you're about to send. */}
+ <Button
+ type="button"
+ variant="ghost"
+ aria-label={t`Go to this comment in ${docBasename(thread.docName)}`}
+ onClick={() => revealThread(thread)}
+ className="h-auto min-h-0 w-full min-w-0 flex-col items-start gap-1 px-0 py-0 text-left font-normal hover:bg-transparent"
+ >
+ <ThreadTargetLine thread={thread} />
+ <span className="line-clamp-2 w-full text-xs whitespace-normal text-foreground/90">
+ {thread.body}
+ </span>
+ </Button>
+ </div>
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ aria-label={t`Remove this comment from the queue`}
+ onClick={() => removeFromQueue(thread.id)}
+ className="size-5 shrink-0 p-0 text-muted-foreground hover:text-foreground"
+ >
+ <X className="size-3" />
+ </Button>
+ </li>
+ );
+ })}
+ </ul>
+ );
+}
+
+/** One queued comment, as the composer hands it to an agent. */
+export interface CommentBatchItem {
+ docName: string;
+ /** What the reviewer wrote on the passage. */
+ body: string;
+ /**
+ * The addressed property — `tags`, `tags[2]`, `author.name` — or null for a
+ * body passage.
+ *
+ * Named rather than quoted: the address IS the identity, so an agent can act
+ * on it with a frontmatter patch instead of hunting for text. When `quote` is
+ * also set, the comment is on a passage INSIDE that value, and both are sent:
+ * the address says which field, the words say where in it.
+ */
+ propertyKey: string | null;
+ /** The anchored passage — the durable record, not an offset. Empty for a whole value. */
+ quote: string;
+ /** The passage or key is no longer in the doc; say so rather than let the agent retarget. */
+ anchorLost: boolean;
+ /** Text immediately before the passage — only rendered when the quote repeats. */
+ prefix: string;
+ /** Text immediately after the passage — only rendered when the quote repeats. */
+ suffix: string;
+ /** The quote occurs more than once in its document. */
+ repeats: boolean;
+}
+
+/**
+ * Server dispatch payload → the shape the batch instruction is composed from.
+ *
+ * One copy, shared by every send path (the composer, the queue panel's send, the
+ * append-to-open-session path, the single-thread delivery hook). They all hand
+ * the same payload to the same composer, and four hand-written copies of this
+ * mapping is four places for a new field to be forgotten in three of them.
+ */
+export function toCommentBatchItem(payload: DispatchPayload): CommentBatchItem {
+ return {
+ docName: payload.docName,
+ body: payload.instruction,
+ propertyKey: payload.property,
+ // A property carries no passage; empty strings keep the shape total so the
+ // composer never branches on undefined, and nothing reads them once
+ // `propertyKey` is set.
+ quote: payload.passage?.exact ?? '',
+ anchorLost: payload.anchorLost,
+ prefix: payload.passage?.prefix ?? '',
+ suffix: payload.passage?.suffix ?? '',
+ repeats: payload.passageRepeats,
+ };
+}
+
+/** Enough context to pick the right occurrence without padding the prompt. */
+const CONTEXT_CHARS = 48;
+
+function trimTail(text: string): string {
+ const flat = text.replace(/\s+/g, ' ').trimStart();
+ return flat.length > CONTEXT_CHARS ? `…${flat.slice(-CONTEXT_CHARS)}` : flat;
+}
+
+function trimHead(text: string): string {
+ const flat = text.replace(/\s+/g, ' ').trimEnd();
+ return flat.length > CONTEXT_CHARS ? `${flat.slice(0, CONTEXT_CHARS)}…` : flat;
+}
+
+/**
+ * Tell the agent WHICH occurrence when the quoted words appear more than once.
+ *
+ * The alternative — sending the stored offsets — looks precise and is worse: a
+ * character offset into the markdown body is a coordinate system the agent does
+ * not work in, and every offset after the first edit of a batch is wrong. The
+ * surrounding text re-locates itself no matter what the agent has already
+ * changed, which is the same reason the anchor is content-addressed at all.
+ */
+function locatingNote(item: CommentBatchItem): string | null {
+ if (!item.repeats) return null;
+ const before = trimTail(item.prefix);
+ const after = trimHead(item.suffix);
+ if (before === '' && after === '') return null;
+ const where =
+ before === ''
+ ? `at the start of the file, followed by "${after}"`
+ : after === ''
+ ? `at the end of the file, preceded by "${before}"`
+ : `between "${before}" and "${after}"`;
+ return `(This text appears more than once in the file. The one meant is ${where} — match that context rather than the first occurrence.)`;
+}
+
+/**
+ * Compose the batch into one instruction: the shared ask the reviewer typed,
+ * then each comment with its document and quoted passage.
+ *
+ * The passages are inlined here rather than ridden as a composer `selection`
+ * because a batch spans documents and the selection scope carries exactly one.
+ * Each entry names its own doc so nothing is attributed to the wrong file.
+ */
+/**
+ * A passage pinned in the composer alongside the batch, if any.
+ *
+ * It rides the prompt TEXT rather than the handoff's structured `selection`
+ * field because a comment batch dispatches at project scope — it spans
+ * documents, so no single doc leads — and `buildComposerHandoffInput` only
+ * carries `selection` on a doc-scoped turn. Every comment's own quote is
+ * already embedded as prose here, so one more labelled block is the same shape,
+ * not a workaround.
+ */
+export interface ExtraPassage {
+ docName: string;
+ markdown: string;
+}
+
+export function composeCommentBatchInstruction(
+ items: readonly CommentBatchItem[],
+ sharedInstruction: string,
+ passage?: ExtraPassage,
+): string {
+ const shared = sharedInstruction.trim();
+ const lines: string[] = [];
+ lines.push(
+ shared.length > 0
+ ? shared
+ : 'Address the following review comments by editing the documents directly.',
+ );
+ lines.push('');
+ lines.push(items.length === 1 ? 'The comment:' : `The ${items.length} comments:`);
+ items.forEach((item, i) => {
+ lines.push('');
+ // Truthy rather than `!== null`: this field crosses the HTTP boundary, so a
+ // payload from a build that predates property targets omits it entirely, and
+ // `undefined` must read as "not a property" exactly as `null` does.
+ if (item.propertyKey) {
+ const quoted = item.quote.trim();
+ // No locating note either way: an address is unique in its frontmatter,
+ // and a quote inside one value has only that value to be confused with —
+ // the note exists for a document-wide ambiguity that cannot arise here.
+ if (quoted === '') {
+ lines.push(
+ `${i + 1}. In \`${item.docName}\`, on the \`${item.propertyKey}\` property (frontmatter):`,
+ );
+ lines.push('');
+ lines.push(` ${item.body.trim()}`);
+ } else {
+ // Both halves: the address says which field to patch, the blockquote says
+ // which part of its text the note is about. An agent given only the words
+ // would have to guess the field; given only the field, it would rewrite
+ // more than was asked.
+ lines.push(
+ `${i + 1}. In \`${item.docName}\`, on this text within the \`${item.propertyKey}\` property (frontmatter):`,
+ );
+ lines.push('');
+ for (const line of quoted.split('\n')) lines.push(` > ${line}`);
+ lines.push('');
+ lines.push(` ${item.body.trim()}`);
+ }
+ if (item.anchorLost) {
+ lines.push('');
+ lines.push(
+ quoted === ''
+ ? ` (Note: \`${item.propertyKey}\` is no longer in this document's frontmatter — it was renamed or removed since the comment was written. Do not apply this to a different property; if you cannot tell what it now refers to, say so instead of guessing.)`
+ : ` (Note: that text is no longer in \`${item.propertyKey}\` — the value was edited, reshaped, or removed since the comment was written. Do not apply this to a different property or a different part of the value; if you cannot tell what it now refers to, say so instead of guessing.)`,
+ );
+ }
+ return;
+ }
+ lines.push(`${i + 1}. In \`${item.docName}\`, on this passage:`);
+ lines.push('');
+ for (const line of item.quote.split('\n')) lines.push(` > ${line}`);
+ lines.push('');
+ lines.push(` ${item.body.trim()}`);
+ const locator = locatingNote(item);
+ if (locator !== null) {
+ lines.push('');
+ lines.push(` ${locator}`);
+ }
+ if (item.anchorLost) {
+ lines.push('');
+ lines.push(
+ ' (Note: this passage is no longer in the document — it was edited or removed since the comment was written. Do not apply this to a different passage; if you cannot tell what it now refers to, say so instead of guessing.)',
+ );
+ }
+ });
+ // Named as separate from the comments so an agent doesn't read it as a fifth
+ // review item with a missing request.
+ if (passage && passage.markdown.trim().length > 0) {
+ lines.push('');
+ lines.push(`Also in scope, selected in \`${passage.docName}\` (not a comment):`);
+ lines.push('');
+ for (const line of passage.markdown.trim().split('\n')) lines.push(`> ${line}`);
+ }
+ return lines.join('\n');
+}
diff --git a/packages/app/src/comments/comment-composer-submit.dom.test.tsx b/packages/app/src/comments/comment-composer-submit.dom.test.tsx
new file mode 100644
index 000000000..26232f1e8
--- /dev/null
+++ b/packages/app/src/comments/comment-composer-submit.dom.test.tsx
@@ -0,0 +1,249 @@
+/**
+ * What the comment composer does with a finished draft.
+ *
+ * The FIELD is `ComposerMentionInput` and is doubled here: Enter-submits,
+ * Shift+Enter-newline, and the IME-composition guard are its behaviour and are
+ * covered by its own tests. Re-driving them through this host would test the
+ * same handler twice and break whenever the field's internals move.
+ *
+ * What is left is what this component owns: which payload gets filed, that a
+ * filed passage stops being selected while a cancelled one does not, and that
+ * "Send to AI" hands over rather than queueing.
+ */
+
+import * as actualLinguiMacro from '@lingui/react/macro';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+
+vi.doMock('@lingui/react/macro', () => ({
+ ...actualLinguiMacro,
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useLingui: () => ({
+ t: (strings: TemplateStringsArray, ...values: unknown[]) =>
+ strings.reduce((acc, part, index) => `${acc}${part}${values[index] ?? ''}`, ''),
+ }),
+}));
+
+// `vi.doMock`, not `vi.mock`: doMock is NOT hoisted, so the factory can close
+// over these declarations and over the top-level lingui import. The component
+// is pulled in with a dynamic import below, after the mocks are registered.
+interface CreateArgs {
+ docName: string;
+ quote: string;
+ body: string;
+ prefix?: string;
+ suffix?: string;
+ onCreated?: (threadId: string) => void;
+}
+
+const captured = {
+ created: [] as CreateArgs[],
+ startComment: null as (() => void) | null,
+ collapsedTo: [] as number[],
+ sent: [] as { threadIds?: readonly string[]; submit?: boolean; resolve?: boolean }[],
+};
+
+/** The field, doubled as a plain textarea that honours the same handle. */
+vi.doMock('@/editor/ComposerMentionInput', () => ({
+ ComposerMentionInput: ({
+ ref,
+ placeholder,
+ onEmptyChange,
+ onSubmit,
+ onEscape,
+ }: {
+ ref?: { current: unknown };
+ placeholder?: string;
+ onEmptyChange: (empty: boolean) => void;
+ onSubmit: () => void;
+ onEscape?: () => void;
+ }) => {
+ // Reads through to the live element rather than a captured local: the host
+ // re-renders on every emptiness change, which would reset a closure variable
+ // and leave `getContent` returning the draft as it was one keystroke ago.
+ return (
+ <textarea
+ placeholder={placeholder}
+ ref={(el) => {
+ if (ref === undefined || ref === null || el === null) return;
+ ref.current = {
+ focus: () => {},
+ blur: () => {},
+ clear: () => {
+ el.value = '';
+ },
+ setText: () => {},
+ getContent: () => ({ instruction: el.value, mentions: [] }),
+ };
+ }}
+ onChange={(e) => {
+ onEmptyChange(e.target.value.trim().length === 0);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' && !e.shiftKey) onSubmit();
+ if (e.key === 'Escape') onEscape?.();
+ }}
+ />
+ );
+ },
+}));
+
+vi.doMock('./append-to-open-session', () => ({
+ appendQueueToOpenSession: (args: Record<string, unknown>) => {
+ captured.sent.push(args);
+ return Promise.resolve(1);
+ },
+}));
+
+vi.doMock('./store', () => ({
+ createThread: (args: CreateArgs) => captured.created.push(args),
+ subscribeStartComment: (cb: () => void) => {
+ captured.startComment = cb;
+ return () => {
+ captured.startComment = null;
+ };
+ },
+}));
+
+// The draft highlight writes through ProseMirror; not what's under test here.
+vi.doMock('./anchor-decorations', () => ({ setCommentDraftRange: () => {} }));
+
+/** The slice of the editor the composer actually touches. */
+function fakeEditor() {
+ return {
+ isDestroyed: false,
+ state: {
+ selection: { from: 4, to: 12, empty: false },
+ // `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 } },
+ },
+ // Records the collapse so the test can assert the passage stops being
+ // "selected for whatever you do next" once it has been filed.
+ commands: { setTextSelection: (pos: number) => captured.collapsedTo.push(pos) },
+ };
+}
+
+afterEach(() => {
+ cleanup();
+ captured.created.length = 0;
+ captured.collapsedTo.length = 0;
+ captured.sent.length = 0;
+ captured.startComment = null;
+});
+
+async function openComposer() {
+ const { CommentSelectionAffordance } = await import('./CommentSelectionAffordance');
+ // biome-ignore lint/suspicious/noExplicitAny: structural editor double
+ render(<CommentSelectionAffordance editor={fakeEditor() as any} docName="recipes/stir-fry" />);
+ captured.startComment?.();
+ return screen.findByPlaceholderText('Add a comment');
+}
+
+describe('the comment composer', () => {
+ test('Add Comment files the passage with the context that disambiguates it', async () => {
+ const field = await openComposer();
+ fireEvent.change(field, { target: { value: 'press it?' } });
+ fireEvent.click(screen.getByRole('button', { name: /add comment/i }));
+
+ // The surrounding text rides along: it is what tells the server which
+ // occurrence was picked when the quoted words appear more than once. The
+ // double returns the same string for every range, so both sides read alike.
+ const [args] = captured.created;
+ expect(args.docName).toBe('recipes/stir-fry');
+ expect(args.quote).toBe('the tofu');
+ expect(args.body).toBe('press it?');
+ expect(args.prefix).toBe('the tofu');
+ expect(args.suffix).toBe('the tofu');
+ // No `onCreated` — filing it is the whole action, so nothing is handed on.
+ expect(args.onCreated).toBeUndefined();
+ });
+
+ test('Enter files it too, so the keyboard never reaches the irreversible one', async () => {
+ const field = await openComposer();
+ fireEvent.change(field, { target: { value: 'press it?' } });
+ fireEvent.keyDown(field, { key: 'Enter' });
+
+ expect(captured.created).toHaveLength(1);
+ expect(captured.created[0].onCreated).toBeUndefined();
+ });
+
+ test('Send to AI hands the comment over and resolves it', async () => {
+ const field = await openComposer();
+ fireEvent.change(field, { target: { value: 'press it?' } });
+ fireEvent.click(screen.getByRole('button', { name: /send to ai/i }));
+
+ const [args] = captured.created;
+ expect(args.body).toBe('press it?');
+ // The send is sequenced behind creation because only the store has the id.
+ expect(args.onCreated).toBeDefined();
+
+ args.onCreated?.('t1');
+ // `resolve` is what keeps it out of the queue: a sent comment is not a
+ // review item waiting to go, and leaving it open would send it twice.
+ expect(captured.sent).toEqual([{ threadIds: ['t1'], submit: true, resolve: true }]);
+ });
+
+ test('posting collapses the selection — the passage has been filed', async () => {
+ // The composer PINS a selection so it survives clicking away into the
+ // input. Filing a comment is the one case where that is wrong: the passage
+ // now rides the batch as that comment's quote, so leaving it selected sends
+ // the same words to the agent twice.
+ const field = await openComposer();
+ fireEvent.change(field, { target: { value: 'press it?' } });
+ fireEvent.keyDown(field, { key: 'Enter' });
+
+ expect(captured.collapsedTo).toEqual([12]); // the end of the picked range
+ });
+
+ test('cancelling leaves the selection alone', async () => {
+ // Escape is not "done with this passage" — you may still want it.
+ const field = await openComposer();
+ fireEvent.change(field, { target: { value: 'press it?' } });
+ fireEvent.keyDown(field, { key: 'Escape' });
+
+ expect(captured.collapsedTo).toEqual([]);
+ });
+
+ test('an empty draft files nothing, from either button', async () => {
+ await openComposer();
+ fireEvent.click(screen.getByRole('button', { name: /add comment/i }));
+ fireEvent.click(screen.getByRole('button', { name: /send to ai/i }));
+
+ expect(captured.created).toEqual([]);
+ });
+
+ test('Escape closes without posting', async () => {
+ const field = await openComposer();
+ fireEvent.change(field, { target: { value: 'press it?' } });
+ fireEvent.keyDown(field, { key: 'Escape' });
+
+ expect(captured.created).toEqual([]);
+ expect(screen.queryByPlaceholderText('Add a comment')).toBeNull();
+ });
+
+ test('a click outside closes it', async () => {
+ const field = await openComposer();
+ fireEvent.change(field, { target: { value: 'press it?' } });
+ fireEvent.pointerDown(document.body);
+
+ expect(captured.created).toEqual([]);
+ expect(screen.queryByPlaceholderText('Add a comment')).toBeNull();
+ });
+
+ test('a click on the mention results does NOT close it', async () => {
+ const field = await openComposer();
+ fireEvent.change(field, { target: { value: '@' } });
+ // The `@`-results are portaled to `document.body`, so they are outside the
+ // card by DOM but not by intent — picking a file must not read as a click
+ // away.
+ const popup = document.createElement('div');
+ popup.dataset.suggestionPopup = 'composer-mention';
+ document.body.append(popup);
+ fireEvent.pointerDown(popup);
+
+ expect(screen.queryByPlaceholderText('Add a comment')).not.toBeNull();
+ popup.remove();
+ });
+});
diff --git a/packages/app/src/comments/comments-client.test.ts b/packages/app/src/comments/comments-client.test.ts
new file mode 100644
index 000000000..9d18eae5c
--- /dev/null
+++ b/packages/app/src/comments/comments-client.test.ts
@@ -0,0 +1,124 @@
+/**
+ * The client validates what the server sends.
+ *
+ * This file used to restate the thread shape by hand and cast responses to it,
+ * so a server-side field the client had not been taught about arrived as
+ * `undefined` and surfaced somewhere far away — a blank card, a crash in a
+ * renderer. It now parses against the shared schema, and these pin the two
+ * dispositions that choice implies.
+ */
+
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { completeDispatchBatch, createThread, listThreads, queueThread } from './comments-client';
+
+function respond(body: unknown): void {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => ({ ok: true, json: async () => body }) as unknown as Response),
+ );
+}
+
+const healthy = {
+ threadId: '11111111-1111-4111-8111-111111111111',
+ docName: 'notes/rollout',
+ target: { kind: 'body' },
+ anchor: { exact: 'minimal downtime', prefix: '', suffix: '', start: 0, end: 16 },
+ state: 'anchored',
+ queued: true,
+ latestComment: 'still accurate?',
+ createdBy: 'principal-abc',
+ createdAt: 1000,
+};
+
+afterEach(() => vi.unstubAllGlobals());
+
+describe('listThreads', () => {
+ test('drops a thread it cannot read and keeps the rest', async () => {
+ // Skipping rather than throwing mirrors the store on the server side, where
+ // an unreadable thread file is skipped instead of being fatal. One bad
+ // thread must not blank the panel for every healthy one.
+ respond({ threads: [healthy, { threadId: 'nope' }, { ...healthy, docName: 'notes/other' }] });
+
+ const threads = await listThreads();
+ expect(threads.map((t) => t.docName)).toEqual(['notes/rollout', 'notes/other']);
+ });
+
+ test('applies the schema defaults rather than leaving holes', async () => {
+ // `target` is absent here. The schema defaults it to `body`, which is why
+ // the store can read `meta.target` directly instead of re-deriving it.
+ const withoutTarget: Record<string, unknown> = { ...healthy };
+ delete withoutTarget.target;
+ respond({ threads: [withoutTarget] });
+
+ const [thread] = await listThreads();
+ expect(thread.target).toEqual({ kind: 'body' });
+ });
+
+ test('a property target keeps its path', async () => {
+ respond({
+ threads: [{ ...healthy, target: { kind: 'property', key: 'tags', path: [2] }, anchor: null }],
+ });
+
+ const [thread] = await listThreads();
+ expect(thread.target).toEqual({ kind: 'property', key: 'tags', path: [2] });
+ expect(thread.anchor).toBeNull();
+ });
+});
+
+describe('a single-thread response', () => {
+ test('rejects rather than handing back a malformed thread', async () => {
+ // The caller asked for one specific thread; an unparseable one means the
+ // result is unknown. Returning it anyway would move the failure far from
+ // its cause.
+ respond({ threadId: 'nope' });
+
+ await expect(createThread({ docName: 'notes/rollout', quote: 'x', body: 'y' })).rejects.toThrow(
+ /cannot read/,
+ );
+ });
+
+ test('returns the thread when it parses', async () => {
+ respond(healthy);
+
+ const meta = await createThread({ docName: 'notes/rollout', quote: 'x', body: 'y' });
+ expect(meta.threadId).toBe(healthy.threadId);
+ });
+});
+
+describe('envelope responses', () => {
+ test('a queue response with an unreadable thread is rejected', async () => {
+ // `queueThread` wraps the thread in `{ meta, orphaned }`. The wrapper used to
+ // be cast wholesale, so a malformed `meta` rode straight through.
+ respond({ meta: { threadId: 'nope' }, orphaned: false });
+
+ await expect(queueThread(healthy.threadId)).rejects.toThrow(/cannot read/);
+ });
+
+ test('a well-formed queue response comes back parsed', async () => {
+ respond({ meta: healthy, orphaned: true });
+
+ const result = await queueThread(healthy.threadId);
+ expect(result.orphaned).toBe(true);
+ expect(result.meta.docName).toBe('notes/rollout');
+ });
+
+ test('a batch keeps its per-item not-found entries', async () => {
+ // One stale id must be reported in place, not fail the batch — the ids were
+ // chosen earlier and one going missing cannot take the rest down.
+ respond({
+ results: [
+ { threadId: healthy.threadId, ok: true, meta: healthy },
+ { threadId: '22222222-2222-4222-8222-222222222222', ok: false, error: 'not-found' },
+ ],
+ });
+
+ const { results } = await completeDispatchBatch([healthy.threadId]);
+ expect(results.map((r) => r.ok)).toEqual([true, false]);
+ });
+
+ test('a batch carrying a malformed thread is rejected', async () => {
+ respond({ results: [{ threadId: healthy.threadId, ok: true, meta: { threadId: 'nope' } }] });
+
+ await expect(completeDispatchBatch([healthy.threadId])).rejects.toThrow(/cannot read/);
+ });
+});
diff --git a/packages/app/src/comments/comments-client.ts b/packages/app/src/comments/comments-client.ts
new file mode 100644
index 000000000..f1454b789
--- /dev/null
+++ b/packages/app/src/comments/comments-client.ts
@@ -0,0 +1,216 @@
+/**
+ * Typed fetch client for the comment routes (`/api/comments`, `/api/comment`).
+ *
+ * The app is the only client of this surface — agents reach comments through
+ * the dispatch payload, not an API. Every mutation is server-mediated so writes
+ * carry attribution; nothing here touches `.ok/` directly.
+ */
+
+/**
+ * Cover-sheet projection returned by the server — the SAME schema the server
+ * parses on disk, not a copy of it.
+ *
+ * This file used to restate the shape by hand, which meant every field added
+ * server-side had to be mirrored here or the two silently disagreed at runtime.
+ * That is how `target` and the nullable `anchor` both arrived: as a second edit
+ * nobody was reminded to make.
+ */
+import {
+ type CommentThreadMeta,
+ CommentThreadMetaSchema,
+ CompleteBatchSuccessSchema,
+ DeleteSuccessSchema,
+ type DispatchPayload,
+ PrepareBatchSuccessSchema,
+ ProblemDetailsSchema,
+ QueueSuccessSchema,
+} from '@inkeep/open-knowledge-core';
+
+/**
+ * Ingredients for handing a comment to an agent; the client composes the prompt.
+ * Shared from core — this was a second hand-written duplicate, and `property`
+ * had to be added to it and the server schema separately.
+ */
+export type { CommentThreadMeta, DispatchPayload };
+
+export type BatchResult<T> =
+ | ({ threadId: string; ok: true } & T)
+ | { threadId: string; ok: false; error: 'not-found' };
+
+async function request<T>(url: string, init?: RequestInit): Promise<T> {
+ const res = await fetch(url, {
+ ...init,
+ headers: { 'content-type': 'application/json', ...init?.headers },
+ });
+ const body = (await res.json().catch(() => null)) as unknown;
+ if (!res.ok) {
+ // Two-step RFC 9457 parse, the same shape every other fetching surface uses
+ // (see GraphPanel / OutlinePanel): validate the problem body, fall back to
+ // the status line when it is not one.
+ //
+ // `title` before `detail` is load-bearing here: `errorResponse` takes the
+ // human-readable reason as its `title` argument and leaves `detail`
+ // optional, so the comment API's messages — "The quoted passage is not in
+ // the document" — live in `title`. Reading `detail` first got `undefined`
+ // for every one of them and degraded each toast to a bare status code.
+ const problem = ProblemDetailsSchema.safeParse(body);
+ throw new Error(
+ problem.success
+ ? (problem.data.title ?? problem.data.detail)
+ : `comments request failed (${res.status})`,
+ );
+ }
+ return body as T;
+}
+
+function mutate<T>(body: unknown): Promise<T> {
+ return request<T>('/api/comment', { method: 'POST', body: JSON.stringify(body) });
+}
+
+/**
+ * Validate an envelope against its shared schema.
+ *
+ * Throws for the same reason {@link parseThread} does — the caller asked for a
+ * specific result, and handing back an unvalidated one moves the failure far
+ * from its cause. Only the LIST tolerates bad entries, because there the healthy
+ * ones are still worth showing.
+ */
+function parse<T>(
+ schema: { safeParse: (v: unknown) => { success: true; data: T } | { success: false } },
+ value: unknown,
+): T {
+ const parsed = schema.safeParse(value);
+ if (!parsed.success) {
+ throw new Error('The server returned a response this build cannot read.');
+ }
+ return parsed.data;
+}
+
+function parseThread(value: unknown): CommentThreadMeta {
+ const parsed = CommentThreadMetaSchema.safeParse(value);
+ if (!parsed.success) {
+ throw new Error('The server returned a comment thread this build cannot read.');
+ }
+ return parsed.data;
+}
+
+/**
+ * Validate a LIST, dropping the entries that fail.
+ *
+ * Skipping rather than throwing, because the store on the other side already
+ * works this way: an unreadable thread file is skipped, not migrated and not
+ * fatal. One malformed thread must not blank the panel for every healthy one —
+ * the same reasoning, applied one layer out.
+ */
+function parseThreads(values: readonly unknown[]): CommentThreadMeta[] {
+ const out: CommentThreadMeta[] = [];
+ for (const value of values) {
+ const parsed = CommentThreadMetaSchema.safeParse(value);
+ if (parsed.success) out.push(parsed.data);
+ else console.warn('[comments] skipped a thread this build cannot read', parsed.error.issues);
+ }
+ return out;
+}
+
+/** Threads for one doc, or project-wide when `docName` is omitted (the queue view). */
+export async function listThreads(docName?: string): Promise<CommentThreadMeta[]> {
+ const url =
+ docName === undefined ? '/api/comments' : `/api/comments?doc=${encodeURIComponent(docName)}`;
+ const { threads } = await request<{ threads: unknown[] }>(url);
+ return parseThreads(threads);
+}
+
+/**
+ * Create a thread. Identify the passage by `quote` (what the rich-text editor
+ * has — its ProseMirror positions are NOT body offsets) or by explicit body
+ * offsets when the caller genuinely has them.
+ */
+export function createThread(input: {
+ docName: string;
+ quote?: string;
+ /** Rendered text either side of the selection — which occurrence, when the quote repeats. */
+ prefix?: string;
+ suffix?: string;
+ start?: number;
+ end?: number;
+ /**
+ * Comment on a frontmatter key instead of a body passage. `quote` then refers
+ * to text inside that VALUE rather than the body; omit it for the whole thing.
+ */
+ propertyKey?: string;
+ /** Steps into the value: `[2]` for the third tag, `['name']` for a nested field. */
+ propertyPath?: (string | number)[];
+ body: string;
+ /** Post straight into the dispatch queue (queue-first compose). */
+ queue?: boolean;
+}): Promise<CommentThreadMeta> {
+ return request<unknown>('/api/comments', {
+ method: 'POST',
+ body: JSON.stringify(input),
+ }).then(parseThread);
+}
+
+/** Revise a thread's comment. Replaces the text — the previous one is not kept. */
+export function editComment(threadId: string, body: string): Promise<CommentThreadMeta> {
+ return mutate<unknown>({ action: 'edit', id: threadId, body }).then(parseThread);
+}
+
+export function resolveThread(threadId: string): Promise<CommentThreadMeta> {
+ return mutate<unknown>({ action: 'resolve', id: threadId }).then(parseThread);
+}
+
+export function reopenThread(threadId: string): Promise<CommentThreadMeta> {
+ return mutate<unknown>({ action: 'reopen', id: threadId }).then(parseThread);
+}
+
+/** Re-anchor an orphaned thread onto a fresh passage (by quote, or by offsets). */
+export function replaceAnchor(
+ threadId: string,
+ passage: { quote?: string; prefix?: string; suffix?: string; start?: number; end?: number },
+): Promise<CommentThreadMeta> {
+ return mutate<unknown>({ action: 'replace', id: threadId, ...passage }).then(parseThread);
+}
+
+export function queueThread(
+ threadId: string,
+): Promise<{ meta: CommentThreadMeta; orphaned: boolean }> {
+ return mutate<unknown>({ action: 'queue', id: threadId }).then((body) =>
+ parse(QueueSuccessSchema, body),
+ );
+}
+
+export function unqueueThread(threadId: string): Promise<CommentThreadMeta> {
+ return mutate<unknown>({ action: 'unqueue', id: threadId }).then(parseThread);
+}
+
+/**
+ * Delete a thread outright — destructive and irreversible. Distinct from
+ * `unqueueThread` (drop from the batch, keep the comment) and `resolveThread`
+ * (close it, keep the history).
+ */
+export function deleteThread(threadId: string): Promise<{ threadId: string }> {
+ return request<unknown>(`/api/comment?id=${encodeURIComponent(threadId)}`, {
+ method: 'DELETE',
+ }).then((body) => parse(DeleteSuccessSchema, body));
+}
+
+/**
+ * Batch dispatch. `ids` is the reviewer's checked selection in intended
+ * run order; results come back in the same order, per item — one id that no
+ * longer exists is reported rather than failing the batch.
+ */
+export function prepareDispatchBatch(
+ ids: readonly string[],
+): Promise<{ results: BatchResult<{ meta: CommentThreadMeta; payload: DispatchPayload }>[] }> {
+ return mutate<unknown>({ action: 'dispatch-prepare-batch', ids }).then((body) =>
+ parse(PrepareBatchSuccessSchema, body),
+ );
+}
+
+export function completeDispatchBatch(
+ ids: readonly string[],
+): Promise<{ results: BatchResult<{ meta: CommentThreadMeta }>[] }> {
+ return mutate<unknown>({ action: 'dispatch-complete-batch', ids }).then((body) =>
+ parse(CompleteBatchSuccessSchema, body),
+ );
+}
diff --git a/packages/app/src/comments/dispatch-batch.test.ts b/packages/app/src/comments/dispatch-batch.test.ts
new file mode 100644
index 000000000..80fd4d837
--- /dev/null
+++ b/packages/app/src/comments/dispatch-batch.test.ts
@@ -0,0 +1,422 @@
+/**
+ * Batch dispatch carries EVERY selected comment.
+ *
+ * Pins the "only one comment got sent" class of bug: the batch must reach the
+ * composer with all queued items, and the composed instruction must name each
+ * one. A regression here is invisible to typecheck — the call succeeds, it just
+ * carries less than it should.
+ */
+
+import { describe, expect, test, vi } from 'vitest';
+import { composeCommentBatchInstruction } from './comment-chips';
+
+vi.mock('./comments-client', () => {
+ // Everything the factory needs must be defined INSIDE it — `vi.mock` is
+ // hoisted above module-level declarations.
+ //
+ // `createdAt` ascends with the thread number, so t1 was written first. The
+ // batch must ship in that order; the panel lists threads newest-first, and
+ // inheriting that sort once numbered the composed prompt backwards.
+ const metas = [
+ {
+ threadId: 't1',
+ docName: 'recipes/one',
+ anchor: { exact: 'Heat oven to 425F', prefix: '', suffix: '', start: 0, end: 17 },
+ state: 'anchored',
+ queued: true,
+ latestComment: 'note on t1',
+ createdBy: 'principal-abc',
+ createdAt: 800,
+ },
+ {
+ threadId: 't2',
+ docName: 'recipes/two',
+ anchor: { exact: 'Whisk the peanut sauce', prefix: '', suffix: '', start: 0, end: 22 },
+ state: 'anchored',
+ queued: true,
+ latestComment: 'note on t2',
+ createdBy: 'principal-abc',
+ createdAt: 900,
+ },
+ {
+ threadId: 't3',
+ docName: 'recipes/three',
+ anchor: { exact: 'cooked brown rice', prefix: '', suffix: '', start: 0, end: 17 },
+ state: 'anchored',
+ queued: true,
+ latestComment: 'note on t3',
+ createdBy: 'principal-abc',
+ createdAt: 1000,
+ },
+ ];
+ return {
+ __metas: metas,
+ listThreads: vi.fn(async () => metas),
+ createThread: vi.fn(),
+ reply: vi.fn(),
+ resolveThread: vi.fn(),
+ reopenThread: vi.fn(),
+ replaceAnchor: vi.fn(),
+ queueThread: vi.fn(),
+ unqueueThread: vi.fn(),
+ deleteThread: vi.fn(),
+ prepareDispatchBatch: vi.fn(async (ids: readonly string[]) => ({
+ results: ids.map((id) => {
+ const m = metas.find((entry) => entry.threadId === id);
+ if (!m) return { threadId: id, ok: false, error: 'not-found' };
+ return {
+ threadId: id,
+ ok: true,
+ meta: m,
+ payload: {
+ docName: m.docName,
+ instruction: `note on ${id}`,
+ passage: { exact: m.anchor.exact, prefix: '', suffix: '' },
+ anchorLost: false,
+ },
+ };
+ }),
+ })),
+ completeDispatchBatch: vi.fn(async (ids: readonly string[]) => ({
+ results: ids.map((id) => ({ threadId: id, ok: true, meta: metas[0] })),
+ })),
+ };
+});
+
+/** The batch send, with everything but the hand-off left at its default. */
+function dispatchWith(
+ store: typeof import('./store'),
+ compose: (items: readonly { threadId: string; payload: unknown }[]) => Promise<boolean>,
+): Promise<string[]> {
+ // biome-ignore lint/suspicious/noExplicitAny: structural payload in a test double
+ return store.dispatchComments({ compose: compose as any });
+}
+
+describe('dispatchComments', () => {
+ test('hands the composer every selected comment, not just the first', async () => {
+ vi.resetModules();
+ const store = await import('./store');
+ await store.refresh();
+
+ // Guards the guard: all three must actually be queued, or the assertions
+ // below would pass against a broken batch.
+ expect(store.getSelectedQueue()).toHaveLength(3);
+
+ const seen: number[] = [];
+ const shipped = await dispatchWith(store, async (items) => {
+ seen.push(items.length);
+ return true;
+ });
+
+ expect(seen).toEqual([3]); // ONE compose call carrying all three
+ expect(shipped).toHaveLength(3);
+ // and all three are marked complete, not just the first
+ const api = await import('./comments-client');
+ expect(api.completeDispatchBatch).toHaveBeenCalledWith(['t1', 't2', 't3']);
+ });
+
+ test('the batch ships in the order the comments were written', async () => {
+ // Regression: the queue inherited `allThreads`' newest-first sort, so a
+ // reviewer who wrote three comments in order got them numbered 3, 2, 1 in
+ // the composed prompt. Run order and display order are different concerns.
+ vi.resetModules();
+ const store = await import('./store');
+ await store.refresh();
+
+ // t1 is the oldest comment (see the fixture) and must lead.
+ expect(store.getQueue()).toEqual(['t1', 't2', 't3']);
+
+ const order: string[] = [];
+ await dispatchWith(store, async (items) => {
+ order.push(...items.map((item) => item.payload.docName));
+ return true;
+ });
+ expect(order).toEqual(['recipes/one', 'recipes/two', 'recipes/three']);
+ });
+
+ test('a deselected comment is excluded but the rest still ship', async () => {
+ vi.resetModules();
+ const store = await import('./store');
+ await store.refresh();
+ store.toggleQueueSelection('t2');
+
+ const shipped = await dispatchWith(store, async () => true);
+ expect(shipped).toEqual(['t1', 't3']);
+ });
+
+ test('a second send while one is in flight is dropped, not duplicated', async () => {
+ // Regression: nothing drains the queue until `completeDispatchBatch` lands,
+ // so a second Enter during the server's anchor re-find read the same ids and
+ // handed the identical batch to a second agent turn. Neither the composer
+ // nor the panel disables its send across that window.
+ vi.resetModules();
+ const store = await import('./store');
+ await store.refresh();
+
+ let release = (): void => {};
+ const held = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const composed: number[] = [];
+
+ const first = dispatchWith(store, async (items) => {
+ composed.push(items.length);
+ await held;
+ return true;
+ });
+ // Same tick as a double-tap on Enter, while `first` sits in its compose.
+ await vi.waitFor(() => expect(composed).toHaveLength(1));
+ const second = await dispatchWith(store, async (items) => {
+ composed.push(items.length);
+ return true;
+ });
+
+ expect(second).toEqual([]); // shipped nothing
+ release();
+ expect(await first).toEqual(['t1', 't2', 't3']);
+ expect(composed).toEqual([3]); // ONE compose, not two
+ });
+
+ test('a send is possible again once the in-flight one finishes', async () => {
+ // The guard must clear on the way out — a flag that leaks would wedge the
+ // queue for the rest of the session.
+ vi.resetModules();
+ const store = await import('./store');
+ await store.refresh();
+
+ expect(await dispatchWith(store, async () => false)).toEqual([]);
+ expect(await dispatchWith(store, async () => true)).toEqual(['t1', 't2', 't3']);
+ });
+
+ test('the Queue panel Send delivers ONE turn carrying every comment', async () => {
+ // Regression: this path used to loop and hand off one comment at a time,
+ // which fragmented a review into N agent threads (and surfaced as "only one
+ // got sent"). It must call the hand-off exactly once, with all three items.
+ vi.resetModules();
+ const store = await import('./store');
+ await store.refresh();
+
+ const calls: number[] = [];
+ await dispatchWith(store, async (items) => {
+ calls.push(items.length);
+ return true;
+ });
+
+ expect(calls).toEqual([3]);
+ const api = await import('./comments-client');
+ expect(api.completeDispatchBatch).toHaveBeenCalledWith(['t1', 't2', 't3']);
+ });
+
+ test('a hand-off that only stages can decline to resolve', async () => {
+ // Appending to a live session leaves the text UNSENT in its input, so the
+ // threads stay queued — the human still has to press enter. Same dispatch
+ // path, one flag apart.
+ vi.resetModules();
+ const store = await import('./store');
+ await store.refresh();
+ // `resetModules` re-imports the store but the client mock is the same
+ // object, so its call log still holds the earlier tests' sends.
+ vi.clearAllMocks();
+
+ const shipped = await store.dispatchComments({
+ compose: async () => true,
+ resolve: false,
+ });
+
+ expect(shipped).toEqual(['t1', 't2', 't3']);
+ const api = await import('./comments-client');
+ expect(api.completeDispatchBatch).not.toHaveBeenCalled();
+ });
+
+ test('deselecting drops the selected count the chip shows', async () => {
+ // The chip counts what a send would CARRY. If it counted the whole queue,
+ // unchecking an item would leave the number unchanged and the control would
+ // give no feedback.
+ vi.resetModules();
+ const store = await import('./store');
+ await store.refresh();
+ expect(store.getSelectedQueue()).toHaveLength(3);
+
+ store.toggleQueueSelection('t2');
+ expect(store.getSelectedQueue()).toHaveLength(2);
+ // still queued — deselecting excludes it from this send, it doesn't remove it
+ expect(store.getQueue()).toHaveLength(3);
+
+ store.toggleQueueSelection('t2');
+ expect(store.getSelectedQueue()).toHaveLength(3);
+ });
+
+ test('a failed hand-off ships nothing and leaves everything queued', async () => {
+ vi.resetModules();
+ const store = await import('./store');
+ await store.refresh();
+
+ const shipped = await dispatchWith(store, async () => false);
+ expect(shipped).toEqual([]);
+ });
+});
+
+describe('composeCommentBatchInstruction', () => {
+ test('names every comment with its own document and passage', () => {
+ const prompt = composeCommentBatchInstruction(
+ [
+ { docName: 'recipes/one', body: 'how hot?', quote: 'Heat oven to 425F', anchorLost: false },
+ { docName: 'recipes/two', body: 'parmesan?', quote: 'Whisk the sauce', anchorLost: false },
+ { docName: 'recipes/three', body: 'swap rice?', quote: 'brown rice', anchorLost: false },
+ ],
+ 'Work through these',
+ );
+
+ expect(prompt).toContain('Work through these');
+ expect(prompt).toContain('The 3 comments:');
+ for (const fragment of [
+ 'recipes/one',
+ 'how hot?',
+ 'Heat oven to 425F',
+ 'recipes/two',
+ 'parmesan?',
+ 'recipes/three',
+ 'swap rice?',
+ 'brown rice',
+ ]) {
+ expect(prompt).toContain(fragment);
+ }
+ });
+});
+
+describe('composeCommentBatchInstruction — the pinned passage', () => {
+ const items = [
+ { docName: 'recipes/one', body: 'how hot?', quote: 'Heat oven to 425F', anchorLost: false },
+ ];
+
+ test('carries a selection that belongs to no comment', () => {
+ // The bug: the composer rendered the selection pill above the send and the
+ // batch payload then dropped it, so a passage you deliberately highlighted
+ // reached the agent nowhere.
+ const prompt = composeCommentBatchInstruction(items, 'Work through these', {
+ docName: 'recipes/one',
+ markdown: '- 2 tbsp neutral oil',
+ });
+
+ expect(prompt).toContain('2 tbsp neutral oil');
+ // Labelled apart from the numbered comments — otherwise it reads as a
+ // review item whose request went missing.
+ expect(prompt).toContain('not a comment');
+ expect(prompt.indexOf('The comment:')).toBeLessThan(prompt.indexOf('2 tbsp neutral oil'));
+ });
+
+ test('adds nothing when no passage is pinned', () => {
+ const prompt = composeCommentBatchInstruction(items, 'Work through these');
+ expect(prompt).not.toContain('not a comment');
+ });
+
+ test('an empty pinned passage is not announced', () => {
+ const prompt = composeCommentBatchInstruction(items, '', {
+ docName: 'recipes/one',
+ markdown: ' \n ',
+ });
+ expect(prompt).not.toContain('not a comment');
+ });
+});
+
+describe('composeCommentBatchInstruction — a quote that repeats', () => {
+ const base = {
+ docName: 'recipes/one',
+ body: 'tighten this',
+ quote: 'needs space',
+ anchorLost: false,
+ prefix: '…1 tsp honey or maple, ',
+ suffix: ' around the header. Outro.',
+ };
+
+ test('says which occurrence is meant', () => {
+ // Offsets would look precise and be wrong: they shift the moment the agent
+ // makes its first edit in the batch. Surrounding text re-locates itself.
+ const prompt = composeCommentBatchInstruction([{ ...base, repeats: true }], '');
+ expect(prompt).toContain('appears more than once');
+ expect(prompt).toContain('1 tsp honey or maple');
+ expect(prompt).toContain('around the header');
+ expect(prompt).toContain('rather than the first occurrence');
+ });
+
+ test('stays terse when the quote is unique', () => {
+ const prompt = composeCommentBatchInstruction([{ ...base, repeats: false }], '');
+ expect(prompt).not.toContain('appears more than once');
+ expect(prompt).toContain('needs space');
+ });
+
+ test('a passage at the start of the file is described by what follows it', () => {
+ const prompt = composeCommentBatchInstruction([{ ...base, repeats: true, prefix: '' }], '');
+ expect(prompt).toContain('at the start of the file');
+ });
+
+ test('a passage at the end of the file is described by what precedes it', () => {
+ const prompt = composeCommentBatchInstruction([{ ...base, repeats: true, suffix: '' }], '');
+ expect(prompt).toContain('at the end of the file');
+ });
+
+ test('long context is trimmed rather than dumped whole', () => {
+ const prompt = composeCommentBatchInstruction(
+ [{ ...base, repeats: true, prefix: 'x'.repeat(400), suffix: 'y'.repeat(400) }],
+ '',
+ );
+ expect(prompt).not.toContain('x'.repeat(200));
+ expect(prompt).toContain('…');
+ });
+
+ test('no context at all falls back to no note rather than an empty one', () => {
+ const prompt = composeCommentBatchInstruction(
+ [{ ...base, repeats: true, prefix: '', suffix: '' }],
+ '',
+ );
+ expect(prompt).not.toContain('appears more than once');
+ });
+});
+
+describe('the composed instruction for a property comment', () => {
+ const propertyItem = {
+ docName: 'recipes/one',
+ body: 'this should be the publish date, not the created date',
+ propertyKey: 'date',
+ quote: '',
+ anchorLost: false,
+ prefix: '',
+ suffix: '',
+ repeats: false,
+ };
+
+ test('names the key instead of quoting a passage', () => {
+ const out = composeCommentBatchInstruction([propertyItem], '');
+ expect(out).toContain('on the `date` property (frontmatter)');
+ expect(out).toContain('this should be the publish date');
+ // No blockquote: there is no passage, and an empty one would read as a
+ // comment on a blank line.
+ expect(out).not.toContain('>');
+ });
+
+ test('a removed key is called out as lost, naming the key', () => {
+ const out = composeCommentBatchInstruction([{ ...propertyItem, anchorLost: true }], '');
+ expect(out).toContain('`date` is no longer in this document');
+ // The passage wording would be wrong here — nothing was edited or removed
+ // from the prose.
+ expect(out).not.toContain('this passage is no longer in the document');
+ });
+
+ test('property and passage comments compose into one numbered batch', () => {
+ const passageItem = {
+ docName: 'recipes/two',
+ body: 'stale example',
+ propertyKey: null,
+ quote: 'Whisk the peanut sauce',
+ anchorLost: false,
+ prefix: '',
+ suffix: '',
+ repeats: false,
+ };
+ const out = composeCommentBatchInstruction([propertyItem, passageItem], 'Fix these');
+ expect(out).toContain('The 2 comments:');
+ expect(out).toContain('1. In `recipes/one`, on the `date` property');
+ expect(out).toContain('2. In `recipes/two`, on this passage:');
+ expect(out).toContain(' > Whisk the peanut sauce');
+ });
+});
diff --git a/packages/app/src/comments/margin-rail-layout.test.ts b/packages/app/src/comments/margin-rail-layout.test.ts
new file mode 100644
index 000000000..7efba4669
--- /dev/null
+++ b/packages/app/src/comments/margin-rail-layout.test.ts
@@ -0,0 +1,80 @@
+/**
+ * Where a comment marker lands on the rail.
+ *
+ * The bug this replaces: markers were positioned by document FRACTION
+ * (`range.from / doc.size`) against the scroll container's box. That container
+ * also holds the cover and the frontmatter table, which ProseMirror knows
+ * nothing about — so on a doc with a tall properties block every marker floated
+ * hundreds of pixels above the text it pointed at. Positions now come from the
+ * text's own viewport coords; these cover what the layout does with them.
+ */
+
+import { describe, expect, test } from 'vitest';
+import { layoutMarkers } from './CommentMarginRail';
+
+const RAIL_TOP = 100;
+const RAIL_HEIGHT = 600; // visible band: 100 → 700
+const ICON_H = 30;
+
+describe('layoutMarkers', () => {
+ test('centers a marker on the line it belongs to', () => {
+ const [marker] = layoutMarkers([{ id: 'a', y: 400 }], RAIL_TOP, RAIL_HEIGHT);
+ // Centered, not hanging below the baseline.
+ expect(marker.top).toBe(400 - ICON_H / 2);
+ expect(marker.offscreen).toBe(false);
+ });
+
+ test('stacks markers that would overlap instead of piling them on one point', () => {
+ const out = layoutMarkers(
+ [
+ { id: 'a', y: 400 },
+ { id: 'b', y: 405 },
+ { id: 'c', y: 410 },
+ ],
+ RAIL_TOP,
+ RAIL_HEIGHT,
+ );
+ for (let i = 1; i < out.length; i += 1) {
+ expect(out[i].top).toBeGreaterThanOrEqual(out[i - 1].top + ICON_H);
+ }
+ // The first still sits where its line is; only the crowded ones move.
+ expect(out[0].top).toBe(400 - ICON_H / 2);
+ });
+
+ test('orders by position on screen, not by input order', () => {
+ const out = layoutMarkers(
+ [
+ { id: 'low', y: 600 },
+ { id: 'high', y: 200 },
+ ],
+ RAIL_TOP,
+ RAIL_HEIGHT,
+ );
+ expect(out.map((m) => m.id)).toEqual(['high', 'low']);
+ });
+
+ test('clamps a line scrolled above the viewport to the top edge, flagged', () => {
+ const [marker] = layoutMarkers([{ id: 'a', y: -250 }], RAIL_TOP, RAIL_HEIGHT);
+ expect(marker.top).toBe(RAIL_TOP);
+ // Flagged so the UI can dim it — parked at the edge, not pointing at a line.
+ expect(marker.offscreen).toBe(true);
+ });
+
+ test('clamps a line scrolled below the viewport to the bottom edge, flagged', () => {
+ const [marker] = layoutMarkers([{ id: 'a', y: 5000 }], RAIL_TOP, RAIL_HEIGHT);
+ expect(marker.top).toBe(RAIL_TOP + RAIL_HEIGHT - ICON_H);
+ expect(marker.offscreen).toBe(true);
+ });
+
+ test('never places a marker outside the rail, however crowded', () => {
+ const crowded = Array.from({ length: 40 }, (_, i) => ({ id: `t${i}`, y: 690 }));
+ for (const marker of layoutMarkers(crowded, RAIL_TOP, RAIL_HEIGHT)) {
+ expect(marker.top).toBeGreaterThanOrEqual(RAIL_TOP);
+ expect(marker.top).toBeLessThanOrEqual(RAIL_TOP + RAIL_HEIGHT - ICON_H);
+ }
+ });
+
+ test('no markers, no positions', () => {
+ expect(layoutMarkers([], RAIL_TOP, RAIL_HEIGHT)).toEqual([]);
+ });
+});
diff --git a/packages/app/src/comments/popover-bus.test.ts b/packages/app/src/comments/popover-bus.test.ts
new file mode 100644
index 000000000..6768bc2dd
--- /dev/null
+++ b/packages/app/src/comments/popover-bus.test.ts
@@ -0,0 +1,64 @@
+/**
+ * The open-popover signal is shared state, not a one-way "open" command.
+ *
+ * Two bugs came from it being one-way. The popover closed itself privately on
+ * Escape / outside click / resolve, so the margin rail kept a marker lit for a
+ * popover that no longer existed — and, not knowing what was open, the rail
+ * could not make a marker toggle. Both need `null` to travel the same channel
+ * as an id, which is what these pin.
+ */
+
+import { describe, expect, test } from 'vitest';
+import { emitOpenThreadPopover, subscribeOpenThreadPopover } from './store';
+
+/** Collect everything the bus publishes for the life of one subscription. */
+function record(): { seen: (string | null)[]; stop: () => void } {
+ const seen: (string | null)[] = [];
+ const stop = subscribeOpenThreadPopover((id) => seen.push(id));
+ return { seen, stop };
+}
+
+describe('the thread-popover bus', () => {
+ test('carries an id when a thread opens', () => {
+ const bus = record();
+ emitOpenThreadPopover('t1');
+ expect(bus.seen).toEqual(['t1']);
+ bus.stop();
+ });
+
+ test('carries null when it closes, so mirrors can clear', () => {
+ // The rail's lit marker depends on hearing this; before, a close was silent.
+ const bus = record();
+ emitOpenThreadPopover('t1');
+ emitOpenThreadPopover(null);
+ expect(bus.seen).toEqual(['t1', null]);
+ bus.stop();
+ });
+
+ test('switching threads reports the new id, not a close first', () => {
+ const bus = record();
+ emitOpenThreadPopover('t1');
+ emitOpenThreadPopover('t2');
+ expect(bus.seen).toEqual(['t1', 't2']);
+ bus.stop();
+ });
+
+ test('an unsubscribed listener stops hearing', () => {
+ const bus = record();
+ emitOpenThreadPopover('t1');
+ bus.stop();
+ emitOpenThreadPopover('t2');
+ expect(bus.seen).toEqual(['t1']);
+ });
+
+ test('every listener sees the same signal', () => {
+ // The popover and the rail both subscribe; they must not diverge.
+ const a = record();
+ const b = record();
+ emitOpenThreadPopover('t1');
+ emitOpenThreadPopover(null);
+ expect(a.seen).toEqual(b.seen);
+ a.stop();
+ b.stop();
+ });
+});
diff --git a/packages/app/src/comments/property-row-rect.dom.test.tsx b/packages/app/src/comments/property-row-rect.dom.test.tsx
new file mode 100644
index 000000000..8b0ea8c88
--- /dev/null
+++ b/packages/app/src/comments/property-row-rect.dom.test.tsx
@@ -0,0 +1,73 @@
+/**
+ * Placing a comment that has no ProseMirror position.
+ *
+ * A property thread is the one comment the editor cannot locate for us, so the
+ * rail and the popover resolve it through the DOM instead. These pin the two
+ * cases that decide whether a marker appears at all: a row that is on screen,
+ * and a row that is not rendered (collapsed disclosure, deleted key), where the
+ * answer has to be "no position" rather than a fallback.
+ *
+ * Mounted rather than hand-built from `document.createElement`: the helper's
+ * whole job is to find rows the property panel rendered, so the fixture carries
+ * the same `data-testid` / `data-key` pair `FrontmatterRow` emits.
+ */
+
+import { cleanup, render } from '@testing-library/react';
+import { afterEach, describe, expect, test } from 'vitest';
+import { findPropertyRow, propertyRowRect } from './property-row-rect';
+
+function Rows({ keys }: { keys: readonly string[] }) {
+ return (
+ <>
+ {keys.map((key) => (
+ <div key={key} data-testid="property-row" data-key={key} />
+ ))}
+ </>
+ );
+}
+
+/**
+ * jsdom lays nothing out, so every rect is zero — which this helper reads as
+ * "not on screen". Stub the row under test so the positive cases exercise the
+ * real branch rather than the absent one.
+ */
+function stubRect(key: string, rect: Partial<DOMRect> = {}): void {
+ const el = findPropertyRow(key);
+ if (el === null) throw new Error(`no row rendered for ${key}`);
+ el.getBoundingClientRect = () =>
+ ({ top: 100, height: 24, width: 300, ...rect }) as unknown as DOMRect;
+}
+
+afterEach(() => cleanup());
+
+describe('locating a property row', () => {
+ test('finds the row for its key', () => {
+ render(<Rows keys={['title', 'tags']} />);
+ stubRect('tags');
+ expect(findPropertyRow('tags')).not.toBeNull();
+ expect(propertyRowRect('tags')?.top).toBe(100);
+ });
+
+ test('a key with no row has no position', () => {
+ render(<Rows keys={['tags']} />);
+ // The disclosure is collapsed, or the key was removed. Callers skip — a
+ // marker pinned to an arbitrary y is worse than an absent one.
+ expect(propertyRowRect('date')).toBeNull();
+ });
+
+ test('a zero-size row counts as absent', () => {
+ render(<Rows keys={['tags']} />);
+ stubRect('tags', { top: 0, height: 0, width: 0 });
+ expect(propertyRowRect('tags')).toBeNull();
+ });
+
+ test('does not match a row belonging to a different key', () => {
+ render(<Rows keys={['tags']} />);
+ expect(findPropertyRow('tag')).toBeNull();
+ });
+
+ test('an empty key never matches', () => {
+ render(<Rows keys={['tags']} />);
+ expect(findPropertyRow('')).toBeNull();
+ });
+});
diff --git a/packages/app/src/comments/property-row-rect.ts b/packages/app/src/comments/property-row-rect.ts
new file mode 100644
index 000000000..5d5fe3517
--- /dev/null
+++ b/packages/app/src/comments/property-row-rect.ts
@@ -0,0 +1,142 @@
+/**
+ * Where a frontmatter row is on screen.
+ *
+ * A property comment has no ProseMirror position, which is why the rail and the
+ * popover cannot ask the editor to place it. They can ask the DOM: the
+ * properties table sits in the SAME scroll container as the editor body (the
+ * container also holds the cover), so a row's viewport rect is directly
+ * comparable to the `coordsAtPos` rects the body threads produce, and the two
+ * kinds of marker can share one layout pass.
+ *
+ * Returns null when the row is not rendered — the properties disclosure is
+ * collapsed, or the key was removed. Callers skip rather than guess a position;
+ * a marker pinned to an arbitrary y is worse than an absent one.
+ */
+
+import { COMMENT_ACTIVE_FILL, COMMENT_HUE } from './anchor-layers';
+
+/**
+ * Marks the field whose selection is standing in for a comment highlight, so
+ * `globals.css` can paint it amber instead of the browser's blue. Cleared on
+ * blur — once the reveal is over the field's ordinary selection must look
+ * ordinary again.
+ */
+const REVEAL_ATTR = 'data-comment-reveal';
+
+/** jsdom's preload lacks `CSS.escape`; keys are author-controlled, so escaping is required. */
+function escapeAttr(value: string): string {
+ return typeof CSS !== 'undefined' && CSS.escape ? CSS.escape(value) : value;
+}
+
+export function findPropertyRow(key: string): HTMLElement | null {
+ if (key === '') return null;
+ return document.querySelector<HTMLElement>(
+ `[data-testid="property-row"][data-key="${escapeAttr(key)}"]`,
+ );
+}
+
+export function propertyRowRect(key: string): DOMRect | null {
+ const row = findPropertyRow(key);
+ if (row === null) return null;
+ const rect = row.getBoundingClientRect();
+ // A collapsed disclosure can leave the node mounted at zero height. That is
+ // not a place to point at, so treat it as absent.
+ return rect.height === 0 && rect.width === 0 ? null : rect;
+}
+
+/** Bring a property row into view — the property twin of scrolling to a passage. */
+export function scrollPropertyRowIntoView(key: string): void {
+ findPropertyRow(key)?.scrollIntoView({ block: 'center', behavior: 'smooth' });
+}
+
+/**
+ * Show which words a value comment is on, by SELECTING them in the field.
+ *
+ * A body passage gets a persistent highlight because the document renders as
+ * styled spans. A property value is a `<textarea>`, whose text no CSS can reach
+ * — so the only highlight available is the browser's own selection, and this
+ * paints it. Transient by nature: it clears when focus moves, which makes it a
+ * reveal rather than a highlight, and is why the thread card and the rail marker
+ * both call it on click rather than the panel drawing it at rest.
+ *
+ * Returns whether it found something to select, so callers can fall back to
+ * merely scrolling the row.
+ */
+export function revealPropertyValueRange(args: {
+ /** Top-level frontmatter key. */
+ key: string;
+ /** Steps into the value; its last step names the row that renders the field. */
+ path: readonly (string | number)[];
+ quote: string;
+ /** Server-maintained offsets into the VALUE. A hint — verified before use. */
+ start?: number;
+ end?: number;
+}): boolean {
+ if (args.quote === '') return false;
+ // Nested rows are keyed by their own child key, not the full path, so two
+ // objects can each have a `name` row. Prefer rows matching the last step, then
+ // fall back to every row — and let the value itself settle which one it is.
+ const lastStep = args.path.length === 0 ? args.key : args.path[args.path.length - 1];
+ const preferred = Array.from(
+ document.querySelectorAll<HTMLElement>(
+ `[data-testid="property-row"][data-key="${escapeAttr(String(lastStep))}"]`,
+ ),
+ );
+ const all = Array.from(document.querySelectorAll<HTMLElement>('[data-testid="property-row"]'));
+ for (const row of [...preferred, ...all]) {
+ const control = row.querySelector<HTMLTextAreaElement | HTMLInputElement>('textarea, input');
+ if (control === null) continue;
+ const range = locateInValue(control.value, args.quote, args.start, args.end);
+ if (range === null) continue;
+ row.scrollIntoView({ block: 'center', behavior: 'smooth' });
+ control.focus();
+ control.setSelectionRange(range.start, range.end);
+ paintRevealSelection(control);
+ return true;
+ }
+ return false;
+}
+
+/**
+ * The stored offsets first, verified against the words; a search only if they no
+ * longer hold. Same order the server's re-find uses, and for the same reason —
+ * the position is a hint that is usually right and never trusted on its own.
+ */
+function locateInValue(
+ value: string,
+ quote: string,
+ start?: number,
+ end?: number,
+): { start: number; end: number } | null {
+ if (start !== undefined && end !== undefined && value.slice(start, end) === quote) {
+ return { start, end };
+ }
+ const index = value.indexOf(quote);
+ return index < 0 ? null : { start: index, end: index + quote.length };
+}
+
+/**
+ * Colour this one selection like a comment highlight, and only while it stands
+ * for one.
+ *
+ * `::selection` cannot be set inline, so the rule lives in `globals.css` and
+ * reads a custom property the element carries — which is what keeps the colour
+ * defined once, beside the decoration hue it matches.
+ *
+ * Scoped to the reveal because the attribute would otherwise repaint every
+ * ordinary selection in that field: someone highlighting text to retype it
+ * would see comment-amber and reasonably think they had hit a comment.
+ */
+function paintRevealSelection(control: HTMLTextAreaElement | HTMLInputElement): void {
+ control.style.setProperty('--comment-reveal-fill', `rgba(${COMMENT_HUE},${COMMENT_ACTIVE_FILL})`);
+ control.setAttribute(REVEAL_ATTR, 'true');
+ const clear = () => {
+ control.removeAttribute(REVEAL_ATTR);
+ control.style.removeProperty('--comment-reveal-fill');
+ };
+ // Blur ends the reveal; so does any fresh selection the user makes themselves,
+ // which is no longer the comment's range even when it overlaps it.
+ control.addEventListener('blur', clear, { once: true });
+ control.addEventListener('pointerdown', clear, { once: true });
+ control.addEventListener('keydown', clear, { once: true });
+}
diff --git a/packages/app/src/comments/property-value-selection.ts b/packages/app/src/comments/property-value-selection.ts
new file mode 100644
index 000000000..ee544f6e3
--- /dev/null
+++ b/packages/app/src/comments/property-value-selection.ts
@@ -0,0 +1,48 @@
+/**
+ * The text a reviewer has highlighted inside a property's value.
+ *
+ * A property comment can be about the whole field or about one passage in it —
+ * a `description` that runs several sentences deserves the same sentence-level
+ * note a paragraph in the body gets. This reads that highlight from the value's
+ * own form control.
+ *
+ * Read from `selectionStart` / `selectionEnd` rather than `window.getSelection`
+ * because the value widgets are `<textarea>` / `<input>`, whose internal
+ * selection the document Selection API does not report.
+ *
+ * Captured on POINTER-DOWN, before the click lands. Clicking the comment button
+ * blurs the field, and while browsers keep the offsets after blur, the field is
+ * no longer `document.activeElement` — so reading later cannot tell "the user
+ * highlighted this" from "some other control has focus".
+ */
+
+const TEXT_CONTROL = /^(TEXTAREA|INPUT)$/;
+
+/** The value control a comment button belongs to — same property row, if any. */
+function textControlInRow(trigger: HTMLElement): HTMLTextAreaElement | HTMLInputElement | null {
+ const active = document.activeElement;
+ if (!(active instanceof HTMLElement) || !TEXT_CONTROL.test(active.tagName)) return null;
+ const row = trigger.closest('[data-testid="property-row"]');
+ // Scoped to the row that owns the button: a highlight left in a DIFFERENT
+ // property's field would otherwise be quoted onto this one, which is the
+ // wrong-target failure the whole anchoring design exists to avoid.
+ if (row === null || !row.contains(active)) return null;
+ return active as HTMLTextAreaElement | HTMLInputElement;
+}
+
+/**
+ * The highlighted text inside this row's value, or null when nothing is
+ * highlighted — in which case the comment is about the property as a whole.
+ */
+export function capturePropertyValueSelection(trigger: HTMLElement): string | null {
+ const control = textControlInRow(trigger);
+ if (control === null) return null;
+ const { selectionStart, selectionEnd } = control;
+ if (selectionStart === null || selectionEnd === null || selectionStart === selectionEnd) {
+ return null;
+ }
+ const quote = control.value.slice(selectionStart, selectionEnd).trim();
+ // Whitespace-only is not a passage. Treating it as one would send an anchor
+ // that matches everywhere in the value.
+ return quote === '' ? null : quote;
+}
diff --git a/packages/app/src/comments/queue-attachment.test.ts b/packages/app/src/comments/queue-attachment.test.ts
new file mode 100644
index 000000000..4b5f77143
--- /dev/null
+++ b/packages/app/src/comments/queue-attachment.test.ts
@@ -0,0 +1,127 @@
+/**
+ * Capturing the queue for a composer that attaches it.
+ *
+ * The batch is captured when the `+` menu's Queue toggle goes ON, and composed
+ * into the message at send. Two properties matter: every checked comment is in
+ * the capture (a partial batch silently drops someone's review), and capturing
+ * resolves nothing — attaching is not dispatching, and closing a request nobody
+ * acted on is the failure the queue exists to prevent.
+ */
+
+import { describe, expect, test, vi } from 'vitest';
+
+vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn(), info: vi.fn() } }));
+
+vi.mock('./comments-client', () => {
+ const metas = [
+ {
+ threadId: 't1',
+ docName: 'recipes/one',
+ anchor: { exact: 'Heat oven to 425F', prefix: '', suffix: '', start: 0, end: 17 },
+ state: 'anchored',
+ queued: true,
+ latestComment: 'too hot?',
+ createdBy: 'principal-abc',
+ createdAt: 800,
+ },
+ {
+ threadId: 't2',
+ docName: 'recipes/two',
+ anchor: { exact: 'Whisk the peanut sauce', prefix: '', suffix: '', start: 0, end: 22 },
+ state: 'anchored',
+ queued: true,
+ latestComment: 'which peanut butter?',
+ createdBy: 'principal-abc',
+ createdAt: 900,
+ },
+ ];
+ return {
+ __metas: metas,
+ listThreads: vi.fn(async () => metas),
+ createThread: vi.fn(),
+ reply: vi.fn(),
+ resolveThread: vi.fn(),
+ reopenThread: vi.fn(),
+ replaceAnchor: vi.fn(),
+ queueThread: vi.fn(),
+ unqueueThread: vi.fn(),
+ deleteThread: vi.fn(),
+ prepareDispatchBatch: vi.fn(async (ids: readonly string[]) => ({
+ results: ids.map((id) => {
+ const m = metas.find((entry) => entry.threadId === id);
+ if (!m) return { threadId: id, ok: false, error: 'not-found' };
+ return {
+ threadId: id,
+ ok: true,
+ meta: m,
+ payload: {
+ docName: m.docName,
+ instruction: m.latestComment,
+ passage: { exact: m.anchor.exact, prefix: '', suffix: '' },
+ anchorLost: false,
+ passageRepeats: false,
+ },
+ };
+ }),
+ })),
+ completeDispatchBatch: vi.fn(async () => ({ results: [] })),
+ };
+});
+
+describe('prepareQueuedComments', () => {
+ test('captures every checked comment with its doc and passage', async () => {
+ vi.resetModules();
+ const store = await import('./store');
+ await store.refresh();
+ expect(store.getSelectedQueue()).toHaveLength(2);
+
+ const { prepareQueuedComments } = await import('./queue-attachment');
+ const items = await prepareQueuedComments();
+
+ expect(items).toHaveLength(2);
+ expect(items?.map((i) => i.body)).toEqual(['too hot?', 'which peanut butter?']);
+ // A batch spans documents, so each item names its own — attributing a
+ // comment to the wrong file is what the per-item `docName` prevents.
+ expect(items?.map((i) => i.docName)).toEqual(['recipes/one', 'recipes/two']);
+ expect(items?.map((i) => i.quote)).toEqual(['Heat oven to 425F', 'Whisk the peanut sauce']);
+ });
+
+ test('composes into a message with the draft leading', async () => {
+ // The typed words frame the comments; the composer holds only those words
+ // while you write, and this is where the two are joined.
+ vi.resetModules();
+ const store = await import('./store');
+ await store.refresh();
+
+ const { prepareQueuedComments } = await import('./queue-attachment');
+ const { composeCommentBatchInstruction } = await import('./comment-chips');
+ const items = await prepareQueuedComments();
+ const text = composeCommentBatchInstruction(items ?? [], 'Keep the voice consistent.');
+
+ expect(text.startsWith('Keep the voice consistent.')).toBe(true);
+ expect(text).toContain('too hot?');
+ expect(text).toContain('which peanut butter?');
+ });
+
+ test('resolves nothing — attaching is not dispatching', async () => {
+ vi.resetModules();
+ const store = await import('./store');
+ await store.refresh();
+
+ const { prepareQueuedComments } = await import('./queue-attachment');
+ await prepareQueuedComments();
+
+ const api = await import('./comments-client');
+ expect(api.completeDispatchBatch).not.toHaveBeenCalled();
+ // Still queued and still checked — nothing has been sent yet, and the Ask
+ // AI composer's Send must still be able to carry them.
+ expect(store.getSelectedQueue()).toHaveLength(2);
+ });
+
+ test('an empty queue captures nothing, so the toggle stays off', async () => {
+ vi.resetModules();
+ const { prepareQueuedComments } = await import('./queue-attachment');
+ // No `refresh()`, so the store's queue is empty.
+ expect(await prepareQueuedComments()).toBeNull();
+ });
+});
diff --git a/packages/app/src/comments/queue-attachment.ts b/packages/app/src/comments/queue-attachment.ts
new file mode 100644
index 000000000..d2d2a5337
--- /dev/null
+++ b/packages/app/src/comments/queue-attachment.ts
@@ -0,0 +1,54 @@
+/**
+ * Attaching the comment queue to a composer that has no context-chip row.
+ *
+ * The Ask AI composer attaches the queue as context and composes it into the
+ * prompt at send. An agent thread's composer is a plain string field, so this
+ * gives it the same shape with the pieces it lacks: `prepareQueuedComments`
+ * captures the batch when you switch it ON, and the composer folds it into the
+ * message at send time with the draft as its leading instruction.
+ *
+ * Capturing at attach rather than at send is what keeps `submit` synchronous —
+ * the composer's send is fire-and-forget today, and making it await a server
+ * round-trip would open a double-send window it has no guard for. The cost is
+ * that a comment queued AFTER you attach is not in the captured batch; toggle
+ * off and on to re-capture.
+ *
+ * **Nothing resolves.** Attaching, and even sending, leaves every thread queued:
+ * only a real dispatch may close a review request, and a thread's send does not
+ * report whether the prompt landed.
+ */
+
+import { t } from '@lingui/core/macro';
+import { toast } from 'sonner';
+import { type CommentBatchItem, toCommentBatchItem } from './comment-chips';
+import * as api from './comments-client';
+import { getSelectedQueue, refresh } from './store';
+
+/**
+ * Capture the checked queue as batch items, ready to compose into a message.
+ * `null` when there is nothing to attach, so the caller stays detached.
+ *
+ * Goes through `prepareDispatchBatch` rather than reading the local store: the
+ * server re-anchors on prepare, so a passage that moved is reported as lost
+ * HERE, and it is the only side that knows whether a quote repeats in its
+ * document — the two facts that stop an agent editing the wrong passage.
+ */
+export async function prepareQueuedComments(): Promise<CommentBatchItem[] | null> {
+ const ids = getSelectedQueue();
+ if (ids.length === 0) return null;
+
+ let prepared: Awaited<ReturnType<typeof api.prepareDispatchBatch>>;
+ try {
+ prepared = await api.prepareDispatchBatch(ids);
+ } catch {
+ toast.error(t`Couldn't read the queued comments.`);
+ return null;
+ }
+
+ const payloads = prepared.results.flatMap((item) => (item.ok ? [item.payload] : []));
+ // Prepare re-anchors, which can flip a thread to orphaned; pull that in so the
+ // queue reflects what was just captured.
+ await refresh().catch(() => undefined);
+ if (payloads.length === 0) return null;
+ return payloads.map(toCommentBatchItem);
+}
diff --git a/packages/app/src/comments/queue-grouping.test.ts b/packages/app/src/comments/queue-grouping.test.ts
new file mode 100644
index 000000000..c8124adea
--- /dev/null
+++ b/packages/app/src/comments/queue-grouping.test.ts
@@ -0,0 +1,62 @@
+/**
+ * The queue groups its cards by file, so the file name is a heading rather than
+ * a badge on every card.
+ *
+ * What matters is the bucketing rule: a file appears ONCE, at its first queued
+ * comment, and comments added later join that bucket. Commenting back and forth
+ * across two files is the case that would otherwise reproduce the per-card
+ * repetition the grouping removes, so it's the case pinned here.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { groupByDoc } from './queue-grouping';
+import type { CommentThread } from './types';
+
+function thread(id: string, docName: string): CommentThread {
+ return {
+ id,
+ docName,
+ anchor: { quote: `quote ${id}`, prefix: '', suffix: '', start: 0, end: 5 },
+ status: 'open',
+ body: `body ${id}`,
+ createdAt: 1000,
+ queued: true,
+ };
+}
+
+describe('grouping the queue by file', () => {
+ it('gives each file one bucket, ordered by its first comment', () => {
+ const groups = groupByDoc([
+ thread('a1', 'recipes/stir-fry'),
+ thread('b1', 'notes/inbox'),
+ thread('a2', 'recipes/stir-fry'),
+ ]);
+
+ expect(groups.map((group) => group.docName)).toEqual(['recipes/stir-fry', 'notes/inbox']);
+ expect(groups[0]?.threads.map((t) => t.id)).toEqual(['a1', 'a2']);
+ expect(groups[1]?.threads.map((t) => t.id)).toEqual(['b1']);
+ });
+
+ it('keeps queue order inside a file', () => {
+ const groups = groupByDoc([
+ thread('t1', 'notes/inbox'),
+ thread('t2', 'notes/inbox'),
+ thread('t3', 'notes/inbox'),
+ ]);
+
+ expect(groups).toHaveLength(1);
+ expect(groups[0]?.threads.map((t) => t.id)).toEqual(['t1', 't2', 't3']);
+ });
+
+ it('separates files that share a basename', () => {
+ // The heading shows the basename, but the bucket key is the full path —
+ // two `README`s in different folders are two files, not one group.
+ const groups = groupByDoc([thread('x', 'a/README'), thread('y', 'b/README')]);
+
+ expect(groups.map((group) => group.docName)).toEqual(['a/README', 'b/README']);
+ });
+
+ it('returns nothing for an empty queue', () => {
+ expect(groupByDoc([])).toEqual([]);
+ });
+});
diff --git a/packages/app/src/comments/queue-grouping.ts b/packages/app/src/comments/queue-grouping.ts
new file mode 100644
index 000000000..1cfd85670
--- /dev/null
+++ b/packages/app/src/comments/queue-grouping.ts
@@ -0,0 +1,25 @@
+/**
+ * Bucketing for the queue panel: queued comments grouped under their document.
+ *
+ * A file appears ONCE, at the position of its first queued comment, and later
+ * comments on it join that bucket rather than opening a second one — commenting
+ * across two files alternately would otherwise produce a heading per comment,
+ * which is the repetition the grouping exists to remove.
+ */
+
+import type { CommentThread } from './types';
+
+export interface QueueGroup {
+ docName: string;
+ threads: CommentThread[];
+}
+
+export function groupByDoc(threads: readonly CommentThread[]): QueueGroup[] {
+ const byDoc = new Map<string, CommentThread[]>();
+ for (const thread of threads) {
+ const bucket = byDoc.get(thread.docName);
+ if (bucket) bucket.push(thread);
+ else byDoc.set(thread.docName, [thread]);
+ }
+ return [...byDoc].map(([docName, group]) => ({ docName, threads: group }));
+}
diff --git a/packages/app/src/comments/queued-toggle.dom.test.tsx b/packages/app/src/comments/queued-toggle.dom.test.tsx
new file mode 100644
index 000000000..13e597e33
--- /dev/null
+++ b/packages/app/src/comments/queued-toggle.dom.test.tsx
@@ -0,0 +1,103 @@
+/**
+ * The queued button's hover-swap affordance.
+ *
+ * Queued is a settled state that doubles as its own undo: ✓ at rest, ✕ on
+ * hover. The properties worth pinning are the ones easy to lose in a restyle —
+ * both glyphs must be present (a swap done by conditional render can't
+ * cross-fade), the reveal must be keyboard-reachable and not pointer-only, and
+ * the accessible name must say what the click DOES rather than echo the label.
+ */
+
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, test } from 'vitest';
+import { ThreadCard } from './CommentsPanel';
+import type { CommentThread } from './types';
+
+function thread(overrides: Partial<CommentThread> = {}): CommentThread {
+ return {
+ id: 't1',
+ docName: 'recipes/stir-fry',
+ target: { kind: 'body' },
+ anchor: { quote: 'the tofu', prefix: '', suffix: '', start: 0, end: 8 },
+ status: 'open',
+ body: 'press it?',
+ createdAt: 1000,
+ queued: true,
+ ...overrides,
+ };
+}
+
+function renderCard(t: CommentThread) {
+ return render(<ThreadCard thread={t} now={2000} cardRef={() => {}} focused={false} />);
+}
+
+afterEach(() => cleanup());
+
+describe('the queued toggle', () => {
+ test('names the action, not the state', () => {
+ renderCard(thread());
+ // "Queued" is the visible label; the accessible name has to tell a screen
+ // reader user that activating it REMOVES the comment from the batch.
+ expect(screen.getByRole('button', { name: /remove from the queue/i })).toBeTruthy();
+ });
+
+ test('carries both glyphs so the swap can cross-fade', () => {
+ const { container } = renderCard(thread());
+ const button = screen.getByRole('button', { name: /remove from the queue/i });
+ // Two absolutely-positioned icons, one visible at rest and one on hover —
+ // rendering only the current glyph would make the transition impossible.
+ expect(button.querySelectorAll('svg').length).toBe(2);
+ expect(container.querySelector('.group\\/queued')).toBeTruthy();
+ });
+
+ test('reveals on focus as well as hover', () => {
+ renderCard(thread());
+ const markup = screen.getByRole('button', { name: /remove from the queue/i }).innerHTML;
+ // Keyboard parity: hover alone would make this a pointer-only affordance.
+ expect(markup).toContain('group-focus-within/queued:opacity-100');
+ expect(markup).toContain('group-hover/queued:opacity-100');
+ });
+
+ test('an unqueued comment offers Queue instead', () => {
+ renderCard(thread({ id: 't2', queued: false }));
+ expect(screen.getByRole('button', { name: /^queue$/i })).toBeTruthy();
+ });
+});
+
+describe('opening an edit', () => {
+ test('puts the caret after the existing text, not in front of it', async () => {
+ renderCard(thread({ body: 'press it?' }));
+ fireEvent.click(screen.getByRole('button', { name: /edit this comment/i }));
+
+ const field = await screen.findByDisplayValue('press it?');
+ await waitFor(() => expect(document.activeElement).toBe(field));
+ // `autoFocus` alone would leave both at 0 — you would be typing in front of
+ // your own sentence.
+ expect((field as HTMLTextAreaElement).selectionStart).toBe('press it?'.length);
+ expect((field as HTMLTextAreaElement).selectionEnd).toBe('press it?'.length);
+ });
+
+ test('seeds the field with the comment as it stands', async () => {
+ renderCard(thread({ body: 'these quantities disagree' }));
+ fireEvent.click(screen.getByRole('button', { name: /edit this comment/i }));
+ expect(await screen.findByDisplayValue('these quantities disagree')).toBeTruthy();
+ });
+});
+
+describe('a property thread in the panel', () => {
+ test('shows its key as YAML instead of a quote, and offers no jump', () => {
+ render(
+ <ThreadCard
+ thread={thread({ target: { kind: 'property', key: 'tags', path: [] }, anchor: null })}
+ />,
+ );
+ // `tags:` reads as the frontmatter it is — which is the whole distinction
+ // from a short quote, since both are a few characters of monospace.
+ expect(screen.getByText('tags:')).toBeTruthy();
+ // A whole-field comment has no words to reveal, so the control is inert
+ // rather than scrolling the reader somewhere arbitrary. (A comment on a
+ // passage INSIDE a value is clickable — it selects those words.)
+ const target = screen.getByTitle(/on the whole property/i);
+ expect(target.hasAttribute('disabled')).toBe(true);
+ });
+});
diff --git a/packages/app/src/comments/reveal-comment.ts b/packages/app/src/comments/reveal-comment.ts
new file mode 100644
index 000000000..6571da461
--- /dev/null
+++ b/packages/app/src/comments/reveal-comment.ts
@@ -0,0 +1,70 @@
+/**
+ * Jump from a comment to the passage it is anchored to.
+ *
+ * The queue is project-wide, so the target doc is often NOT the one on screen.
+ * That makes this two steps rather than one: navigate if needed, then wait for
+ * that document's editor to actually mount before selecting the passage — a
+ * jump issued during navigation would land on an editor that doesn't exist yet
+ * and silently do nothing.
+ *
+ * The passage is located by its quoted text, the same durable record the anchor
+ * itself is built on, so this keeps working after the text has moved.
+ */
+
+import { requestDocPanelTab } from '@/components/doc-panel-events';
+import { getEditorForDoc, subscribeEditorRegistry } from '@/editor/active-editor';
+import { hashFromDocName } from '@/lib/doc-hash';
+import { type AnchorContext, findQuoteRange } from './anchor-search';
+import { scrollAnchorIntoView } from './scroll-to-anchor';
+import { emitFocusThread } from './store';
+
+/** Give up waiting for an editor that never mounts (bad docName, failed load). */
+const EDITOR_WAIT_MS = 10_000;
+
+/**
+ * Select + scroll to a comment's passage, navigating to its document first when
+ * it isn't the one open. Also opens the Comments tab so the thread is visible
+ * beside the passage it belongs to.
+ */
+export function revealComment(input: {
+ docName: string;
+ quote: string;
+ threadId: string;
+ /** Stored context — disambiguates a quote that appears more than once. */
+ context?: AnchorContext;
+}): void {
+ const focusInEditor = (): boolean => {
+ const editor = getEditorForDoc(input.docName);
+ if (!editor || editor.isDestroyed) return false;
+ const range = findQuoteRange(editor.state.doc, input.quote, input.context);
+ // The doc is open but the words are gone (an orphaned anchor). Still count
+ // it as handled — navigation succeeded; there is simply nothing to select.
+ if (range) {
+ editor.chain().focus().setTextSelection(range).run();
+ scrollAnchorIntoView(editor, range);
+ }
+ emitFocusThread(input.threadId);
+ return true;
+ };
+
+ requestDocPanelTab('comments');
+ if (focusInEditor()) return;
+
+ window.location.assign(hashFromDocName(input.docName));
+
+ // The editor registers itself once mounted; retry on each registry change
+ // rather than guessing at a fixed delay.
+ let settled = false;
+ const stop = (): void => {
+ if (settled) return;
+ settled = true;
+ unsubscribe();
+ window.clearTimeout(timer);
+ };
+ const unsubscribe = subscribeEditorRegistry(() => {
+ if (focusInEditor()) stop();
+ });
+ const timer = window.setTimeout(stop, EDITOR_WAIT_MS);
+ // The editor may already have been registered between the two calls above.
+ if (focusInEditor()) stop();
+}
diff --git a/packages/app/src/comments/reveal-queue.test.ts b/packages/app/src/comments/reveal-queue.test.ts
new file mode 100644
index 000000000..c992c1943
--- /dev/null
+++ b/packages/app/src/comments/reveal-queue.test.ts
@@ -0,0 +1,128 @@
+/**
+ * Posting a comment reveals the queue — but only once the server has taken it.
+ *
+ * The reveal is what tells a first-time reviewer the queue exists and where the
+ * send lives, so it has to fire on a real post. Equally, it must NOT fire on a
+ * rejected one: opening the queue for a comment that failed to anchor shows an
+ * empty batch and reads as "your comment went somewhere", which is worse than
+ * no reveal at all.
+ */
+
+import { describe, expect, test, vi } from 'vitest';
+
+const META = {
+ threadId: 't1',
+ docName: 'recipes/stir-fry',
+ anchor: { exact: 'the tofu', prefix: '', suffix: '', start: 0, end: 8 },
+ state: 'anchored',
+ queued: true,
+ createdBy: 'principal-abc',
+ createdAt: 1000,
+};
+
+vi.mock('sonner', () => ({ toast: { error: vi.fn(), info: vi.fn(), success: vi.fn() } }));
+
+vi.mock('./comments-client', () => ({
+ listThreads: vi.fn(async () => []),
+ createThread: vi.fn(async () => META),
+ reply: vi.fn(),
+ resolveThread: vi.fn(),
+ reopenThread: vi.fn(),
+ replaceAnchor: vi.fn(),
+ queueThread: vi.fn(),
+ unqueueThread: vi.fn(),
+ deleteThread: vi.fn(),
+ prepareDispatchBatch: vi.fn(),
+ completeDispatchBatch: vi.fn(),
+}));
+
+/** Let the store's fire-and-forget promise chain settle. */
+const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
+
+/**
+ * Subscribe through the SAME module instance the store will publish on.
+ * `vi.resetModules()` gives each test a fresh registry, and the event bus is
+ * module state — a statically imported subscriber would listen on the previous
+ * instance's bus and never hear a thing.
+ */
+async function watchReveals(): Promise<{ count: () => number; stop: () => void }> {
+ const { subscribeQueueScopeRequests } = await import('./reveal-queue');
+ let seen = 0;
+ const stop = subscribeQueueScopeRequests(() => {
+ seen += 1;
+ });
+ return { count: () => seen, stop };
+}
+
+describe('createThread reveals the queue', () => {
+ test('fires once the server accepts the comment', async () => {
+ vi.resetModules();
+ const store = await import('./store');
+ const reveals = await watchReveals();
+
+ store.createThread({ docName: 'recipes/stir-fry', quote: 'the tofu', body: 'press it?' });
+ await settle();
+
+ expect(reveals.count()).toBe(1);
+ reveals.stop();
+ });
+
+ test('stays put when the post is rejected', async () => {
+ vi.resetModules();
+ const api = await import('./comments-client');
+ vi.mocked(api.createThread).mockRejectedValueOnce(new Error('passage not found'));
+ const store = await import('./store');
+ const reveals = await watchReveals();
+
+ store.createThread({ docName: 'recipes/stir-fry', quote: 'gone', body: 'x' });
+ await settle();
+
+ expect(reveals.count()).toBe(0);
+ // and the failure is surfaced rather than swallowed
+ const { toast } = await import('sonner');
+ expect(vi.mocked(toast.error)).toHaveBeenCalled();
+ reveals.stop();
+ });
+});
+
+describe('a reveal nobody was listening for', () => {
+ // The reported bug: posting a comment opened the Comments tab but left it on
+ // "This doc". Opening the tab only SCHEDULES a mount, so when the tab wasn't
+ // already showing there was no subscriber when the scope event fired — the
+ // request was simply dropped. The earlier tests missed it by always
+ // subscribing first, which is the one case that already worked.
+ test('is latched for the component the reveal is about to mount', async () => {
+ vi.resetModules();
+ const { revealQueue, consumePendingQueueScope } = await import('./reveal-queue');
+
+ revealQueue(); // nothing subscribed — exactly the tab-was-closed case
+
+ expect(consumePendingQueueScope()).toBe(true);
+ // and only once: a later mount must not re-jump to the queue
+ expect(consumePendingQueueScope()).toBe(false);
+ });
+
+ test('a live subscriber clears the latch instead of leaving it armed', async () => {
+ vi.resetModules();
+ const { revealQueue, consumePendingQueueScope, subscribeQueueScopeRequests } = await import(
+ './reveal-queue'
+ );
+ let handled = 0;
+ const stop = subscribeQueueScopeRequests(() => {
+ handled += 1;
+ });
+
+ revealQueue();
+
+ expect(handled).toBe(1);
+ // Already delivered — a tab mounted later must NOT be yanked to the queue.
+ expect(consumePendingQueueScope()).toBe(false);
+ stop();
+ });
+
+ test('nothing is latched until a comment is actually posted', async () => {
+ vi.resetModules();
+ const { consumePendingQueueScope } = await import('./reveal-queue');
+ expect(consumePendingQueueScope()).toBe(false);
+ });
+});
diff --git a/packages/app/src/comments/reveal-queue.ts b/packages/app/src/comments/reveal-queue.ts
new file mode 100644
index 000000000..26c8687dc
--- /dev/null
+++ b/packages/app/src/comments/reveal-queue.ts
@@ -0,0 +1,60 @@
+/**
+ * Bring the dispatch queue on screen.
+ *
+ * Posting a comment is the moment the queue becomes relevant, and it is also
+ * the moment the send control is easiest to miss: the composer's comments chip
+ * only exists while the Ask AI bar is showing, and the bar is hidden whenever
+ * the sessions dock is open. Without this, a reviewer can queue five comments
+ * and never find the thing that sends them.
+ *
+ * Two steps, because the tab and the scope are owned by different components:
+ * `requestDocPanelTab` opens the doc panel and selects the Comments tab
+ * (`EditorArea` subscribes), and the scope event flips that tab from "This doc"
+ * to "Queue" (`CommentsTab` subscribes, since it owns the toggle's state).
+ */
+
+import { requestDocPanelTab } from '@/components/doc-panel-events';
+
+const QUEUE_SCOPE_EVENT = 'open-knowledge:comments-queue-scope';
+
+// `createThread` reaches this from the store, which the node-env unit tier
+// imports — where there is no `window`. One module-level stand-in (rather than
+// the sibling event modules' per-call default) so subscribe and dispatch still
+// meet on the same target instead of silently passing each other.
+const bus: EventTarget = typeof window === 'undefined' ? new EventTarget() : window;
+
+/**
+ * Latch for the reveal that arrives before anyone can hear it.
+ *
+ * Opening the Comments tab only SCHEDULES a React state change, so when the
+ * tab wasn't already open `CommentsTab` has not mounted — and has not
+ * subscribed — by the time the scope event goes out. The event lands on an
+ * empty room and the tab opens on "This doc". Mirrors the pending-tab latch in
+ * `doc-panel-events.ts`, which exists for the same reason: a live subscriber
+ * clears it, and a component mounting afterwards consumes it instead.
+ */
+let pendingQueueScope = false;
+
+/** True once per reveal that no live subscriber handled. */
+export function consumePendingQueueScope(): boolean {
+ const pending = pendingQueueScope;
+ pendingQueueScope = false;
+ return pending;
+}
+
+export function subscribeQueueScopeRequests(onRequest: () => void): () => void {
+ const handler = (): void => {
+ // Handled live — don't also leave a latch for the next mount to trip on.
+ pendingQueueScope = false;
+ onRequest();
+ };
+ bus.addEventListener(QUEUE_SCOPE_EVENT, handler);
+ return () => bus.removeEventListener(QUEUE_SCOPE_EVENT, handler);
+}
+
+/** Open the doc panel on the Comments tab, scoped to the queue. */
+export function revealQueue(): void {
+ pendingQueueScope = true;
+ requestDocPanelTab('comments');
+ bus.dispatchEvent(new Event(QUEUE_SCOPE_EVENT));
+}
diff --git a/packages/app/src/comments/scroll-to-anchor.test.ts b/packages/app/src/comments/scroll-to-anchor.test.ts
new file mode 100644
index 000000000..5f046c887
--- /dev/null
+++ b/packages/app/src/comments/scroll-to-anchor.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it } from 'vitest';
+import { type AnchorViewport, scrollDeltaForAnchor } from './scroll-to-anchor';
+
+/** A scrollport 800px tall with the usual toolbar strip across its top. */
+const view = (anchorTop: number, anchorBottom: number): AnchorViewport => ({
+ anchorTop,
+ anchorBottom,
+ viewTop: 100,
+ viewBottom: 900,
+ insetTop: 56,
+});
+
+/** Where the passage's top lands after applying the delta. */
+function landsAt(v: AnchorViewport): number {
+ return v.anchorTop - scrollDeltaForAnchor(v);
+}
+
+describe('scrollDeltaForAnchor', () => {
+ it('leaves a comfortably placed passage alone', () => {
+ expect(scrollDeltaForAnchor(view(300, 320))).toBe(0);
+ });
+
+ it('pulls up a passage sitting too low for its card to fit beneath', () => {
+ // Visible, but only 20px from the bottom — the thread card would open
+ // off-screen, which is the whole complaint.
+ const v = view(880, 900);
+ expect(scrollDeltaForAnchor(v)).toBeGreaterThan(0);
+ expect(landsAt(v)).toBe(180);
+ });
+
+ it('clears a passage hidden behind the floating toolbar', () => {
+ const v = view(120, 140);
+ expect(scrollDeltaForAnchor(v)).toBeLessThan(0);
+ expect(landsAt(v)).toBe(180);
+ });
+
+ it('scrolls back up to a passage above the viewport', () => {
+ const v = view(-400, -380);
+ expect(landsAt(v)).toBe(180);
+ });
+
+ it('nudges a passage whose tail runs past the resting band', () => {
+ // A quote spanning most of the scrollport: its start is fine, its end is
+ // not, so it moves just enough to open room underneath.
+ expect(scrollDeltaForAnchor(view(200, 700))).toBe(20);
+ });
+
+ it('counts the inset as unusable, not merely as padding', () => {
+ const withInset = view(120, 140);
+ const withoutInset = { ...withInset, insetTop: 0 };
+ expect(scrollDeltaForAnchor(withInset)).toBeLessThan(0);
+ expect(scrollDeltaForAnchor(withoutInset)).toBe(0);
+ });
+
+ it('still places the passage near the top when the scrollport is tiny', () => {
+ // Shorter than the room a card needs: nothing can be comfortable, so the
+ // passage goes as high as it can rather than staying put.
+ const v: AnchorViewport = {
+ anchorTop: 50,
+ anchorBottom: 60,
+ viewTop: 0,
+ viewBottom: 200,
+ insetTop: 0,
+ };
+ expect(landsAt(v)).toBe(24);
+ });
+});
diff --git a/packages/app/src/comments/scroll-to-anchor.ts b/packages/app/src/comments/scroll-to-anchor.ts
new file mode 100644
index 000000000..3c4a7d641
--- /dev/null
+++ b/packages/app/src/comments/scroll-to-anchor.ts
@@ -0,0 +1,110 @@
+/**
+ * Scroll a comment's passage somewhere you can actually read it.
+ *
+ * Two things went wrong before, both of which land the passage at an edge:
+ *
+ * ProseMirror's own `scrollIntoView` does minimal scroll-arithmetic against the
+ * scrollport's box and, like CM6, does not read `scroll-padding-top` off the
+ * scroll ancestor — so the passage stops flush against the top, underneath the
+ * floating toolbar. And `Element.scrollIntoView({ block: 'center' })` centers
+ * the BLOCK the passage sits in: for a long code fence or a table taller than
+ * the viewport, centering the block says nothing about where the quoted line
+ * ends up, which can be off-screen entirely.
+ *
+ * So: work from the passage's own coordinates, honour the inset the scrollport
+ * declares, and keep room beneath it for the thread card that opens there.
+ */
+
+import type { Editor } from '@tiptap/react';
+import { getEditorView } from '@/editor/utils/get-editor-view';
+
+/**
+ * Room left below the passage for the thread popover, which opens under it.
+ * Generous on purpose — landing the passage on the last visible line puts its
+ * card off-screen, which is the failure this whole module exists to prevent.
+ */
+const CARD_ROOM_PX = 220;
+
+/** Breathing room below the toolbar when we do move, so it isn't flush. */
+const LEAD_PX = 24;
+
+export interface AnchorViewport {
+ /** The passage, in viewport coordinates. */
+ anchorTop: number;
+ anchorBottom: number;
+ /** The scrollport, in viewport coordinates. */
+ viewTop: number;
+ viewBottom: number;
+ /** Top strip of the scrollport hidden behind the floating toolbar. */
+ insetTop: number;
+}
+
+/**
+ * How far to move `scrollTop`; `0` to leave it alone.
+ *
+ * Leaving a comfortably-placed passage alone matters as much as moving a badly
+ * placed one: clicking through a list of comments on the same paragraph should
+ * not jolt the page for each one.
+ */
+export function scrollDeltaForAnchor(v: AnchorViewport): number {
+ const restTop = v.viewTop + v.insetTop;
+ const restBottom = v.viewBottom - CARD_ROOM_PX;
+ if (v.anchorTop >= restTop && v.anchorBottom <= restBottom) return 0;
+ return v.anchorTop - (restTop + LEAD_PX);
+}
+
+/** Nearest scrollable ancestor of the editor content. */
+export function findScrollContainer(el: HTMLElement | null): HTMLElement | null {
+ let node = el?.parentElement ?? null;
+ while (node) {
+ const overflowY = getComputedStyle(node).overflowY;
+ if (overflowY === 'auto' || overflowY === 'scroll') return node;
+ node = node.parentElement;
+ }
+ return null;
+}
+
+/**
+ * Read the inset from the scrollport itself rather than restating the toolbar
+ * height here — one fewer constant to keep in sync with `scroll-pt-14`.
+ */
+function insetTopOf(container: HTMLElement): number {
+ const value = Number.parseFloat(getComputedStyle(container).scrollPaddingTop);
+ return Number.isFinite(value) ? value : 0;
+}
+
+/** Bring a comment's passage into a readable position, with room for its card. */
+export function scrollAnchorIntoView(editor: Editor, range: { from: number; to: number }): void {
+ const view = getEditorView(editor);
+ if (!view) return;
+ const container = findScrollContainer(view.dom);
+ // No scrollport of our own to drive (an embedded or content-sized editor):
+ // ProseMirror's minimal scroll is still better than not moving at all.
+ if (!container) {
+ editor.commands.scrollIntoView();
+ return;
+ }
+ let start: { top: number; bottom: number };
+ let end: { top: number; bottom: number };
+ try {
+ // Throws for a position ProseMirror has not laid out yet (mid-remount).
+ start = view.coordsAtPos(range.from);
+ end = view.coordsAtPos(range.to);
+ } catch {
+ return;
+ }
+ const box = container.getBoundingClientRect();
+ const delta = scrollDeltaForAnchor({
+ anchorTop: start.top,
+ anchorBottom: Math.max(start.bottom, end.bottom),
+ viewTop: box.top,
+ viewBottom: box.bottom,
+ insetTop: insetTopOf(container),
+ });
+ if (delta === 0) return;
+ const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
+ container.scrollTo({
+ top: container.scrollTop + delta,
+ behavior: reduceMotion ? 'auto' : 'smooth',
+ });
+}
diff --git a/packages/app/src/comments/store.refresh-fanout.test.ts b/packages/app/src/comments/store.refresh-fanout.test.ts
new file mode 100644
index 000000000..b8afc0f6d
--- /dev/null
+++ b/packages/app/src/comments/store.refresh-fanout.test.ts
@@ -0,0 +1,97 @@
+/**
+ * One request per refresh.
+ *
+ * Loading the thread list used to cost `2 + 2N` round trips per mutation — the
+ * open doc's threads, the project's threads, then every thread's full event log
+ * — to render a panel that only ever shows each thread's newest comment. That
+ * regression is invisible to typecheck, to lint, and to every other test here:
+ * the data is identical either way, it just arrives N times slower. So the
+ * request count itself is the assertion.
+ */
+
+import { beforeEach, describe, expect, test, vi } from 'vitest';
+
+vi.mock('./comments-client', () => {
+ // Everything the factory needs must be defined INSIDE it — `vi.mock` is
+ // hoisted above module-level declarations.
+ const metas = [
+ {
+ threadId: 't1',
+ docName: 'notes/a',
+ anchor: { exact: 'minimal downtime', prefix: '', suffix: '', start: 0, end: 16 },
+ state: 'anchored',
+ queued: true,
+ latestComment: 'still true?',
+ createdBy: 'principal-abc',
+ createdAt: 900,
+ },
+ {
+ threadId: 't2',
+ docName: 'notes/b',
+ anchor: { exact: 'ship by Q3', prefix: '', suffix: '', start: 0, end: 10 },
+ state: 'anchored',
+ queued: true,
+ latestComment: 'which Q3?',
+ createdBy: 'principal-abc',
+ createdAt: 1000,
+ },
+ ];
+ return {
+ listThreads: vi.fn(async () => metas),
+ createThread: vi.fn(),
+ editComment: vi.fn(),
+ resolveThread: vi.fn(),
+ reopenThread: vi.fn(),
+ replaceAnchor: vi.fn(),
+ queueThread: vi.fn(),
+ unqueueThread: vi.fn(),
+ deleteThread: vi.fn(),
+ prepareDispatchBatch: vi.fn(async () => ({ results: [] })),
+ completeDispatchBatch: vi.fn(async () => ({ results: [] })),
+ };
+});
+
+describe('refresh fan-out', () => {
+ // A fresh store per test, and fresh call counts: the mocked client module
+ // survives `resetModules`, so without the clear each test would also be
+ // counting the previous one's requests.
+ beforeEach(() => {
+ vi.resetModules();
+ vi.clearAllMocks();
+ });
+
+ test('a doc-scoped refresh makes exactly one project-wide request', async () => {
+ const api = await import('./comments-client');
+ const store = await import('./store');
+
+ await store.refresh('notes/a');
+
+ expect(api.listThreads).toHaveBeenCalledTimes(1);
+ // No argument: the project-wide list is a superset of every per-doc view,
+ // so asking for one doc's threads separately is a wasted round trip.
+ expect(api.listThreads).toHaveBeenCalledWith();
+ });
+
+ test('the single fetch populates the per-doc view and the project queue', async () => {
+ const api = await import('./comments-client');
+ const store = await import('./store');
+
+ await store.refresh('notes/a');
+
+ // Guards the guard: an empty store would make the count assertion above
+ // pass for the wrong reason.
+ expect(store.getThreads('notes/a').map((t) => t.id)).toEqual(['t1']);
+ expect(store.getQueue()).toEqual(['t1', 't2']);
+ expect(api.listThreads).toHaveBeenCalledTimes(1);
+ });
+
+ test('the rendered body comes off the cover sheet, with no log read', async () => {
+ // The projected `latestComment` is what removed the per-thread log fetch —
+ // if it stops being the body source, the N reads come straight back.
+ const store = await import('./store');
+
+ await store.refresh('notes/a');
+
+ expect(store.getThreads('notes/a')[0].body).toBe('still true?');
+ });
+});
diff --git a/packages/app/src/comments/store.snapshot-stability.test.ts b/packages/app/src/comments/store.snapshot-stability.test.ts
new file mode 100644
index 000000000..18fe34834
--- /dev/null
+++ b/packages/app/src/comments/store.snapshot-stability.test.ts
@@ -0,0 +1,108 @@
+/**
+ * `useSyncExternalStore` snapshot-stability guard.
+ *
+ * Every getter passed to `useSyncExternalStore` must return a referentially
+ * stable value between real changes — React compares snapshots with `Object.is`
+ * and a getter that builds a fresh array per call re-renders forever
+ * ("Maximum update depth exceeded"). That failure is invisible to typecheck,
+ * lint, and the build: it only appears when the app runs.
+ *
+ * These tests MUST run against a NON-EMPTY store. The empty case is stable even
+ * when the getters are broken (they short-circuit to a frozen empty array), so
+ * asserting on an empty store would pass on the buggy implementation and prove
+ * nothing.
+ */
+
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import type { CommentThreadMeta } from './comments-client';
+
+const QUEUED_META: CommentThreadMeta = {
+ threadId: 't1',
+ docName: 'notes/rollout',
+ anchor: { exact: 'minimal downtime', prefix: '', suffix: '', start: 10, end: 26 },
+ state: 'anchored',
+ queued: true,
+ latestComment: 'still true?',
+ createdBy: 'principal-abc',
+ createdAt: 1000,
+};
+
+vi.mock('./comments-client', () => ({
+ listThreads: vi.fn(async () => [QUEUED_META]),
+ createThread: vi.fn(async () => QUEUED_META),
+ reply: vi.fn(async () => QUEUED_META),
+ resolveThread: vi.fn(async () => QUEUED_META),
+ reopenThread: vi.fn(async () => QUEUED_META),
+ replaceAnchor: vi.fn(async () => QUEUED_META),
+ queueThread: vi.fn(async () => ({ meta: QUEUED_META, orphaned: false })),
+ unqueueThread: vi.fn(async () => QUEUED_META),
+ prepareDispatchBatch: vi.fn(async () => ({ results: [] })),
+ completeDispatchBatch: vi.fn(async () => ({ results: [] })),
+}));
+
+let store: typeof import('./store');
+
+beforeEach(async () => {
+ vi.resetModules();
+ store = await import('./store');
+ // Load real data — the whole point is to assert stability with a populated store.
+ await store.refresh('notes/rollout');
+});
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('useSyncExternalStore snapshot stability (populated store)', () => {
+ test('the fixture actually populates the queue', () => {
+ // Guards the guard: if this ever returns empty, every assertion below is
+ // vacuous and would pass against a broken getter.
+ expect(store.getQueue()).toEqual(['t1']);
+ expect(store.getThreads('notes/rollout')).toHaveLength(1);
+ });
+
+ test('getQueue returns the same reference across repeated calls', () => {
+ const first = store.getQueue();
+ expect(store.getQueue()).toBe(first);
+ expect(store.getQueue()).toBe(first);
+ });
+
+ test('getSelectedQueue returns the same reference across repeated calls', () => {
+ const first = store.getSelectedQueue();
+ expect(store.getSelectedQueue()).toBe(first);
+ expect(store.getSelectedQueue()).toBe(first);
+ });
+
+ test('getThreads returns the same reference across repeated calls', () => {
+ const first = store.getThreads('notes/rollout');
+ expect(store.getThreads('notes/rollout')).toBe(first);
+ expect(store.getThreads('notes/rollout')).toBe(first);
+ });
+
+ test('references stay stable across repeated reads after a refresh', async () => {
+ // The contract is stability BETWEEN writes, which is what keeps React from
+ // looping. A refresh is a write, so it is allowed to hand back new arrays
+ // even when the fetched data is identical — the store keys its snapshots on
+ // a write counter rather than comparing contents, so it cannot know the
+ // refetch changed nothing. That is the deliberate trade: identical data
+ // costs one re-render, and no derived view can go stale on a field nobody
+ // remembered to compare.
+ await store.refresh('notes/rollout');
+
+ const queue = store.getQueue();
+ const selected = store.getSelectedQueue();
+ const threads = store.getThreads('notes/rollout');
+
+ expect(store.getQueue()).toBe(queue);
+ expect(store.getSelectedQueue()).toBe(selected);
+ expect(store.getThreads('notes/rollout')).toBe(threads);
+ });
+
+ test('deselecting a queued item changes the selection but not the queue', () => {
+ const queue = store.getQueue();
+ store.toggleQueueSelection('t1');
+
+ expect(store.getSelectedQueue()).toEqual([]); // the one item is unchecked
+ expect(store.getQueue()).toBe(queue); // still queued, same reference
+ });
+});
diff --git a/packages/app/src/comments/store.ts b/packages/app/src/comments/store.ts
new file mode 100644
index 000000000..a00b87e39
--- /dev/null
+++ b/packages/app/src/comments/store.ts
@@ -0,0 +1,785 @@
+/**
+ * Comment-thread store — a thin client cache over the server's comment API.
+ *
+ * Threads live in `.ok/local/comments/` and every mutation is server-mediated
+ * (so writes carry attribution); this module holds the last-fetched view and
+ * re-fetches when the server signals a change. It keeps the window-scoped
+ * pub/sub idiom of `ask-ai-composer-events.ts` for the UI-only signals
+ * (focus a thread, open a popover, start the composer).
+ *
+ * useSyncExternalStore contract: `getThreads(docName)` returns a referentially
+ * stable array between refreshes — the array identity changes only when data
+ * actually changes — so React's snapshot comparison never loops.
+ *
+ * Delivery (handing a comment to an agent) is NOT here: it needs the app's
+ * Ask-AI handoff hook, which is React context. Callers pass their own hand-off
+ * into {@link dispatchComments}; this module owns only the server round-trips
+ * that bracket it (`dispatch-prepare-batch` → hand off → `dispatch-complete-batch`).
+ */
+
+import { t } from '@lingui/core/macro';
+import { useSyncExternalStore } from 'react';
+import { toast } from 'sonner';
+import { subscribeToDocumentsChanged } from '@/lib/documents-events';
+import type { DispatchPayload } from './comments-client';
+import * as api from './comments-client';
+import { revealQueue } from './reveal-queue';
+import type { CommentThread } from './types';
+
+const EMPTY: readonly CommentThread[] = Object.freeze([]);
+const EMPTY_QUEUE: readonly string[] = Object.freeze([]);
+
+const threadsByDoc = new Map<string, CommentThread[]>();
+/** Project-wide view backing the queue (threads on docs you don't have open). */
+let allThreads: CommentThread[] = [];
+const listeners = new Set<() => void>();
+const loadedDocs = new Set<string>();
+let allLoaded = false;
+
+/**
+ * Which queued threads are checked for the next batch. Purely client-side: the
+ * server records *queued*, the reviewer decides *selected*. Nothing to persist
+ * — a selection is a decision about the click you are about to make.
+ */
+let deselected = new Set<string>();
+
+/**
+ * Write counters — the key every derived snapshot is cached against.
+ *
+ * `useSyncExternalStore` needs a getter that returns the same reference between
+ * writes, and this is how the derived views get it: rebuild when the counter
+ * moved, otherwise hand back what you built last time. What this replaces was
+ * hand-comparing each view's fields, which went quietly stale on any field
+ * nobody remembered to list and made adding a field to {@link CommentThread} a
+ * two-place edit.
+ *
+ * Two counters rather than one because they are genuinely independent axes:
+ * unchecking a queued comment changes what a send would carry, but the queue
+ * itself is untouched, and collapsing them would churn the queue on every
+ * checkbox.
+ *
+ * The remaining cost is coarseness: a refetch returning identical data still
+ * counts as a write and still re-renders, where a content comparison could have
+ * suppressed it. Comment writes are user-initiated clicks, not a stream, so that
+ * is cheap — the same trade the ACP thread store makes.
+ */
+let version = 0;
+let selectionVersion = 0;
+
+function notify(): void {
+ for (const listener of listeners) listener();
+}
+
+/** The fetched thread data changed. */
+function bump(): void {
+ version += 1;
+ notify();
+}
+
+/** Only the reviewer's checked subset changed. */
+function bumpSelection(): void {
+ selectionVersion += 1;
+ notify();
+}
+
+// ---------------------------------------------------------------------------
+// Server → UI mapping
+// ---------------------------------------------------------------------------
+
+/** Cover sheet → the display shape the panel renders. */
+function toThread(meta: api.CommentThreadMeta): CommentThread {
+ return {
+ id: meta.threadId,
+ docName: meta.docName,
+ // Taken as-is: the response is schema-parsed at the client boundary, and the
+ // schema defaults `target` to `body` and `path` to `[]`, so anything that
+ // reaches here already has both.
+ target: meta.target,
+ anchor:
+ meta.anchor === null
+ ? null
+ : {
+ quote: meta.anchor.exact,
+ prefix: meta.anchor.prefix,
+ suffix: meta.anchor.suffix,
+ start: meta.anchor.start,
+ end: meta.anchor.end,
+ },
+ status: meta.state === 'anchored' ? 'open' : meta.state,
+ // The live comment rides the cover sheet — a thread renders as its current
+ // request, and there is no history behind it to render.
+ body: meta.latestComment,
+ createdAt: meta.createdAt,
+ // "Queued for the next batch" is what the UI shows as in-flight; the server
+ // deliberately does not persist "an agent is working right now".
+ queued: meta.queued,
+ };
+}
+
+/**
+ * Every thread in the project, in one request.
+ *
+ * This used to fetch the open doc's threads, then the project's threads, then
+ * every thread's full event log — `2 + 2N` round trips per mutation, to render
+ * a list that only ever shows each thread's newest comment. The server projects
+ * that comment onto the cover sheet, so the project-wide list is a superset of
+ * every per-doc view and one call serves all of them.
+ */
+async function fetchThreads(): Promise<CommentThread[]> {
+ const metas = await api.listThreads();
+ return metas.map(toThread).sort((a, b) => b.createdAt - a.createdAt);
+}
+
+/** Refresh every loaded view from one fetch. */
+export async function refresh(docName?: string): Promise<void> {
+ if (docName !== undefined) loadedDocs.add(docName);
+ const nextAll = await fetchThreads();
+ allThreads = nextAll;
+ allLoaded = true;
+ // Every per-doc cache is a slice of the same fetch, so a change made from the
+ // queue panel shows up in an open doc's panel without a second round trip.
+ for (const doc of loadedDocs) {
+ threadsByDoc.set(
+ doc,
+ nextAll.filter((t) => t.docName === doc),
+ );
+ }
+ // One write, one bump. The derived queue views rebuild off the new version on
+ // whatever reads them next, so a subscriber reading during this same tick
+ // cannot see them disagree with `allThreads`.
+ bump();
+}
+
+/**
+ * Refetch when the server says comments changed.
+ *
+ * Our own mutations already refresh themselves, so this is what carries a
+ * change made anywhere else — a second window, or the queue panel in a doc this
+ * tab doesn't have open. Installed on first read rather than at module scope:
+ * the node test tier imports this module with no `window` to listen on.
+ */
+let cc1Installed = false;
+function ensureCc1Subscription(): void {
+ if (cc1Installed || typeof window === 'undefined') return;
+ cc1Installed = true;
+ subscribeToDocumentsChanged((channels) => {
+ if (!channels.includes('comments')) return;
+ // Quiet by design: this is a background signal nobody clicked, so a failed
+ // refetch has no action attached to it and toasting would interrupt work
+ // the user is doing elsewhere. The next signal re-syncs.
+ void refresh().catch(() => undefined);
+ });
+}
+
+/** Load a doc's threads once; subsequent refreshes come from mutations + CC1. */
+function ensureLoaded(docName: string): void {
+ ensureCc1Subscription();
+ if (loadedDocs.has(docName)) return;
+ loadedDocs.add(docName);
+ void refresh(docName).catch(() => {
+ loadedDocs.delete(docName);
+ });
+}
+
+function ensureAllLoaded(): void {
+ ensureCc1Subscription();
+ if (allLoaded) return;
+ allLoaded = true;
+ void refresh().catch(() => {
+ allLoaded = false;
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Reads
+// ---------------------------------------------------------------------------
+
+export function getThreads(docName: string): readonly CommentThread[] {
+ ensureLoaded(docName);
+ return threadsByDoc.get(docName) ?? EMPTY;
+}
+
+export function subscribe(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
+
+/** React binding — re-renders whenever `docName`'s threads change. */
+export function useCommentThreads(docName: string): readonly CommentThread[] {
+ return useSyncExternalStore(
+ subscribe,
+ () => getThreads(docName),
+ () => EMPTY,
+ );
+}
+
+/** Look a thread up across every doc (the queue is project-wide). */
+export function getThreadById(threadId: string): CommentThread | null {
+ for (const threads of threadsByDoc.values()) {
+ const found = threads.find((t) => t.id === threadId);
+ if (found) return found;
+ }
+ return allThreads.find((t) => t.id === threadId) ?? null;
+}
+
+// ---------------------------------------------------------------------------
+// Writes — each round-trips to the server, then refreshes
+// ---------------------------------------------------------------------------
+
+/**
+ * Post a comment. The passage is identified by its quoted text — the editor has
+ * ProseMirror positions, which are not the body offsets the server anchors
+ * against, so the server locates the words itself. Queue-first: posting adds it
+ * to the batch rather than dispatching on its own.
+ */
+export function createThread(args: {
+ docName: string;
+ quote: string;
+ body: string;
+ /** Rendered text either side of the pick — which occurrence, when the quote repeats. */
+ prefix?: string;
+ suffix?: string;
+ /**
+ * Runs once the server has accepted the comment, with its new id.
+ *
+ * A callback rather than a `dispatch` flag because sending goes through the
+ * open-session path, which imports this module — doing it here would close an
+ * import cycle. The sequencing still has to live behind the request: only this
+ * side holds the id, and sending before the server accepts would hand an agent
+ * a thread that failed to anchor.
+ */
+ onCreated?: (threadId: string) => void;
+}): void {
+ void api
+ .createThread({
+ docName: args.docName,
+ quote: args.quote,
+ prefix: args.prefix,
+ suffix: args.suffix,
+ body: args.body,
+ queue: true,
+ })
+ .then((meta) => {
+ // Voided + caught rather than left floating: it is NOT chained into the
+ // outer `.catch` below, so a rejection here would surface as an unhandled
+ // promise. A stale panel is the whole cost of a failed refetch, and the
+ // next CC1 signal corrects it — the creation itself already succeeded.
+ void refresh(args.docName).catch(() => undefined);
+ if (args.onCreated !== undefined) {
+ // Going straight to an agent: no queue reveal, because the comment is
+ // not sitting in the queue waiting to be noticed.
+ args.onCreated(meta.threadId);
+ return;
+ }
+ // Only after the server accepted it. Revealing optimistically would open
+ // the queue on a comment that then failed to anchor.
+ revealQueue();
+ emitCommentPosted();
+ })
+ .catch((err: unknown) => {
+ // A failed post used to vanish — the comment simply never appeared, with
+ // nothing to explain why. Surface it: the usual cause is a passage the
+ // server can't locate in the document body.
+ toast.error(
+ err instanceof Error && err.message
+ ? t`Couldn't add that comment: ${err.message}`
+ : t`Couldn't add that comment.`,
+ );
+ });
+}
+
+/**
+ * Post a comment on a frontmatter key. Same queue-first flow as a passage
+ * comment — it joins the batch rather than dispatching on its own.
+ *
+ * The key is sent by name, so none of the passage machinery runs: no quote to
+ * locate, no context to disambiguate, and no way to land on the wrong target.
+ */
+export function createPropertyThread(args: {
+ docName: string;
+ propertyKey: string;
+ /** Steps into the value — one list item, one nested field. Omit for the value itself. */
+ propertyPath?: (string | number)[];
+ /** Selected text INSIDE the value. Omit to comment on the whole thing. */
+ quote?: string;
+ body: string;
+}): void {
+ void api
+ .createThread({
+ docName: args.docName,
+ propertyKey: args.propertyKey,
+ propertyPath: args.propertyPath,
+ quote: args.quote,
+ body: args.body,
+ queue: true,
+ })
+ .then(() => {
+ // Same as the passage path above: not chained into the outer `.catch`, so
+ // it has to carry its own.
+ void refresh(args.docName).catch(() => undefined);
+ revealQueue();
+ emitCommentPosted();
+ })
+ .catch((err: unknown) => {
+ toast.error(
+ err instanceof Error && err.message
+ ? t`Couldn't add that comment: ${err.message}`
+ : t`Couldn't add that comment.`,
+ );
+ });
+}
+
+/**
+ * Every mutation's tail: refresh on success, SAY SO on failure.
+ *
+ * These used to end in `.catch(() => undefined)`. A rejected edit or delete then
+ * looked exactly like a successful one — the card sat there unchanged and the
+ * reviewer had no way to tell the server had refused. The message is the
+ * server's own: `request` lifts the RFC 9457 `title`, which is where the comment
+ * API puts its reasons ("The quoted passage is not in the document").
+ */
+function settle(promise: Promise<unknown>, docName: string | undefined, failed: string): void {
+ void promise
+ .then(() => refresh(docName))
+ .catch((err: unknown) => {
+ toast.error(err instanceof Error && err.message ? `${failed} ${err.message}` : failed);
+ // Re-sync anyway: a rejection can still have changed server state (a
+ // thread deleted by another window), and leaving the stale row on screen
+ // would be a second, quieter lie.
+ void refresh(docName).catch(() => undefined);
+ });
+}
+
+export function editComment(threadId: string, body: string): void {
+ const docName = getThreadById(threadId)?.docName;
+ settle(api.editComment(threadId, body), docName, t`Couldn't save that edit.`);
+}
+
+export function resolveThread(threadId: string): void {
+ const docName = getThreadById(threadId)?.docName;
+ settle(api.resolveThread(threadId), docName, t`Couldn't resolve that comment.`);
+}
+
+export function reopenThread(threadId: string): void {
+ const docName = getThreadById(threadId)?.docName;
+ settle(api.reopenThread(threadId), docName, t`Couldn't reopen that comment.`);
+}
+
+/**
+ * Delete a thread outright. Destructive: both files go, and the conversation
+ * with them. The queue's ✕ only *unqueues* — this is the separate, explicit act.
+ */
+export function deleteThread(threadId: string): void {
+ const docName = getThreadById(threadId)?.docName;
+ settle(api.deleteThread(threadId), docName, t`Couldn't delete that comment.`);
+}
+
+/** Re-place an orphaned thread onto a fresh passage. */
+export function replaceOrphan(
+ threadId: string,
+ quote: string,
+ context?: { prefix: string; suffix: string },
+): void {
+ const docName = getThreadById(threadId)?.docName;
+ settle(
+ api.replaceAnchor(threadId, { quote, prefix: context?.prefix, suffix: context?.suffix }),
+ docName,
+ t`Couldn't re-place that comment.`,
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Queue — `queued` is server state; the checked subset is local UI state
+// ---------------------------------------------------------------------------
+
+/**
+ * Derived queue arrays, cached against {@link version}.
+ *
+ * `useSyncExternalStore` compares snapshots with `Object.is`, so a getter that
+ * builds a fresh array on every call reports a change on every render and loops
+ * forever ("Maximum update depth exceeded"). Rebuilding only when the version
+ * moved gives the stable reference without anyone having to enumerate which
+ * fields count as a change — and `selected` derives from both `allThreads` and
+ * `deselected`, which one counter already covers.
+ */
+let queueSnapshot: readonly string[] = EMPTY_QUEUE;
+let queueSnapshotVersion = -1;
+let selectedSnapshot: readonly string[] = EMPTY_QUEUE;
+let selectedSnapshotVersion = -1;
+let selectedSnapshotSelectionVersion = -1;
+
+export function getQueue(): readonly string[] {
+ ensureAllLoaded();
+ if (queueSnapshotVersion !== version) {
+ // OLDEST first — the order the comments were written, which is the order a
+ // reviewer means by "these comments." `allThreads` is sorted newest-first
+ // for the panel, and inheriting that sort silently numbered the composed
+ // batch backwards. Display order and run order are different concerns, so
+ // the queue sorts for itself.
+ //
+ // `createdAt` rather than the `queued` event's timestamp: posting a comment
+ // queues it, so the two agree in practice, and the client no longer reads
+ // event logs at all.
+ const ids = allThreads
+ .filter((t) => t.queued && t.status !== 'resolved')
+ .sort((a, b) => a.createdAt - b.createdAt)
+ .map((t) => t.id);
+ queueSnapshot = ids.length === 0 ? EMPTY_QUEUE : ids;
+ queueSnapshotVersion = version;
+ }
+ return queueSnapshot;
+}
+
+export function useQueue(): readonly string[] {
+ return useSyncExternalStore(subscribe, getQueue, () => EMPTY_QUEUE);
+}
+
+/** Queued minus whatever the reviewer unchecked — what a batch send actually ships. */
+export function getSelectedQueue(): readonly string[] {
+ const queued = getQueue();
+ // Derives from both axes, so it rebuilds when either moves.
+ if (
+ selectedSnapshotVersion !== version ||
+ selectedSnapshotSelectionVersion !== selectionVersion
+ ) {
+ const ids = queued.filter((id) => !deselected.has(id));
+ selectedSnapshot = ids.length === 0 ? EMPTY_QUEUE : ids;
+ selectedSnapshotVersion = version;
+ selectedSnapshotSelectionVersion = selectionVersion;
+ }
+ return selectedSnapshot;
+}
+
+export function useQueueSelection(): readonly string[] {
+ return useSyncExternalStore(subscribe, getSelectedQueue, () => EMPTY_QUEUE);
+}
+
+export function isQueued(threadId: string): boolean {
+ return getQueue().includes(threadId);
+}
+
+export function addToQueue(threadId: string): void {
+ const docName = getThreadById(threadId)?.docName;
+ // Re-queuing clears any earlier deselection.
+ if (deselected.has(threadId)) {
+ const next = new Set(deselected);
+ next.delete(threadId);
+ deselected = next;
+ bumpSelection();
+ }
+ settle(api.queueThread(threadId), docName, t`Couldn't queue that comment.`);
+}
+
+export function removeFromQueue(threadId: string): void {
+ const docName = getThreadById(threadId)?.docName;
+ settle(api.unqueueThread(threadId), docName, t`Couldn't remove that comment from the queue.`);
+}
+
+export function toggleQueue(threadId: string): void {
+ if (isQueued(threadId)) removeFromQueue(threadId);
+ else addToQueue(threadId);
+}
+
+/**
+ * Re-check everything in the queue.
+ *
+ * Deselection is sticky — it lives in `deselected` until something clears it —
+ * so "put the queue on this message" has to mean the WHOLE queue. Without this,
+ * re-attaching after unchecking every item would attach a batch that carries
+ * nothing, and the control would look broken twice over.
+ */
+export function selectAllQueued(): void {
+ if (deselected.size === 0) return;
+ deselected = new Set();
+ bumpSelection();
+}
+
+/** Check / uncheck a queued item without removing it from the queue. */
+export function toggleQueueSelection(threadId: string): void {
+ const next = new Set(deselected);
+ if (next.has(threadId)) next.delete(threadId);
+ else next.add(threadId);
+ deselected = next;
+ bumpSelection();
+}
+
+export function clearQueue(): void {
+ const ids = getQueue();
+ if (ids.length === 0) return;
+ // Per-item tolerance, then ONE report: clearing twenty comments must not fire
+ // twenty toasts, but a partial clear cannot pass for a complete one either.
+ void Promise.all(
+ ids.map((id) =>
+ api
+ .unqueueThread(id)
+ .then(() => true)
+ .catch(() => false),
+ ),
+ ).then((results) => {
+ const failed = results.filter((ok) => !ok).length;
+ if (failed > 0) {
+ toast.error(t`${failed} of ${ids.length} comments could not be removed from the queue.`);
+ }
+ void refresh().catch(() => undefined);
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Dispatch — the server brackets it; the app's Ask-AI plumbing delivers
+// ---------------------------------------------------------------------------
+
+/**
+ * Hand a prepared batch to an agent. `true` when it landed, `false` when it did
+ * not — a hand-off that never happened must not resolve its threads.
+ *
+ * Passed in per call rather than registered in a module slot. The slot version
+ * was only installed while the Comments tab was mounted, which made the whole
+ * dispatch path silently inert anywhere else and forced a second, unguarded
+ * delivery route to exist alongside it.
+ */
+export type ComposeDispatch = (items: readonly BatchPreparedItem[]) => Promise<boolean>;
+
+export interface BatchPreparedItem {
+ threadId: string;
+ payload: DispatchPayload;
+}
+
+/**
+ * One dispatch at a time, across every surface that sends the queue.
+ *
+ * A send is not atomic: it awaits the server's anchor re-find, then the
+ * hand-off, and only then does `completeDispatchBatch` drain what shipped. For
+ * that whole window `getSelectedQueue()` still returns the same ids — so a
+ * second Enter in the composer, or a second click on the queue panel's Send,
+ * reads the identical batch and hands it to a second agent turn. Neither
+ * surface disables its button across that window.
+ *
+ * Module scope so the flag spans surfaces rather than sitting in one component:
+ * the composer and the panel drain ONE queue, and they must not race each
+ * other either. Same shape as the launcher's `inflightLaunches`.
+ */
+let dispatchInFlight = false;
+
+/**
+ * THE dispatch path. Prepare the batch, hand it over, resolve what shipped.
+ *
+ * Every surface routes through here — the composer, the queue panel's send, and
+ * the append-to-an-open-session path — so the re-entrancy guard, the
+ * re-anchor-on-prepare, and the single `completeDispatchBatch` call site apply
+ * to all of them rather than to whichever one remembered.
+ *
+ * Returns the ids that shipped, so a caller can clear its draft only on a real
+ * send. A batch that fails to deliver leaves every thread queued.
+ */
+export async function dispatchComments({
+ compose,
+ threadIds,
+ resolve = true,
+}: {
+ compose: ComposeDispatch;
+ /**
+ * Send exactly these instead of the checked queue — the selection composer
+ * hands over the ONE comment just written, which is not in the checked set.
+ */
+ threadIds?: readonly string[];
+ /**
+ * Close the threads once handed over. True for a turn that RUNS: the agent
+ * has it. False when the batch only lands staged in a live input — the human
+ * still has to press enter, and marking work done that nobody has acted on is
+ * the failure the queue exists to prevent.
+ */
+ resolve?: boolean;
+}): Promise<string[]> {
+ const ids = threadIds ?? getSelectedQueue();
+ if (ids.length === 0) return [];
+ if (dispatchInFlight) return [];
+ dispatchInFlight = true;
+ try {
+ return await runDispatch(ids, compose, resolve);
+ } finally {
+ dispatchInFlight = false;
+ }
+}
+
+async function runDispatch(
+ ids: readonly string[],
+ compose: ComposeDispatch,
+ resolve: boolean,
+): Promise<string[]> {
+ let prepared: Awaited<ReturnType<typeof api.prepareDispatchBatch>>;
+ try {
+ prepared = await api.prepareDispatchBatch(ids);
+ } catch (err) {
+ // The send is over before it began, and the button gives no other feedback —
+ // silence here read as "the click did nothing".
+ toast.error(
+ err instanceof Error && err.message
+ ? t`Couldn't read the queued comments: ${err.message}`
+ : t`Couldn't read the queued comments — nothing was sent.`,
+ );
+ return [];
+ }
+ // Prepare re-anchors, which can flip a thread to orphaned; surface that even
+ // when the hand-off below fails.
+ bump();
+ const items = prepared.results.flatMap((item) =>
+ item.ok ? [{ threadId: item.threadId, payload: item.payload }] : [],
+ );
+ if (items.length === 0) {
+ // Every id came back missing — the threads were deleted between queueing and
+ // now, which the re-sync below makes visible. Nothing failed, so nothing to
+ // report.
+ await refresh().catch(() => undefined);
+ return [];
+ }
+ let delivered = false;
+ try {
+ delivered = await compose(items);
+ } catch {
+ // Leave them queued — a hand-off that never happened must not resolve.
+ delivered = false;
+ }
+ const shipped = delivered ? items.map((item) => item.threadId) : [];
+ if (shipped.length > 0 && resolve) {
+ // The batch DID reach the agent; only the bookkeeping failed. Say which, or
+ // the reviewer sees comments still sitting in the queue and sends them a
+ // second time.
+ await api.completeDispatchBatch(shipped).catch(() => {
+ toast.error(t`Sent, but the comments could not be marked done — they are still queued.`);
+ });
+ }
+ // Background re-sync. Deliberately quiet: the send already reported itself,
+ // and a failed refetch only means the panel is briefly stale, which the next
+ // CC1 signal or panel open corrects.
+ await refresh().catch(() => undefined);
+ return shipped;
+}
+
+// ---------------------------------------------------------------------------
+// UI-only signals (no server state)
+// ---------------------------------------------------------------------------
+
+const FOCUS_EVENT = 'ok:comment-focus-thread';
+const POPOVER_EVENT = 'ok:comment-open-popover';
+const START_EVENT = 'ok:comment-start';
+const POSTED_EVENT = 'ok:comment-posted';
+
+// The node-env unit tier imports this module and has no `window`, so touching
+// these emitters there would throw. One module-level stand-in (not a per-call
+// default) so subscribe and dispatch still meet on the same target.
+const bus: EventTarget = typeof window === 'undefined' ? new EventTarget() : window;
+
+export function emitFocusThread(threadId: string): void {
+ bus.dispatchEvent(new CustomEvent(FOCUS_EVENT, { detail: threadId }));
+}
+
+export function subscribeFocusThread(onFocus: (threadId: string) => void): () => void {
+ const handler = (event: Event): void => onFocus((event as CustomEvent<string>).detail);
+ bus.addEventListener(FOCUS_EVENT, handler);
+ return () => bus.removeEventListener(FOCUS_EVENT, handler);
+}
+
+/**
+ * Which thread the reader is on right now — its popover is open, or the pointer
+ * is on its card or margin marker. `null` for none.
+ *
+ * This is what tells two comments sharing a passage apart. Every commented
+ * passage carries the same pale wash, so overlapping ones read as one mark;
+ * deepening the active thread's own range is what says which is which. Kept out
+ * of {@link subscribe} deliberately — pointing at a comment must not re-render
+ * every panel that reads the thread list.
+ */
+let pinnedThreadId: string | null = null;
+let pointedThreadId: string | null = null;
+let activeThreadId: string | null = null;
+const activeListeners = new Set<() => void>();
+
+/** Pointing at something wins over the open popover; it's the newer intent. */
+function recomputeActive(): void {
+ const next = pointedThreadId ?? pinnedThreadId;
+ if (next === activeThreadId) return;
+ activeThreadId = next;
+ for (const listener of activeListeners) listener();
+}
+
+export function getActiveThread(): string | null {
+ return activeThreadId;
+}
+
+/** Pointer or keyboard focus arrived on a thread's card or margin marker. */
+export function setActiveThread(threadId: string | null): void {
+ pointedThreadId = threadId;
+ recomputeActive();
+}
+
+/**
+ * Stand down only if this thread is still the pointed-at one — the pointer can
+ * reach the next card before the last one's leave handler runs, and an
+ * unconditional clear would blank the highlight that just lit up. An open
+ * popover keeps its thread active underneath.
+ */
+export function clearActiveThread(threadId: string): void {
+ if (pointedThreadId !== threadId) return;
+ pointedThreadId = null;
+ recomputeActive();
+}
+
+export function subscribeActiveThread(listener: () => void): () => void {
+ activeListeners.add(listener);
+ return () => {
+ activeListeners.delete(listener);
+ };
+}
+
+/**
+ * Which thread's in-doc popover is open — `null` for none.
+ *
+ * One signal both ways, rather than "open" one-way. The popover used to close
+ * itself privately (Escape, outside click, thread resolved), so the margin rail
+ * never learned about it: the rail kept a marker lit for a popover that was gone,
+ * and could not tell whether clicking a marker should open or close.
+ */
+export function emitOpenThreadPopover(threadId: string | null): void {
+ pinnedThreadId = threadId;
+ recomputeActive();
+ bus.dispatchEvent(new CustomEvent(POPOVER_EVENT, { detail: threadId }));
+}
+
+export function subscribeOpenThreadPopover(
+ onChange: (threadId: string | null) => void,
+): () => void {
+ const handler = (event: Event): void => onChange((event as CustomEvent<string | null>).detail);
+ bus.addEventListener(POPOVER_EVENT, handler);
+ return () => bus.removeEventListener(POPOVER_EVENT, handler);
+}
+
+/**
+ * A comment was successfully posted.
+ *
+ * The composer pins a selection until you send or dismiss it, deliberately, so
+ * it survives clicking away into the input. But filing a comment means you are
+ * DONE with that passage — leaving it pinned sends the same words to the agent
+ * twice, once as the comment's quoted passage and once as an unrelated
+ * in-scope selection.
+ */
+export function emitCommentPosted(): void {
+ bus.dispatchEvent(new CustomEvent(POSTED_EVENT));
+}
+
+export function subscribeCommentPosted(onPosted: () => void): () => void {
+ const handler = (): void => onPosted();
+ bus.addEventListener(POSTED_EVENT, handler);
+ return () => bus.removeEventListener(POSTED_EVENT, handler);
+}
+
+export function emitStartComment(): void {
+ bus.dispatchEvent(new CustomEvent(START_EVENT));
+}
+
+export function subscribeStartComment(onStart: () => void): () => void {
+ const handler = (): void => onStart();
+ bus.addEventListener(START_EVENT, handler);
+ return () => bus.removeEventListener(START_EVENT, handler);
+}
diff --git a/packages/app/src/comments/types.ts b/packages/app/src/comments/types.ts
new file mode 100644
index 000000000..892eea55e
--- /dev/null
+++ b/packages/app/src/comments/types.ts
@@ -0,0 +1,79 @@
+/**
+ * The client's view of a comment thread.
+ *
+ * A flattened projection of what the server returns — its cover sheet plus the
+ * current comment — shaped for rendering rather than for storage. The
+ * authoritative schema lives server-side in
+ * `packages/server/src/comments/types.ts`; this is what survives the trip to
+ * the UI.
+ */
+
+/** Thread lifecycle. `orphaned` = the anchored text is gone. */
+type CommentStatus = 'open' | 'resolved' | 'orphaned';
+
+/**
+ * Content-addressed anchor sketch: we re-find the passage by its quote (plus a
+ * little surrounding context for disambiguation), never by a saved position —
+ * the whole point of REPORT §3. Exact-match-or-orphan, no fuzzy pass (matches
+ * the OUTCOMES non-goal "No fuzzy re-anchoring at v1").
+ */
+interface CommentAnchor {
+ quote: string;
+ prefix: string;
+ suffix: string;
+ /**
+ * Position of the passage in the doc's body, as resolved by the SERVER's
+ * re-find (which disambiguates a repeated quote by context and by nearest
+ * previous position). Highlights use this rather than re-running `indexOf`
+ * on the client, which picks the first match and lands on the wrong
+ * occurrence whenever a quote appears more than once.
+ */
+ start: number;
+ end: number;
+}
+
+/**
+ * Which text the comment's `anchor` is measured against.
+ *
+ * `body` is the markdown. `property` narrows to one frontmatter value — `key`
+ * alone is the whole property, `path` walks into it (`['tags', 2]`). Structure is
+ * addressed by name, which is exact; prose inside a value is addressed by its
+ * words, which is what `anchor` is for.
+ *
+ * Either way a property thread has NO range in the document body, so surfaces
+ * that draw there — the anchor decorations, and the rail's quote search — must
+ * branch on the target rather than fall back to `anchor`, whose offsets index
+ * the value, not the doc.
+ */
+type CommentTarget =
+ | { kind: 'body' }
+ | {
+ kind: 'property';
+ key: string;
+ /** Steps into the value. Empty means the value itself. */
+ path: readonly (string | number)[];
+ };
+
+export interface CommentThread {
+ id: string;
+ docName: string;
+ target: CommentTarget;
+ /**
+ * A passage within the text `target` selects, or null for the whole thing.
+ * With a property target its offsets index THAT VALUE, never the document.
+ */
+ anchor: CommentAnchor | null;
+ status: CommentStatus;
+ /** The comment's current text — its newest revision. */
+ body: string;
+ createdAt: number;
+ /**
+ * The comment is in the dispatch queue, waiting to be sent in the next batch.
+ *
+ * Deliberately NOT "an agent is working on it": the server does not persist
+ * in-flight state (an ACP thread and its agent's writes share no join key),
+ * so claiming work is underway would be a guess. Queued is a fact; working is
+ * not.
+ */
+ queued: boolean;
+}
diff --git a/packages/app/src/comments/use-comment-agent-picker.ts b/packages/app/src/comments/use-comment-agent-picker.ts
new file mode 100644
index 000000000..df01c39f5
--- /dev/null
+++ b/packages/app/src/comments/use-comment-agent-picker.ts
@@ -0,0 +1,167 @@
+/**
+ * Agent picker for the queue panel's Send control.
+ *
+ * Assembles the same row set the Ask-AI composer's picker shows — enabled
+ * Desktop apps, docked-terminal CLIs, in-app agents — and resolves the current
+ * target with the shared `resolveLauncherSelection`.
+ *
+ * KNOWN DUPLICATION: `BottomComposer`, `CreatePromptComposer`,
+ * `TerminalSessionsHost`, and this file each assemble these rows independently.
+ * They agree only by discipline, and the composer's own comment already warns
+ * about the pickers drifting. Consolidating them into one shared hook is the
+ * right fix; this copy was taken deliberately to keep the queue panel isolated
+ * from those working surfaces, not because a fourth copy is correct.
+ *
+ * Picks write through `saveStickyAgent`, the same storage the composer reads,
+ * so choosing an agent here changes where the composer sends too — the two
+ * surfaces stay in agreement through the store rather than through shared code.
+ */
+
+import { type TargetData, TERMINAL_CLIS, type TerminalCli } from '@inkeep/open-knowledge-core';
+import { t } from '@lingui/core/macro';
+import { useState } from 'react';
+import type { TerminalCliRow } from '@/components/handoff/AgentSplitButton';
+import { useTerminalLaunch } from '@/components/handoff/TerminalLaunchContext';
+import { useInstalledAgents } from '@/components/handoff/useInstalledAgents';
+import { isDesktopTargetEnabled, isInAppAgentEnabled } from '@/lib/acp/agent-visibility';
+import { useEnabledOverrides } from '@/lib/acp/enabled-agents';
+import {
+ enabledDesktopTargets,
+ enabledTerminalClis,
+ resolveLauncherSelection,
+} from '@/lib/acp/launcher-selection';
+import {
+ pickEffectiveDefaultAgent,
+ type RegisteredAgent,
+ registerAgent,
+ useDefaultRegisteredAgent,
+ useRegisteredAgents,
+} from '@/lib/acp/registered-agents';
+import { VISIBLE_TARGETS } from '@/lib/handoff/targets';
+import {
+ IN_APP_THREAD_ID,
+ loadStickyAgent,
+ saveStickyAgent,
+ terminalCliId,
+} from '@/lib/unified-agent-store';
+
+export interface CommentAgentPicker {
+ /** In-app agent thread is the resolved target. */
+ isThreadSelected: boolean;
+ /** The in-app agent a send would launch, when `isThreadSelected`. */
+ threadAgent: RegisteredAgent | null;
+ /** The docked-terminal CLI a send would use, else null. */
+ cli: TerminalCli | null;
+ /** The external app a send would deep-link into, else null. */
+ target: TargetData | null;
+ /** True while the install probe hasn't answered — "detecting" vs "none". */
+ probePending: boolean;
+ /** Props to spread onto `AgentSplitButton`. */
+ rows: {
+ installedTargets: readonly TargetData[];
+ selectedTargetId: TargetData['id'] | null;
+ onSelectTarget: (target: TargetData) => void;
+ terminals: readonly TerminalCliRow[] | undefined;
+ threadAgents: readonly {
+ key: string;
+ id: string;
+ name: string;
+ iconUrl?: string;
+ selected: boolean;
+ onSelect: () => void;
+ }[];
+ };
+}
+
+export function useCommentAgentPicker(): CommentAgentPicker {
+ const overrides = useEnabledOverrides();
+ const terminalLaunch = useTerminalLaunch();
+ const { states } = useInstalledAgents();
+ const registeredAgents = useRegisteredAgents();
+ const defaultRegisteredAgent = useDefaultRegisteredAgent();
+ // Mirrors the composer: the pick is applied immediately (and persisted), and
+ // this local copy is what re-renders the checkmark.
+ const [selectedId, setSelectedId] = useState<string | null>(() => loadStickyAgent());
+
+ const enabledThreadAgents = registeredAgents.filter((agent) =>
+ isInAppAgentEnabled(overrides, agent.source, agent.id, true, agent.supported),
+ );
+ const threadAgent = pickEffectiveDefaultAgent(enabledThreadAgents, defaultRegisteredAgent);
+
+ const selection = resolveLauncherSelection({
+ sticky: selectedId,
+ effectiveThreadAgent: threadAgent,
+ enabledClis:
+ terminalLaunch !== null ? enabledTerminalClis(overrides, terminalLaunch.installedClis) : [],
+ enabledDesktopTargets: enabledDesktopTargets(overrides),
+ installedClis: terminalLaunch?.installedClis ?? {},
+ terminalAvailable: terminalLaunch !== null,
+ threadsAvailable: true,
+ desktopSelectable: true,
+ });
+
+ const isThreadSelected = selection.kind === 'thread';
+ const cli = selection.kind === 'cli' ? selection.cli : null;
+ const target =
+ selection.kind === 'desktop'
+ ? (VISIBLE_TARGETS.find((entry) => entry.id === selection.target) ?? null)
+ : null;
+
+ // Every ENABLED app, not only the install-detected ones — an enabled but
+ // uninstalled agent still lists and routes to its installer on launch.
+ const installedTargets = VISIBLE_TARGETS.filter((entry) =>
+ isDesktopTargetEnabled(overrides, entry.id),
+ );
+
+ const select = (id: string): void => {
+ setSelectedId(id);
+ saveStickyAgent(id);
+ };
+
+ const terminals: TerminalCliRow[] | undefined =
+ terminalLaunch !== null
+ ? enabledTerminalClis(overrides, terminalLaunch.installedClis).map((entry) => {
+ const { displayName } = TERMINAL_CLIS[entry];
+ return {
+ cli: entry,
+ label: displayName,
+ // Accessible name carries "CLI" so it's distinguishable from a
+ // same-named Desktop row (WCAG 2.5.3).
+ ariaLabel: t`${displayName} CLI`,
+ selected: cli === entry,
+ onSelect: () => select(terminalCliId(entry)),
+ };
+ })
+ : undefined;
+
+ return {
+ isThreadSelected,
+ threadAgent,
+ cli,
+ target,
+ probePending: VISIBLE_TARGETS.some((entry) => states[entry.id]?.installed == null),
+ rows: {
+ installedTargets,
+ selectedTargetId: cli !== null ? null : (target?.id ?? null),
+ onSelectTarget: (entry) => select(entry.id),
+ terminals,
+ threadAgents: enabledThreadAgents.map((agent) => ({
+ key: `${agent.source}:${agent.id}`,
+ id: agent.id,
+ name: agent.name,
+ ...(agent.iconUrl !== undefined ? { iconUrl: agent.iconUrl } : {}),
+ selected:
+ isThreadSelected &&
+ threadAgent !== null &&
+ threadAgent.source === agent.source &&
+ threadAgent.id === agent.id,
+ onSelect: () => {
+ // Picking a specific agent re-registers it as the default a send
+ // launches, then selects thread mode.
+ registerAgent(agent);
+ select(IN_APP_THREAD_ID);
+ },
+ })),
+ },
+ };
+}
diff --git a/packages/app/src/comments/use-comment-delivery.ts b/packages/app/src/comments/use-comment-delivery.ts
new file mode 100644
index 000000000..6cd7ea165
--- /dev/null
+++ b/packages/app/src/comments/use-comment-delivery.ts
@@ -0,0 +1,169 @@
+/**
+ * Installs the store's delivery seam: how a queued comment actually reaches an
+ * agent.
+ *
+ * Delivery reuses the SAME plumbing and the SAME target set as the "Ask AI"
+ * composer — an in-app agent thread, the docked terminal, or a deep link into
+ * an external app — because commenting and asking are meant to be one muscle
+ * memory. It also means the passage is fitted to each target's transport and
+ * budget by `buildComposerHandoffInput` (a deep link has a URL length limit),
+ * which is why the server hands over ingredients rather than a finished prompt.
+ *
+ * Mount once where the queue lives; it registers on mount and clears on unmount.
+ */
+
+import { t } from '@lingui/core/macro';
+import { toast } from 'sonner';
+import { useTerminalLaunch } from '@/components/handoff/TerminalLaunchContext';
+import {
+ buildComposerHandoffInput,
+ openInstallUrl,
+ startAgentThreadForInput,
+ useHandoffDispatch,
+} from '@/components/handoff/useHandoffDispatch';
+import { useInstalledAgents } from '@/components/handoff/useInstalledAgents';
+import { isInAppAgentEnabled } from '@/lib/acp/agent-visibility';
+import { useEnabledOverrides } from '@/lib/acp/enabled-agents';
+import {
+ enabledDesktopTargets,
+ enabledTerminalClis,
+ resolveLauncherSelection,
+} from '@/lib/acp/launcher-selection';
+import {
+ pickEffectiveDefaultAgent,
+ useDefaultRegisteredAgent,
+ useRegisteredAgents,
+} from '@/lib/acp/registered-agents';
+import { VISIBLE_TARGETS } from '@/lib/handoff/targets';
+import { loadStickyAgent } from '@/lib/unified-agent-store';
+import { openAgentSettings } from '@/lib/use-settings-route';
+import { useWorkspace } from '@/lib/use-workspace';
+import { docNameToRelativePath } from '@/lib/workspace-paths';
+import { composeCommentBatchInstruction, toCommentBatchItem } from './comment-chips';
+import type { DispatchPayload } from './comments-client';
+import type { BatchPreparedItem, ComposeDispatch } from './store';
+
+/**
+ * The instruction handed to the agent. The comment body is the request; the
+ * passage rides as the selection so the composer can transport it per target.
+ *
+ * When the anchor was lost we say so explicitly. Without that line an agent
+ * that cannot find the passage may "fix" a different occurrence, or re-add text
+ * a rewrite deliberately removed — the silent-wrong-target failure the whole
+ * anchoring design exists to prevent.
+ */
+function composeInstruction(payloads: readonly DispatchPayload[]): string {
+ return composeCommentBatchInstruction(payloads.map(toCommentBatchItem), '');
+}
+
+/**
+ * The hand-off a comment batch takes to reach an agent — a fresh turn on the
+ * user's preferred target.
+ *
+ * RETURNED rather than registered into the store. As an installed slot it was
+ * only live while the Comments tab was mounted, so a send from anywhere else
+ * silently did nothing; a caller that holds the function cannot have that
+ * problem, and the store keeps no mutable global to reason about.
+ */
+export function useCommentDispatch(): ComposeDispatch {
+ const workspace = useWorkspace();
+ const overrides = useEnabledOverrides();
+ const { dispatch } = useHandoffDispatch();
+ const terminalLaunch = useTerminalLaunch();
+ const { states } = useInstalledAgents();
+ const registeredAgents = useRegisteredAgents();
+ const defaultRegisteredAgent = useDefaultRegisteredAgent();
+
+ const enabledAgents = registeredAgents.filter((agent) =>
+ isInAppAgentEnabled(overrides, agent.source, agent.id, true, agent.supported),
+ );
+ const defaultThreadAgent = pickEffectiveDefaultAgent(enabledAgents, defaultRegisteredAgent);
+
+ // One selection decision, enablement-aware — the same resolver the Ask AI
+ // composer, create composer, and sessions dock share, so a disabled agent
+ // is never what a comment launches either.
+ const selection = resolveLauncherSelection({
+ sticky: loadStickyAgent(),
+ effectiveThreadAgent: defaultThreadAgent,
+ enabledClis:
+ terminalLaunch !== null ? enabledTerminalClis(overrides, terminalLaunch.installedClis) : [],
+ enabledDesktopTargets: enabledDesktopTargets(overrides),
+ installedClis: terminalLaunch?.installedClis ?? {},
+ terminalAvailable: terminalLaunch !== null,
+ threadsAvailable: true,
+ desktopSelectable: true,
+ });
+
+ return async (items: readonly BatchPreparedItem[]) => {
+ const payloads = items.map((item) => item.payload);
+ if (payloads.length === 0) return false;
+ // Project scope: a batch spans documents, so no single doc leads. Each
+ // comment names its own file inside the composed instruction, and every
+ // touched doc rides as a mention.
+ const input = buildComposerHandoffInput({
+ docName: null,
+ workspace,
+ instruction: composeInstruction(payloads),
+ mentions: [...new Set(payloads.map((p) => docNameToRelativePath(p.docName)))],
+ });
+ if (input === null) {
+ toast.error(t`Couldn't send your comments — the workspace isn't ready.`);
+ return false;
+ }
+
+ // One in-app agent thread for the whole batch.
+ if (selection.kind === 'thread') {
+ startAgentThreadForInput(
+ input,
+ defaultThreadAgent !== null
+ ? { agent: { source: defaultThreadAgent.source, id: defaultThreadAgent.id } }
+ : undefined,
+ );
+ return true;
+ }
+
+ // Docked terminal: hand the composed prompt to the selected CLI.
+ if (selection.kind === 'cli' && terminalLaunch !== null) {
+ try {
+ terminalLaunch.launchInTerminal(input, selection.cli);
+ return true;
+ } catch {
+ toast.error(t`Couldn't open the terminal — the comments stay queued.`);
+ return false;
+ }
+ }
+
+ // Nothing enabled to ask with. Send the user where they can enable
+ // something — the same destination the sessions dock picks in this state —
+ // rather than swallowing a click that looked like a send.
+ if (selection.kind === 'none') {
+ toast.info(t`No agent is set up yet — opening Configure agents.`);
+ openAgentSettings();
+ return false;
+ }
+ // A CLI was selected but the terminal host is not mounted (web, or a build
+ // without pty). Previously this fell through to a bare `return false`.
+ if (selection.kind === 'cli') {
+ toast.error(t`The terminal isn't available here — the comments stay queued.`);
+ return false;
+ }
+ if (selection.kind !== 'desktop') {
+ toast.error(t`Couldn't work out where to send the comments — they stay queued.`);
+ return false;
+ }
+ const target = VISIBLE_TARGETS.find((entry) => entry.id === selection.target) ?? null;
+ if (target === null) {
+ toast.error(t`That app isn't available — the comments stay queued.`);
+ return false;
+ }
+ // Enabled but not installed: route to the installer rather than a
+ // deep-link that would fail. Not a delivery, so the thread stays queued.
+ if (states[target.id]?.installed !== true) {
+ void openInstallUrl(target);
+ toast.info(t`${target.displayName} isn't installed yet — opening its download page.`);
+ return false;
+ }
+ const outcome = await dispatch(target.id, input);
+ return outcome.ok;
+ };
+}
diff --git a/packages/app/src/components/BottomComposer.dom.test.tsx b/packages/app/src/components/BottomComposer.dom.test.tsx
index 98058d797..d225bb4b6 100644
--- a/packages/app/src/components/BottomComposer.dom.test.tsx
+++ b/packages/app/src/components/BottomComposer.dom.test.tsx
@@ -81,6 +81,20 @@ vi.doMock('@/components/ui/dropdown-menu', () => ({
{children}
</button>
),
+ // The `+` context menu's Queue row is a checkbox item (attach / detach), so
+ // the passthrough has to cover it too or every test in this file dies on a
+ // missing export rather than on anything it means to assert.
+ DropdownMenuCheckboxItem: ({ children, disabled, checked, ...props }: MenuChild) => (
+ <button
+ type="button"
+ role="menuitemcheckbox"
+ aria-checked={checked === true}
+ disabled={disabled}
+ {...props}
+ >
+ {children}
+ </button>
+ ),
DropdownMenuLabel: ({ children, ...props }: MenuChild) => <div {...props}>{children}</div>,
DropdownMenuSeparator: () => <hr data-testid="menu-separator" />,
}));
diff --git a/packages/app/src/components/BottomComposer.tsx b/packages/app/src/components/BottomComposer.tsx
index 6a6ccac1e..af8ca3a7b 100644
--- a/packages/app/src/components/BottomComposer.tsx
+++ b/packages/app/src/components/BottomComposer.tsx
@@ -30,6 +30,20 @@ import { Trans, useLingui } from '@lingui/react/macro';
import { ChevronDown, Loader2, TextQuote, X } from 'lucide-react';
import { type ReactNode, useEffect, useRef, useState } from 'react';
import { toast } from 'sonner';
+import {
+ composeCommentBatchInstruction,
+ QueuedCommentsChip,
+ QueuedCommentsList,
+ toCommentBatchItem,
+ useQueuedComments,
+ useSelectedCommentCount,
+} from '@/comments/comment-chips';
+import {
+ type BatchPreparedItem,
+ dispatchComments,
+ selectAllQueued,
+ subscribeCommentPosted,
+} from '@/comments/store';
import { RegisteredAgentIcon } from '@/components/acp/RegisteredAgentIcon';
import { ComposerContextChips } from '@/components/ComposerContextChips';
import { AgentSplitButton } from '@/components/handoff/AgentSplitButton';
@@ -112,7 +126,7 @@ function markdownRelativePathStem(path: string): string | null {
* from the ProseMirror body (a contentEditable root), so this is deliberately
* NARROWER than `isEditableShortcutTarget` — only native INPUT/TEXTAREA/SELECT
* are excluded, so ⌘L never steals a caret out of a real form field (e.g. the
- * rename input, a search box). Mirrors `EditWithAiBubbleButton`'s helper.
+ * rename input, a search box).
*/
function isNativeTextControl(target: EventTarget | null): boolean {
if (!(target instanceof HTMLElement)) return false;
@@ -438,6 +452,23 @@ export function BottomComposer({
// the top row never duplicates an inline reference. Reset on dispatch/clear.
const [touchedFiles, setTouchedFiles] = useState<readonly string[]>([]);
const [dismissedFiles, setDismissedFiles] = useState<ReadonlySet<string>>(() => new Set());
+ // Comments queued from the selection composer — they ride this composer's
+ // chip row and its send button.
+ const queuedComments = useQueuedComments();
+ // The count that matters is what a send would carry — the CHECKED subset.
+ // Unchecking every item leaves the queue non-empty but the send empty, so
+ // gate the send button on this too rather than on the raw queue length.
+ const selectedCommentCount = useSelectedCommentCount();
+ const [commentsExpanded, setCommentsExpanded] = useState(false);
+ // Attached = "part of THIS message", and OFF until asked for. An attached queue
+ // takes over the send button and the placeholder, so attaching by itself would
+ // let a comment left anywhere in the project repoint a composer the user opened
+ // for an unrelated question. The `+` menu's toggle is the way in, and queueing
+ // another comment does not flip it — a default that re-asserts itself is not a
+ // default. Dispatching the batch is what the Queue panel's own send is for.
+ const [commentsAttached, setCommentsAttached] = useState(false);
+ const queueSize = queuedComments.length;
+ const hasQueuedComments = selectedCommentCount > 0 && commentsAttached;
// The current inline-mention `@path` set, pushed up from the editor — used to
// dedup the top row against inline mentions (the live invariant).
const [inlineMentions, setInlineMentions] = useState<readonly string[]>([]);
@@ -502,6 +533,19 @@ export function BottomComposer({
useEffect(() => {
if (liveFrontmatterSelection) setPinnedSelection(liveFrontmatterSelection);
}, [liveFrontmatterSelection]);
+ // A pinned selection deliberately outlives the editor selection so it can
+ // survive clicking away into the composer. Filing a comment is the one case
+ // where that is wrong: the passage now rides the batch as that comment's
+ // quote, and leaving it pinned would send the same words again as an
+ // unrelated in-scope selection.
+ useEffect(
+ () =>
+ subscribeCommentPosted(() => {
+ setPinnedSelection(null);
+ setSelectionExpanded(false);
+ }),
+ [],
+ );
// Explicit pick this session wins; otherwise the sticky preference; otherwise
// first-installed. `selectedId` stays null until the user picks so a
@@ -545,7 +589,10 @@ export function BottomComposer({
// is enough context to hand off).
const canSend =
!pending &&
- (!isEmpty || pinnedSelection !== null) &&
+ // Queued comments are enough on their own: each carries its own body, and
+ // an untyped batch still has a default instruction. Requiring typed text
+ // would leave the send button dead with a full queue.
+ (!isEmpty || pinnedSelection !== null || hasQueuedComments) &&
(isTerminalSelected || resolvedTarget !== null || isThreadSelected);
// Picker options for the split button's menu. Desktop rows are the agents the
@@ -582,14 +629,22 @@ export function BottomComposer({
})
: undefined;
- // Rotating example prompts shown as an animated placeholder while empty.
- const suggestions = [
- t`Research the extinction of flightless birds`,
- t`Condense my AGENTS.md file to less than 40k characters`,
- t`Create a new spec file for my user story`,
- t`Summarize everything I changed this week`,
- ];
- const suggestion = useRotatingSuggestion(suggestions, !reduced && isEmpty && !dismissed);
+ // Rotating example prompts shown as an animated placeholder while empty. With
+ // comments queued the placeholder stops rotating and states what sending will
+ // do — that IS the default instruction the batch carries when nothing is
+ // typed, so it should be visible rather than implicit.
+ const suggestions = hasQueuedComments
+ ? [t`Work through these comments`]
+ : [
+ t`Research the extinction of flightless birds`,
+ t`Condense my AGENTS.md file to less than 40k characters`,
+ t`Create a new spec file for my user story`,
+ t`Summarize everything I changed this week`,
+ ];
+ const suggestion = useRotatingSuggestion(
+ suggestions,
+ !reduced && isEmpty && !dismissed && !hasQueuedComments,
+ );
// Stickiness persists on PICK, not gated to submit: the
// moment the user chooses an agent/CLI in the dropdown it becomes the default
@@ -627,6 +682,11 @@ export function BottomComposer({
// sticky-dismissed tracking (and `inlineMentions` follows the cleared editor).
setTouchedFiles([]);
setDismissedFiles(new Set());
+ // The queue detaches with the rest of the draft's context. Left on, the next
+ // message would silently carry whatever had been queued since — the same
+ // surprise as attaching by default, just deferred a send.
+ setCommentsAttached(false);
+ setCommentsExpanded(false);
// Clear the SHARED draft too so a sent prompt does not reappear in the
// create-screen hero (or on the next navigation back to a doc).
clearComposerDraft();
@@ -636,14 +696,39 @@ export function BottomComposer({
// folder / project scope. Surfaces the rare null-workspace case, routes a CLI
// pick to the docked terminal (else the installed-agent deep-link), and clears
// the draft on completion.
- const dispatchComposed = (input: ReturnType<typeof buildComposerHandoffInput>) => {
+ //
+ // Resolves to whether the prompt actually reached an agent. The queued-comment
+ // send is the caller that needs the answer: a batch reported as delivered is
+ // resolved and dropped from the queue, so a branch that hands off nothing —
+ // no resolved target, a terminal that refused to open, an uninstalled agent
+ // routed to its download page, a deep-link dispatch that came back not-ok —
+ // has to say so rather than let the comments close on a send that never
+ // happened.
+ const dispatchComposed = async (
+ input: ReturnType<typeof buildComposerHandoffInput>,
+ /**
+ * Clear the composer once the prompt is away. True for a plain send, where
+ * this function IS the send.
+ *
+ * The queued-comment path passes false, because there this is only the
+ * hand-off — the send is not finished until `dispatchComments` reports what
+ * actually shipped, and that caller owns the clear. Two owners meant the
+ * clear ran twice on that path, and worse, the not-installed branch below
+ * cleared while returning false: the typed instruction was thrown away on a
+ * batch that never left the queue.
+ */
+ clearOnSuccess = true,
+ ): Promise<boolean> => {
+ const clearIfOwned = () => {
+ if (clearOnSuccess) clearComposer();
+ };
if (input === null) {
// Defensive: `buildComposerHandoffInput` returns null only when the
// workspace hasn't resolved yet, and the composer normally only shows once
// a doc / folder (hence a workspace) is open — so this is rarely reachable.
// Surface a toast rather than a silent no-op if it is.
toast.error(t`Couldn't send your prompt — please try again.`);
- return;
+ return false;
}
// In-app agent thread: open a server-hosted thread with the composed prompt
// (like "Open with AI → Start an agent"), then clear. Works on every host.
@@ -657,8 +742,8 @@ export function BottomComposer({
: undefined,
);
recordOnboardingAskedAi();
- clearComposer();
- return;
+ clearIfOwned();
+ return true;
}
// CLI mode: hand the composed prompt to the docked terminal for the selected
// CLI (like Open with AI) and clear. No deep-link dispatch. Stickiness already
@@ -670,21 +755,27 @@ export function BottomComposer({
terminalLaunch.launchInTerminal(input, selectedCli);
} catch {
toast.error(t`Couldn't open the terminal — please try again.`);
- return;
+ return false;
}
recordOnboardingAskedAi();
- clearComposer();
- return;
+ clearIfOwned();
+ return true;
+ }
+ // Nothing resolved to send to. `submit` gates on `canSend` before reaching
+ // here, so this is the defence-in-depth path for callers that don't (the
+ // agent-picker rows dispatch directly) — say why rather than swallowing it.
+ if (resolvedTarget === null) {
+ toast.error(t`No agent is set up yet — pick one from the send menu.`);
+ return false;
}
- if (resolvedTarget === null) return;
// An enabled-but-not-installed Desktop agent routes to its installer
// rather than a failing deep-link dispatch (the toggle can enable an agent
// the user hasn't installed yet).
if (states[resolvedTarget.id]?.installed !== true) {
void openInstallUrl(resolvedTarget);
toast.info(t`${resolvedTarget.displayName} isn't installed yet — opening its download page.`);
- clearComposer();
- return;
+ clearIfOwned();
+ return false;
}
setPending(true);
// dispatchHandoff never throws and toasts success/error itself; on resolve
@@ -692,14 +783,16 @@ export function BottomComposer({
// step records only on a confirmed-successful outcome — a failed handoff
// ({ ok: false }: agent offline, install error) must not check it off, matching
// the success-gated terminal path above.
- void dispatch(resolvedTarget.id, input)
- .then((outcome) => {
- if (outcome.ok) recordOnboardingAskedAi();
- })
- .finally(() => {
- setPending(false);
- clearComposer();
- });
+ //
+ // `Promise.finally`, not `try`/`finally`: React Compiler cannot lower a
+ // TryStatement with no catch clause and fails the build on it, so the
+ // clean-up-regardless has to ride the promise rather than the syntax.
+ const outcome = await dispatch(resolvedTarget.id, input).finally(() => {
+ setPending(false);
+ clearIfOwned();
+ });
+ if (outcome.ok) recordOnboardingAskedAi();
+ return outcome.ok;
};
// Compose the current draft (instruction + chips + pinned selection) into a
@@ -765,8 +858,78 @@ export function BottomComposer({
};
const submit = () => {
+ // The gate runs FIRST, for the queued path too. `canSend`'s content clause
+ // already counts an attached queue as content, so this does not reinstate
+ // the "type something first" requirement a batch is exempt from — it just
+ // stops the queued send from skipping the not-pending and has-a-target
+ // checks. Those were being caught downstream by `dispatchInFlight` and a
+ // toast in `dispatchComposed`, which is two unrelated mechanisms standing in
+ // for one guard.
if (!canSend) return;
- dispatchComposed(composeCurrentInput());
+ // Queued comments take over the send: the typed text becomes the shared
+ // instruction for the batch, and every queued comment rides along with its
+ // own doc + passage. One send, one agent turn.
+ if (hasQueuedComments) {
+ void submitQueuedComments();
+ return;
+ }
+ void dispatchComposed(composeCurrentInput());
+ };
+
+ /**
+ * Dispatch the queued comments as one turn. The server re-finds each anchor
+ * first (so a passage that moved is still found, and one that is gone is
+ * flagged rather than silently retargeted), then the batch resolves only if
+ * the hand-off actually happened.
+ *
+ * Re-entrant sends (a second Enter before the first batch completes) are held
+ * off by `dispatchQueueAsBatch` itself, not here — the queue-panel Send drains
+ * the same queue and needs the same guard.
+ */
+ const submitQueuedComments = async () => {
+ const { instruction, mentions } = inputRef.current?.getContent() ?? {
+ instruction: '',
+ mentions: [],
+ };
+ const shipped = await dispatchComments({
+ compose: async (items: readonly BatchPreparedItem[]) => {
+ const input = buildComposerHandoffInput({
+ // Project scope: a batch spans documents, so no single doc leads. Each
+ // comment names its own file in the composed instruction.
+ docName: null,
+ workspace,
+ instruction: composeCommentBatchInstruction(
+ items.map((item) => toCommentBatchItem(item.payload)),
+ instruction,
+ // The pinned selection is the one chip the batch cannot reconstruct —
+ // a passage that belongs to no comment. It used to render above the
+ // send and then be dropped by it.
+ pinnedSelection
+ ? { docName: pinnedSelection.docName, markdown: pinnedSelection.markdown }
+ : undefined,
+ ),
+ // Every touched doc, not only the batch's: a file chip or `@`-mention
+ // added while drafting is context for THIS send too. Deduped, so a doc
+ // that is both commented on and chipped is named once.
+ mentions: [
+ ...new Set([
+ ...items.map((item) => docNameToRelativePath(item.payload.docName)),
+ ...fileChips,
+ ...mentions,
+ ]),
+ ],
+ });
+ if (input === null) {
+ toast.error(t`Couldn't send your comments — please try again.`);
+ return false;
+ }
+ // `false`: this is the hand-off, not the send. `dispatchComments` decides
+ // what shipped, and the clear below is keyed off that — so a batch that
+ // fails to leave the queue keeps the instruction you typed for it.
+ return dispatchComposed(input, false);
+ },
+ });
+ if (shipped.length > 0) clearComposer();
};
// Dismissed: render nothing (the host shows the footer reopen badge). The
@@ -914,6 +1077,47 @@ export function BottomComposer({
) : null}
</>
) : null}
+ {/* Queued comments ride the same chip row as files + the selection pill:
+ the queue lives in the composer you already use, not a separate
+ dispatch surface. The chip is the attach control too, so it renders on
+ the RAW queue rather than on what a send would carry — nothing else
+ would say a queue exists while the batch is still detached. */}
+ {/* Gated here as well as inside the chip: `ComposerContextChips` decides
+ whether to render its row at all by counting children, and an element
+ that returns null still counts as one. An empty queue has to
+ contribute NO child, or the chip row appears as an empty strip. */}
+ {queueSize > 0 && (
+ <>
+ <QueuedCommentsChip
+ // Attached, the count is what a SEND carries, so unchecking an item
+ // moves it. Detached the chip shows no number, so the raw queue is
+ // what decides it renders at all.
+ count={hasQueuedComments ? selectedCommentCount : queueSize}
+ // `hasQueuedComments`, not `commentsAttached`: unchecking the LAST
+ // item means nothing rides this message, which is the detached
+ // state however it was reached. Keying on the flag alone left a
+ // countless chip above a list of unchecked rows — attached in name,
+ // carrying nothing.
+ attached={hasQueuedComments}
+ expanded={commentsExpanded}
+ onAttach={() => {
+ setCommentsAttached(true);
+ // Deselection is sticky, so re-attaching has to re-check the
+ // queue — otherwise this puts an empty batch on the message and
+ // the chip bounces straight back to detached.
+ selectAllQueued();
+ }}
+ onToggleExpanded={() => setCommentsExpanded((open) => !open)}
+ onDismiss={() => {
+ setCommentsAttached(false);
+ setCommentsExpanded(false);
+ }}
+ />
+ {hasQueuedComments && commentsExpanded && (
+ <QueuedCommentsList threads={queuedComments} />
+ )}
+ </>
+ )}
</ComposerContextChips>
<div className="flex items-end gap-2">
<div className="relative flex-1">
diff --git a/packages/app/src/components/ComposerAddContextMenu.dom.test.tsx b/packages/app/src/components/ComposerAddContextMenu.dom.test.tsx
new file mode 100644
index 000000000..eacf06a7b
--- /dev/null
+++ b/packages/app/src/components/ComposerAddContextMenu.dom.test.tsx
@@ -0,0 +1,205 @@
+/**
+ * The composer's `+` menu.
+ *
+ * What it exists to fix: dismissing the queued-comments chip had no inverse, so
+ * "not part of this message" was a one-way door until you happened to queue
+ * another comment. These pin the door open in both directions, and pin the two
+ * states where the row must NOT act — nothing queued, and already attached —
+ * since both would otherwise read as a button that silently does nothing.
+ */
+
+import { cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { afterEach, describe, expect, test } from 'vitest';
+import { ComposerAddContextMenu } from './ComposerAddContextMenu';
+
+afterEach(() => cleanup());
+
+function renderMenu(
+ props: Partial<{
+ queueCount: number;
+ queueAttached: boolean;
+ compact: boolean;
+ onAddQueue: () => void;
+ onRemoveQueue: () => void;
+ }> = {},
+) {
+ return render(
+ <ComposerAddContextMenu
+ queueCount={props.queueCount ?? 3}
+ queueAttached={props.queueAttached ?? false}
+ compact={props.compact ?? false}
+ onAddQueue={props.onAddQueue ?? (() => {})}
+ onRemoveQueue={props.onRemoveQueue ?? (() => {})}
+ />,
+ );
+}
+
+describe('the composer + menu', () => {
+ test('is present with nothing attached — it is how you attach', async () => {
+ // Gating the `+` on there being something to add would hide it exactly when
+ // someone goes looking for it.
+ renderMenu({ queueCount: 0 });
+ expect(screen.getByTestId('composer-add-context')).toBeTruthy();
+ });
+
+ test('opens to a Queue row that reports the count', async () => {
+ const user = userEvent.setup();
+ renderMenu({ queueCount: 3 });
+
+ await user.click(screen.getByTestId('composer-add-context'));
+ const row = await screen.findByTestId('composer-add-context-queue');
+ expect(row.textContent).toMatch(/3 comments/);
+ });
+
+ test('clicking Queue attaches it', async () => {
+ const user = userEvent.setup();
+ let added = 0;
+ renderMenu({
+ onAddQueue: () => {
+ added += 1;
+ },
+ });
+
+ await user.click(screen.getByTestId('composer-add-context'));
+ await user.click(await screen.findByTestId('composer-add-context-queue'));
+ expect(added).toBe(1);
+ });
+
+ test('an empty queue leaves the row inert and says why', async () => {
+ const user = userEvent.setup();
+ let added = 0;
+ renderMenu({
+ queueCount: 0,
+ onAddQueue: () => {
+ added += 1;
+ },
+ });
+
+ await user.click(screen.getByTestId('composer-add-context'));
+ const row = await screen.findByTestId('composer-add-context-queue');
+ // Visible but disabled: a missing row reads as a broken menu to someone who
+ // opened it specifically to add comments.
+ expect(row.getAttribute('data-disabled')).not.toBeNull();
+ expect(row.textContent).toMatch(/nothing queued/i);
+ await user.click(row);
+ expect(added).toBe(0);
+ });
+
+ test('the menu is wide enough that a row does not wrap', async () => {
+ // `DropdownMenuContent` sizes to `--radix-dropdown-menu-trigger-width` with
+ // a `min-w-32` floor. Against this icon trigger that is 8rem, which wrapped
+ // "Queue (5 comments)" onto two lines. `w-60` also matches the agent
+ // settings menu sharing that action bar.
+ const user = userEvent.setup();
+ renderMenu({ queueCount: 5 });
+
+ await user.click(screen.getByTestId('composer-add-context'));
+ const content = await screen.findByTestId('composer-add-context-menu');
+ expect(content.className).toContain('w-60');
+ // The bug was the trigger-width sizing, and that is what must be gone. The
+ // `min-w-32` floor survives (different tailwind-merge group) and is inert
+ // at 15rem — leaving it in place is correct, not a missed override.
+ expect(content.className).not.toContain('--radix-dropdown-menu-trigger-width');
+ });
+
+ test('compact sizes the trigger to a dense action bar', async () => {
+ // The agent thread's bar is `h-6` controls; the default `size-8` button
+ // towered over the settings trigger beside it.
+ const { rerender } = renderMenu({ compact: true });
+ expect(screen.getByTestId('composer-add-context').className).toContain('h-6');
+
+ rerender(
+ <ComposerAddContextMenu
+ queueCount={3}
+ queueAttached={false}
+ compact={false}
+ onAddQueue={() => {}}
+ />,
+ );
+ // The composer row is sized to a full-height input — not h-6 there.
+ expect(screen.getByTestId('composer-add-context').className).toContain('size-8');
+ });
+
+ test('a detach handler turns the row into a real checkbox', async () => {
+ // `menuitemcheckbox` + `aria-checked` is what makes the state reachable to
+ // a screen reader — the Switch beside it is decorative and aria-hidden, so
+ // the role is the whole accessibility story here.
+ const user = userEvent.setup();
+ renderMenu({ queueAttached: true, onRemoveQueue: () => {} });
+
+ await user.click(screen.getByTestId('composer-add-context'));
+ const row = await screen.findByTestId('composer-add-context-queue');
+ expect(row.getAttribute('role')).toBe('menuitemcheckbox');
+ expect(row.getAttribute('aria-checked')).toBe('true');
+ });
+
+ test('toggling off detaches, toggling on re-attaches', async () => {
+ const user = userEvent.setup();
+ let added = 0;
+ let removed = 0;
+ const { rerender } = renderMenu({
+ queueAttached: true,
+ onAddQueue: () => {
+ added += 1;
+ },
+ onRemoveQueue: () => {
+ removed += 1;
+ },
+ });
+
+ await user.click(screen.getByTestId('composer-add-context'));
+ await user.click(await screen.findByTestId('composer-add-context-queue'));
+ expect(removed).toBe(1);
+ expect(added).toBe(0);
+
+ rerender(
+ <ComposerAddContextMenu
+ queueCount={3}
+ queueAttached={false}
+ compact={false}
+ onAddQueue={() => {
+ added += 1;
+ }}
+ onRemoveQueue={() => {
+ removed += 1;
+ }}
+ />,
+ );
+ // The menu stays open through a toggle (settings-menu parity), so the row
+ // is still reachable without reopening.
+ await user.click(await screen.findByTestId('composer-add-context-queue'));
+ expect(added).toBe(1);
+ expect(removed).toBe(1);
+ });
+
+ test('an empty queue cannot be toggled on', async () => {
+ const user = userEvent.setup();
+ let added = 0;
+ renderMenu({
+ queueCount: 0,
+ queueAttached: true,
+ onAddQueue: () => {
+ added += 1;
+ },
+ onRemoveQueue: () => {},
+ });
+
+ await user.click(screen.getByTestId('composer-add-context'));
+ const row = await screen.findByTestId('composer-add-context-queue');
+ // Attached-but-empty must read as OFF: a switch promising an attachment
+ // that carries nothing is worse than no switch.
+ expect(row.getAttribute('aria-checked')).toBe('false');
+ expect(row.getAttribute('data-disabled')).not.toBeNull();
+ await user.click(row);
+ expect(added).toBe(0);
+ });
+
+ test('the trigger says what it does, not what it looks like', async () => {
+ // "Plus" / "Add" alone leaves a screen-reader user guessing what is added.
+ renderMenu();
+ expect(screen.getByTestId('composer-add-context').getAttribute('aria-label')).toMatch(
+ /add context to this message/i,
+ );
+ });
+});
diff --git a/packages/app/src/components/ComposerAddContextMenu.tsx b/packages/app/src/components/ComposerAddContextMenu.tsx
new file mode 100644
index 000000000..da8cc1171
--- /dev/null
+++ b/packages/app/src/components/ComposerAddContextMenu.tsx
@@ -0,0 +1,137 @@
+/**
+ * The composer's `+` — add context to this message.
+ *
+ * For composers with NO context-chip row. Where a row exists (the Ask AI
+ * composer), the chip itself is the toggle: it already has to render to say a
+ * queue exists, so a second control behind a menu was one click deep, invisible
+ * until opened, and a duplicate of the ✕ it sat above. An agent thread's
+ * composer is a plain text field with nowhere to put a chip, which is what this
+ * menu is for.
+ *
+ * Opened as a menu rather than a bare button because context sources will grow
+ * past the comment queue, and a row of one button per possible source stops
+ * being a summary of what IS attached.
+ *
+ * Attaching is deliberately NOT sending: the item puts the batch on the message
+ * so the composer's own send carries it.
+ *
+ * The row is a toggle. It once had a second, action-only variant for a host
+ * that could not undo the add; nothing ever rendered it, so it is gone rather
+ * than kept warm for a caller that may never arrive.
+ */
+
+import { Plural, useLingui } from '@lingui/react/macro';
+import { Plus } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import {
+ DropdownMenu,
+ DropdownMenuCheckboxItem,
+ DropdownMenuContent,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { Switch } from '@/components/ui/switch';
+import { cn } from '@/lib/utils';
+
+export function ComposerAddContextMenu({
+ queueCount,
+ queueAttached,
+ compact = false,
+ onAddQueue,
+ onRemoveQueue,
+}: {
+ /** Comments waiting in the dispatch queue, attached or not. `0` → the row is disabled. */
+ queueCount: number;
+ /** The queue is riding this message — the toggle's state. */
+ queueAttached: boolean;
+ /** Take the queue back off this message. */
+ onRemoveQueue: () => void;
+ /**
+ * Size the trigger for a dense action bar rather than a composer row.
+ *
+ * The agent thread's bar is a row of `h-6` / `text-xs` controls (the settings
+ * trigger beside this one); the Ask AI composer's row is sized to a
+ * full-height input and its send button. One fixed size cannot sit right in
+ * both, so the host says which bar it is — rather than the control guessing
+ * from context or every caller passing raw classes.
+ */
+ compact?: boolean;
+ onAddQueue: () => void;
+}) {
+ const { t } = useLingui();
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ type="button"
+ // No `size` in compact mode: the height and padding come from the
+ // classes below, matching the settings trigger exactly.
+ {...(compact ? {} : { size: 'icon' as const })}
+ variant="ghost"
+ aria-label={t`Add context to this message`}
+ data-testid="composer-add-context"
+ // `shrink-0` either way, so the row's layout is identical whether or
+ // not anything is attached — the input keeps every remaining pixel.
+ className={cn(
+ 'shrink-0 text-muted-foreground hover:text-foreground',
+ compact ? 'h-6 rounded-md px-2' : 'size-8',
+ )}
+ >
+ <Plus className={compact ? 'size-3.5' : 'size-4'} />
+ </Button>
+ </DropdownMenuTrigger>
+ {/* `align="start"` so the menu grows from the `+` rather than the far side
+ of the composer, and `side="top"` because the composer is docked at the
+ bottom of the column — a downward menu would open off-screen.
+ The width override is required, not cosmetic: DropdownMenuContent
+ sizes itself to `--radix-dropdown-menu-trigger-width` with a `min-w-32`
+ floor, which is 8rem against a 2rem icon trigger — narrow enough to
+ wrap a row like "Queue (5 comments)" onto two lines. `w-60` is the
+ agent-settings menu's width, so the two menus in that action bar are
+ the same size rather than nearly. */}
+ <DropdownMenuContent
+ align="start"
+ side="top"
+ className="w-60"
+ data-testid="composer-add-context-menu"
+ >
+ {/* An empty queue leaves the row visible but inert: hiding it would make
+ the menu look broken to someone who opened it specifically to add
+ comments, and the secondary line says why.
+
+ The agent-settings menu's own on/off row shape (`Fast mode`): a real
+ `menuitemcheckbox` owns the state, its default checkmark is hidden,
+ and a decorative Switch stands in on the right. The Switch is
+ aria-hidden + pointer-events-none so it never becomes a second,
+ invalid menu control. */}
+ <DropdownMenuCheckboxItem
+ checked={queueCount > 0 && queueAttached}
+ onCheckedChange={(next) => (next ? onAddQueue() : onRemoveQueue())}
+ disabled={queueCount === 0}
+ // Keep the menu open on toggle, matching the settings menu — you can
+ // see the chip row change behind it without reopening.
+ onSelect={(event) => event.preventDefault()}
+ className="items-start justify-between gap-4 pr-2 [&_[data-slot=dropdown-menu-checkbox-item-indicator]]:hidden"
+ data-testid="composer-add-context-queue"
+ >
+ <div className="flex min-w-0 flex-col">
+ <span>{t`Queue`}</span>
+ <span className="text-1sm text-muted-foreground">
+ {queueCount === 0 ? (
+ t`Nothing queued`
+ ) : (
+ <Plural value={queueCount} one="# comment" other="# comments" />
+ )}
+ </span>
+ </div>
+ <Switch
+ checked={queueCount > 0 && queueAttached}
+ size="sm"
+ aria-hidden="true"
+ tabIndex={-1}
+ className="pointer-events-none mt-0.5"
+ />
+ </DropdownMenuCheckboxItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/packages/app/src/components/ComposerContextChips.tsx b/packages/app/src/components/ComposerContextChips.tsx
index ee9033a87..aced822ae 100644
--- a/packages/app/src/components/ComposerContextChips.tsx
+++ b/packages/app/src/components/ComposerContextChips.tsx
@@ -23,7 +23,7 @@
import { useLingui } from '@lingui/react/macro';
import { X } from 'lucide-react';
-import type { ReactNode } from 'react';
+import { Children, type ReactNode } from 'react';
import { FileEntryPathIcon } from '@/components/file-entry-icon';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
@@ -100,7 +100,11 @@ export function ComposerContextChips({
* (the expanded selection preview) drops onto its own line beneath the chips. */
children?: ReactNode;
}) {
- if (files.length === 0 && children == null) return null;
+ // `Children.toArray` drops null / undefined / booleans, so a set of children
+ // that all render nothing counts as none. A plain `children == null` held only
+ // while there was ONE conditional child: a second turns it into an array, and
+ // `[null, false] == null` is false, so the row rendered as an empty strip.
+ if (files.length === 0 && Children.toArray(children).length === 0) return null;
return (
<div
className={cn('flex flex-wrap items-center gap-1', className)}
diff --git a/packages/app/src/components/DocPanel.dom.test.tsx b/packages/app/src/components/DocPanel.dom.test.tsx
index cd5a11448..fb6b9a8e9 100644
--- a/packages/app/src/components/DocPanel.dom.test.tsx
+++ b/packages/app/src/components/DocPanel.dom.test.tsx
@@ -121,10 +121,10 @@ afterEach(() => {
});
describe('DocPanel — tab gating', () => {
- test('project mode renders the full tab strip (outline + links + graph + timeline + problems)', () => {
+ test('project mode renders the full tab strip (outline + links + graph + timeline + problems + comments)', () => {
singleFileValue = false;
renderPanel('outline');
- expect(screen.getAllByRole('tab')).toHaveLength(5);
+ expect(screen.getAllByRole('tab')).toHaveLength(6);
expect(screen.getByTestId('outline-panel')).toBeTruthy();
});
diff --git a/packages/app/src/components/DocPanel.tsx b/packages/app/src/components/DocPanel.tsx
index d05e4cc83..3d4679228 100644
--- a/packages/app/src/components/DocPanel.tsx
+++ b/packages/app/src/components/DocPanel.tsx
@@ -1,7 +1,8 @@
import { t } from '@lingui/core/macro';
import { Trans, useLingui } from '@lingui/react/macro';
-import { AlertTriangle, Clock, Link2, ListTree, Network } from 'lucide-react';
+import { AlertTriangle, Clock, Link2, ListTree, MessageSquare, Network } from 'lucide-react';
import { lazy, Suspense, useEffect } from 'react';
+import { CommentsTab } from '@/comments/CommentsTab';
import {
composeFixAllProblemsTerminalPaste,
composeLintFixTerminalPaste,
@@ -24,7 +25,7 @@ import { useDocLinkFindings } from '@/editor/validation-audit-client';
import { useSingleFileMode } from '@/lib/single-file-mode';
import { type DocProblemCounts, patchDocValidationSource } from '@/lib/validation-store';
-export type PanelTab = 'outline' | 'links' | 'graph' | 'timeline' | 'problems';
+export type PanelTab = 'outline' | 'links' | 'graph' | 'timeline' | 'problems' | 'comments';
export const TABS: { id: PanelTab; icon: typeof ListTree }[] = [
{ id: 'outline', icon: ListTree },
@@ -34,6 +35,12 @@ export const TABS: { id: PanelTab; icon: typeof ListTree }[] = [
{ id: 'problems', icon: AlertTriangle },
];
+// A single Comments tab, carrying its own This-doc / Queue scope toggle.
+// Separate from TABS because single-file mode drops it.
+const COMMENT_TABS: { id: PanelTab; icon: typeof ListTree }[] = [
+ { id: 'comments', icon: MessageSquare },
+];
+
function countsOf(diagnostics: readonly { severity: string }[]): DocProblemCounts {
let errorCount = 0;
let warningCount = 0;
@@ -50,6 +57,7 @@ function tabLabel(id: PanelTab): string {
if (id === 'links') return t`Links`;
if (id === 'graph') return t`Graph`;
if (id === 'problems') return t`Problems`;
+ if (id === 'comments') return t`Comments`;
return t`Timeline`;
}
@@ -170,9 +178,12 @@ export function DocPanel({
// persisted now-hidden selection back to outline so the rail never renders a
// hidden panel.
const singleFile = useSingleFileMode();
- const tabs = singleFile
+ const baseTabs = singleFile
? TABS.filter((tab) => tab.id === 'outline' || tab.id === 'problems')
: TABS;
+ // Comments span docs (the queue is project-wide), so the tab is only offered
+ // when there is a project to span.
+ const tabs = singleFile ? baseTabs : [...baseTabs, ...COMMENT_TABS];
const effectiveTab: PanelTab = tabs.some((tab) => tab.id === activeTab) ? activeTab : 'outline';
const showTabStrip = mode === 'doc' && tabs.length > 1;
return (
@@ -256,6 +267,7 @@ export function DocPanel({
</Suspense>
)}
{effectiveTab === 'timeline' && <TimelineContent docName={docName} />}
+ {effectiveTab === 'comments' && <CommentsTab docName={docName} />}
{effectiveTab === 'problems' && (
<ProblemsPanel
docName={docName}
diff --git a/packages/app/src/components/FrontmatterRow.tsx b/packages/app/src/components/FrontmatterRow.tsx
index 4a4da5401..aa5ab790f 100644
--- a/packages/app/src/components/FrontmatterRow.tsx
+++ b/packages/app/src/components/FrontmatterRow.tsx
@@ -136,6 +136,16 @@ interface FrontmatterRowProps {
onChangeType: (next: FrontmatterType) => void;
/** Delete handler. Omit to hide the trash icon. */
onRemove?: () => void;
+ /**
+ * Row-level affordance rendered beside the delete control — the document
+ * panel puts its "comment on this property" button here.
+ *
+ * A slot rather than a handler because the control owns a popover it has to
+ * anchor itself. Passing it in also keeps comments out of this file: the row
+ * is shared by templates, skills, and folder cards, none of which have
+ * comment threads.
+ */
+ actionSlot?: ReactNode;
}
/**
@@ -159,6 +169,7 @@ export function FrontmatterRow({
onCommit,
onChangeType,
onRemove,
+ actionSlot,
}: FrontmatterRowProps) {
const { t } = useLingui();
const isComplex = isComplexValue(value);
@@ -258,6 +269,7 @@ export function FrontmatterRow({
)}
</div>
{badge ? <div className="shrink-0 min-h-7 flex items-center">{badge}</div> : null}
+ {actionSlot}
{onRemove ? (
<Button
type="button"
diff --git a/packages/app/src/components/ObjectWidget.tsx b/packages/app/src/components/ObjectWidget.tsx
index f8cbb79e9..bfd664739 100644
--- a/packages/app/src/components/ObjectWidget.tsx
+++ b/packages/app/src/components/ObjectWidget.tsx
@@ -43,6 +43,7 @@ import {
import { Plural, Trans, useLingui } from '@lingui/react/macro';
import { ChevronRight, Plus } from 'lucide-react';
import { useState } from 'react';
+import { PropertyCommentButton } from '@/comments/PropertyCommentButton';
import { useFrontmatterBinding } from '@/components/FrontmatterBindingContext';
import {
type AddDraft,
@@ -341,6 +342,15 @@ export function ObjectWidget({ keyName, value, path, depth = 0 }: ObjectWidgetPr
onCommit={(v) => commitChild(childKey, v)}
onChangeType={(nextType) => changeChildType(childKey, nextType)}
onRemove={readOnly ? undefined : () => removeChild(childKey)}
+ // `childPath` is rooted at the document, so its head is
+ // the top-level key and the rest is the walk into it —
+ // exactly the split a property comment target stores.
+ actionSlot={
+ <PropertyCommentButton
+ propertyKey={String(childPath[0])}
+ propertyPath={childPath.slice(1)}
+ />
+ }
/>
);
})}
diff --git a/packages/app/src/components/PanelScopeHeader.tsx b/packages/app/src/components/PanelScopeHeader.tsx
index 1ddf78f97..d2db6b049 100644
--- a/packages/app/src/components/PanelScopeHeader.tsx
+++ b/packages/app/src/components/PanelScopeHeader.tsx
@@ -11,9 +11,17 @@ export type PanelScope = 'doc' | 'project';
export function PanelScopeHeader({
scope,
onScopeChange,
+ projectLabel,
}: {
scope: PanelScope;
onScopeChange: (scope: PanelScope) => void;
+ /**
+ * Label for the project-scope side. Defaults to "Project". Comments override
+ * it with "Queue" — the project view there isn't "every comment in the
+ * project", it's specifically the batch waiting to be sent, and calling it
+ * Project sent people looking for a list they weren't going to find.
+ */
+ projectLabel?: string;
}) {
const { t } = useLingui();
return (
@@ -34,7 +42,7 @@ export function PanelScopeHeader({
<Trans>This doc</Trans>
</ToggleGroupItem>
<ToggleGroupItem value="project" className="flex-1" data-testid="panel-scope-project">
- <Trans>Project</Trans>
+ {projectLabel ?? <Trans>Project</Trans>}
</ToggleGroupItem>
</ToggleGroup>
</div>
diff --git a/packages/app/src/components/PropertyInlineLinks.dom.test.tsx b/packages/app/src/components/PropertyInlineLinks.dom.test.tsx
index 9488c7672..6ba419a00 100644
--- a/packages/app/src/components/PropertyInlineLinks.dom.test.tsx
+++ b/packages/app/src/components/PropertyInlineLinks.dom.test.tsx
@@ -10,7 +10,7 @@
* of property values (which have no embedded link syntax) pay zero
* DOM cost beyond a bare text node.
*
- * Repo convention (see `EditWithAiBubbleButton.dom.test.tsx`,
+ * Repo convention (see `FootnoteBubbleButton.dom.test.tsx`,
* `tag-pill-input.dom.test.tsx`): no @testing-library/react interaction
* helpers — assert through queries on the rendered DOM after `render`.
*/
diff --git a/packages/app/src/components/PropertyPanel.tsx b/packages/app/src/components/PropertyPanel.tsx
index 8bee64c86..ff7be3d3e 100644
--- a/packages/app/src/components/PropertyPanel.tsx
+++ b/packages/app/src/components/PropertyPanel.tsx
@@ -30,6 +30,8 @@ import {
import { Trans, useLingui } from '@lingui/react/macro';
import { AlertTriangle, Plus } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
+import { CommentedDocProvider } from '@/comments/CommentedDocContext';
+import { PropertyCommentButton } from '@/comments/PropertyCommentButton';
import { FrontmatterBindingProvider } from '@/components/FrontmatterBindingContext';
import {
type AddDraft,
@@ -416,84 +418,97 @@ export function PropertyPanel({ provider, reservedKeys }: PropertyPanelProps) {
return (
<FrontmatterBindingProvider binding={binding}>
- <PropertyDisclosure
- ref={panelRef}
- title={<Trans>Properties</Trans>}
- count={renderKeys.length}
- testId="property-panel"
- className="pt-4"
- contentClassName={PROP_CONTENT_SHIFT}
- open={!collapsed}
- onOpenChange={(open) => setCollapsed(!open)}
- >
- {parseError ? (
- // No drag-handle gutter — cancel the content shift so the banner sits
- // flush instead of hanging into the page margin (see PROP_CONTENT_SHIFT).
- <div
- role="alert"
- data-testid="property-panel-yaml-error"
- className={`mb-1 ${PROP_GUTTER_COMPENSATE} flex items-start gap-1.5 rounded border border-destructive/30 bg-destructive/5 px-2 py-1.5 text-[11px] text-destructive`}
- >
- <AlertTriangle className="size-3.5 shrink-0 mt-0.5" />
- <div>
- <Trans>
- The properties block at the top of this doc has a formatting error. Switch to source
- mode to fix it.
- </Trans>
- <span className="block text-[10px] opacity-80">{parseError}</span>
+ {/* Sibling to the binding: the recursive rows below host comment buttons,
+ and every one of them needs to know which document it belongs to.
+ Empty name means there is no document (an unattached provider), which
+ the buttons read as "render nothing". */}
+ <CommentedDocProvider docName={docName === '' ? null : docName}>
+ <PropertyDisclosure
+ ref={panelRef}
+ title={<Trans>Properties</Trans>}
+ count={renderKeys.length}
+ testId="property-panel"
+ className="pt-4"
+ contentClassName={PROP_CONTENT_SHIFT}
+ open={!collapsed}
+ onOpenChange={(open) => setCollapsed(!open)}
+ >
+ {parseError ? (
+ // No drag-handle gutter — cancel the content shift so the banner sits
+ // flush instead of hanging into the page margin (see PROP_CONTENT_SHIFT).
+ <div
+ role="alert"
+ data-testid="property-panel-yaml-error"
+ className={`mb-1 ${PROP_GUTTER_COMPENSATE} flex items-start gap-1.5 rounded border border-destructive/30 bg-destructive/5 px-2 py-1.5 text-[11px] text-destructive`}
+ >
+ <AlertTriangle className="size-3.5 shrink-0 mt-0.5" />
+ <div>
+ <Trans>
+ The properties block at the top of this doc has a formatting error. Switch to
+ source mode to fix it.
+ </Trans>
+ <span className="block text-[10px] opacity-80">{parseError}</span>
+ </div>
</div>
- </div>
- ) : null}
- <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
- <SortableContext
- items={renderKeys.map((k, i) => rowId(k, i))}
- strategy={verticalListSortingStrategy}
+ ) : null}
+ <DndContext
+ sensors={sensors}
+ collisionDetection={closestCenter}
+ onDragEnd={handleDragEnd}
>
- {renderKeys.map((key, idx) => {
- const value = map[key];
- if (value === undefined) return null;
- const declared = overrides[key] ?? inferType(value);
- const renameState = renaming?.key === key ? renaming : null;
- const isDuplicate = (dupCount.get(key) ?? 0) > 1;
- // File-owned key. The trash icon deletes the key from the
- // file's own frontmatter.
- // Position-aware sortable id: dup-name rows share the same
- // `key` string, so we suffix with the source-order index so
- // SortableContext can distinguish them. yaml@2 with
- // `uniqueKeys: false` admits duplicates, and the panel
- // surfaces them as distinct rows. The index is load-bearing
- // here precisely because the YAML source order is the
- // rendered order — biome/lint warns about index keys for
- // unstable arrays, but FM rows are deterministic by source
- // position.
- return (
- <FrontmatterRow
- // biome-ignore lint/suspicious/noArrayIndexKey: position-aware key for dup-name rows.
- key={`${key}-${idx}`}
- sortableId={rowId(key, idx)}
- keyName={key}
- value={value}
- declared={declared}
- enumConstraint={enumConstraints.get(key)}
- error={errors[key] ?? null}
- resetCounter={resetCounters[key] ?? 0}
- isDuplicate={isDuplicate}
- rename={{
- state: renameState,
- onBegin: () => beginRename(key),
- onChangeDraft: changeRenameDraft,
- onCommit: commitRename,
- onCancel: cancelRename,
- }}
- onCommit={(v) => commitProperty(key, v)}
- onChangeType={(t) => setType(key, t)}
- onRemove={() => removeProperty(key)}
- />
- );
- })}
- </SortableContext>
- </DndContext>
- {/*
+ <SortableContext
+ items={renderKeys.map((k, i) => rowId(k, i))}
+ strategy={verticalListSortingStrategy}
+ >
+ {renderKeys.map((key, idx) => {
+ const value = map[key];
+ if (value === undefined) return null;
+ const declared = overrides[key] ?? inferType(value);
+ const renameState = renaming?.key === key ? renaming : null;
+ const isDuplicate = (dupCount.get(key) ?? 0) > 1;
+ // File-owned key. The trash icon deletes the key from the
+ // file's own frontmatter.
+ // Position-aware sortable id: dup-name rows share the same
+ // `key` string, so we suffix with the source-order index so
+ // SortableContext can distinguish them. yaml@2 with
+ // `uniqueKeys: false` admits duplicates, and the panel
+ // surfaces them as distinct rows. The index is load-bearing
+ // here precisely because the YAML source order is the
+ // rendered order — biome/lint warns about index keys for
+ // unstable arrays, but FM rows are deterministic by source
+ // position.
+ return (
+ <FrontmatterRow
+ // biome-ignore lint/suspicious/noArrayIndexKey: position-aware key for dup-name rows.
+ key={`${key}-${idx}`}
+ sortableId={rowId(key, idx)}
+ keyName={key}
+ value={value}
+ declared={declared}
+ enumConstraint={enumConstraints.get(key)}
+ error={errors[key] ?? null}
+ resetCounter={resetCounters[key] ?? 0}
+ isDuplicate={isDuplicate}
+ rename={{
+ state: renameState,
+ onBegin: () => beginRename(key),
+ onChangeDraft: changeRenameDraft,
+ onCommit: commitRename,
+ onCancel: cancelRename,
+ }}
+ onCommit={(v) => commitProperty(key, v)}
+ onChangeType={(t) => setType(key, t)}
+ onRemove={() => removeProperty(key)}
+ // Top-level row: the key IS the whole address. Nested rows
+ // pass their own path (see ObjectWidget). The button itself
+ // decides whether a document is behind it.
+ actionSlot={<PropertyCommentButton propertyKey={key} />}
+ />
+ );
+ })}
+ </SortableContext>
+ </DndContext>
+ {/*
Tags discoverability affordance — render an empty, pinned-at-
end `tags` row when the key is absent from the file YAML
(`map`). The first commit from this virtual row writes the YAML
@@ -503,70 +518,71 @@ export function PropertyPanel({ provider, reservedKeys }: PropertyPanelProps) {
the virtual row is purely for "this doc has no tags field yet,
but you can add one here."
*/}
- {!reserved.has('tags') && !Object.hasOwn(map, 'tags') ? (
- <FrontmatterRow
- key="virtual-tags"
- keyName="tags"
- value={[]}
- declared="list"
- enumConstraint={enumConstraints.get('tags')}
- error={errors.tags ?? null}
- resetCounter={resetCounters.tags ?? 0}
- isPlaceholder
- onCommit={(v) => commitProperty('tags', v)}
- // No type-change for the virtual row — the chip widget is
- // the only meaningful editor for `tags`, and
- // `isPlaceholder` hides the type-icon dropdown anyway.
- // The handler is required by the type but never reaches
- // user input here.
- onChangeType={() => {}}
- />
- ) : null}
- {adding ? (
- // No drag-handle gutter — cancel the content shift so the add form
- // sits flush with the rows (see PROP_CONTENT_SHIFT).
- <div className={PROP_GUTTER_COMPENSATE}>
- <AddPropertyRow
- draft={adding}
- onChangeName={changeAddName}
- onChangeType={changeAddType}
- onChangeValue={changeAddValue}
- onCommit={commitAdd}
- onCancel={cancelAdd}
+ {!reserved.has('tags') && !Object.hasOwn(map, 'tags') ? (
+ <FrontmatterRow
+ key="virtual-tags"
+ keyName="tags"
+ value={[]}
+ declared="list"
+ enumConstraint={enumConstraints.get('tags')}
+ error={errors.tags ?? null}
+ resetCounter={resetCounters.tags ?? 0}
+ isPlaceholder
+ onCommit={(v) => commitProperty('tags', v)}
+ // No type-change for the virtual row — the chip widget is
+ // the only meaningful editor for `tags`, and
+ // `isPlaceholder` hides the type-icon dropdown anyway.
+ // The handler is required by the type but never reaches
+ // user input here.
+ onChangeType={() => {}}
/>
- </div>
- ) : (
- // Wrapper mirrors FrontmatterRow's flex layout above: an
- // aria-hidden `w-4` spacer occupies the drag-handle column,
- // gap-1 separates it from the Button (which itself starts at
- // the TypeIcon column edge). Result: the Button's hover
- // background starts at 20px (=16+4) — the same x as the
- // TypeIconButton in the rows above — instead of stretching
- // all the way to the row's left edge as `pl-7` would. The
- // `+` icon center still lands at ~35px (20+8+7), within ±2px
- // of the TypeIconButton icon center (34px).
- <div className="mt-1 flex items-center gap-1">
- <span aria-hidden className="h-7 w-4 shrink-0" />
- <Button
- type="button"
- variant="ghost"
- size="sm"
- data-testid="add-property-trigger"
- onClick={beginAdd}
- // Visible label is just "Add"; the aria-label restores the
- // action's object so screen readers don't announce a
- // context-free "Add, button".
- aria-label={t`Add property`}
- className="flex items-center gap-1.5 rounded px-2 py-1 font-medium text-sm hover:bg-muted/50 hover:text-foreground"
- >
- <Plus className="size-3.5" />
- <span>
- <Trans>Add</Trans>
- </span>
- </Button>
- </div>
- )}
- </PropertyDisclosure>
+ ) : null}
+ {adding ? (
+ // No drag-handle gutter — cancel the content shift so the add form
+ // sits flush with the rows (see PROP_CONTENT_SHIFT).
+ <div className={PROP_GUTTER_COMPENSATE}>
+ <AddPropertyRow
+ draft={adding}
+ onChangeName={changeAddName}
+ onChangeType={changeAddType}
+ onChangeValue={changeAddValue}
+ onCommit={commitAdd}
+ onCancel={cancelAdd}
+ />
+ </div>
+ ) : (
+ // Wrapper mirrors FrontmatterRow's flex layout above: an
+ // aria-hidden `w-4` spacer occupies the drag-handle column,
+ // gap-1 separates it from the Button (which itself starts at
+ // the TypeIcon column edge). Result: the Button's hover
+ // background starts at 20px (=16+4) — the same x as the
+ // TypeIconButton in the rows above — instead of stretching
+ // all the way to the row's left edge as `pl-7` would. The
+ // `+` icon center still lands at ~35px (20+8+7), within ±2px
+ // of the TypeIconButton icon center (34px).
+ <div className="mt-1 flex items-center gap-1">
+ <span aria-hidden className="h-7 w-4 shrink-0" />
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ data-testid="add-property-trigger"
+ onClick={beginAdd}
+ // Visible label is just "Add"; the aria-label restores the
+ // action's object so screen readers don't announce a
+ // context-free "Add, button".
+ aria-label={t`Add property`}
+ className="flex items-center gap-1.5 rounded px-2 py-1 font-medium text-sm hover:bg-muted/50 hover:text-foreground"
+ >
+ <Plus className="size-3.5" />
+ <span>
+ <Trans>Add</Trans>
+ </span>
+ </Button>
+ </div>
+ )}
+ </PropertyDisclosure>
+ </CommentedDocProvider>
</FrontmatterBindingProvider>
);
}
diff --git a/packages/app/src/components/TerminalSessionsHost.threads.dom.test.tsx b/packages/app/src/components/TerminalSessionsHost.threads.dom.test.tsx
index d34b57840..9236eda60 100644
--- a/packages/app/src/components/TerminalSessionsHost.threads.dom.test.tsx
+++ b/packages/app/src/components/TerminalSessionsHost.threads.dom.test.tsx
@@ -18,6 +18,7 @@ import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
import { requestPreferredSession } from './handoff/preferred-session-events';
import { requestActiveTerminalInput } from './handoff/terminal-input-events';
import { subscribeToTerminalLaunchRequests } from './handoff/terminal-launch-events';
+import { _resetReusableSession, getReusableSession } from './reusable-session-store';
// A tiny controllable stand-in for the server-authoritative thread store.
let openThreads: ThreadInfo[] = [];
@@ -118,6 +119,10 @@ vi.doMock('@tanstack/react-query', () => ({
const { TerminalSessionsHost } = await import('./TerminalSessionsHost');
+/** Two distinguishable agents, so a stale publish names a visibly wrong one. */
+const FIRST_AGENT = { id: 'a1', name: 'First Agent', source: 'registry' } as const;
+const SECOND_AGENT = { id: 'a2', name: 'Second Agent', source: 'registry' } as const;
+
function makeThread(overrides: Partial<ThreadInfo> & { threadId: string }): ThreadInfo {
return {
agent: { id: 'a', name: 'Agent', source: 'registry' },
@@ -189,7 +194,10 @@ describe('TerminalSessionsHost — agent-thread hosting (web / no bridge)', () =
catalogData = undefined;
mockRegisteredAgent = null;
});
- afterEach(() => cleanup());
+ afterEach(() => {
+ cleanup();
+ _resetReusableSession();
+ });
test('a server thread becomes a tab rendering its ThreadView', async () => {
render(<Harness />);
@@ -230,6 +238,28 @@ describe('TerminalSessionsHost — agent-thread hosting (web / no bridge)', () =
expect(screen.getByRole('tab', { name: /Two/ })).toBeDefined();
});
+ test('the appendable-session signal names the ACTIVE tab, not the previous one', async () => {
+ // Regression: the publish effect read `activeSessionIdRef` / `sessionsRef`,
+ // which are synced by an effect declared BELOW it — so it saw the previous
+ // commit and published the tab you just switched AWAY from. The queue's
+ // send button reads this to name its destination, so the symptom was
+ // "Send → Cursor" while sitting in Claude Agent.
+ render(<Harness />);
+ setOpenThreads([makeThread({ threadId: 't1', title: 'One', agent: FIRST_AGENT })]);
+ await screen.findByRole('tab', { name: /One/ });
+ await waitFor(() => expect(getReusableSession()?.label).toBe('First Agent'));
+
+ // A second thread arrives and auto-reveals as the active tab.
+ setOpenThreads([
+ makeThread({ threadId: 't1', title: 'One', agent: FIRST_AGENT }),
+ makeThread({ threadId: 't2', title: 'Two', agent: SECOND_AGENT }),
+ ]);
+ await screen.findByRole('tab', { name: /Two/ });
+
+ await waitFor(() => expect(getReusableSession()?.label).toBe('Second Agent'));
+ expect(getReusableSession()).toMatchObject({ id: 't2', kind: 'thread', agentId: 'a2' });
+ });
+
test('closing a thread tab archives it via the client (not a local remove)', async () => {
const user = userEvent.setup();
render(<Harness />);
@@ -412,6 +442,30 @@ describe('TerminalSessionsHost — agent-thread hosting (web / no bridge)', () =
expect(launchAgentThread).not.toHaveBeenCalled();
});
+ test('reusing a thread reveals a collapsed dock', async () => {
+ mockRegisteredAgent = { source: 'registry', id: 'acme-agent', name: 'Acme' };
+ // Seeded BEFORE mount so the live count never increases — the auto-reveal
+ // that covers a fresh thread cannot fire, which is exactly the state a
+ // user is in after collapsing a dock they had been working in.
+ setOpenThreads([makeThread({ threadId: 't1', title: 'Work' })]);
+ const onVisibleChange = vi.fn((_v: boolean) => {});
+ render(<Harness initialVisible={false} onVisibleChange={onVisibleChange} />);
+ await screen.findByTestId('thread-view');
+ expect(onVisibleChange).not.toHaveBeenCalled();
+
+ const staged: string[] = [];
+ const stopStaging = subscribeStagedThreadDraft('t1', (text) => staged.push(text));
+ await act(async () => {
+ requestActiveTerminalInput('fix this lint error', { submit: false });
+ });
+ stopStaging();
+
+ // The draft lands in the session AND the dock comes back, so the send is
+ // visibly a send. Staging into a hidden surface reads as a no-op.
+ expect(staged).toEqual(['fix this lint error']);
+ expect(onVisibleChange).toHaveBeenCalledWith(true);
+ });
+
test('newTab forces a fresh thread even with one open (⇧⌘J)', async () => {
mockRegisteredAgent = { source: 'registry', id: 'acme-agent', name: 'Acme' };
render(<Harness />);
diff --git a/packages/app/src/components/TerminalSessionsHost.tsx b/packages/app/src/components/TerminalSessionsHost.tsx
index 87795da94..5584ef4ac 100644
--- a/packages/app/src/components/TerminalSessionsHost.tsx
+++ b/packages/app/src/components/TerminalSessionsHost.tsx
@@ -1,4 +1,4 @@
-import type { TerminalCli } from '@inkeep/open-knowledge-core';
+import { TERMINAL_CLIS, type TerminalCli } from '@inkeep/open-knowledge-core';
import type { ThreadInfo, ThreadStatus } from '@inkeep/open-knowledge-core/acp/thread-protocol';
import { useLingui } from '@lingui/react/macro';
import { Loader2, SquareTerminalIcon } from 'lucide-react';
@@ -14,6 +14,7 @@ import {
import { createPortal } from 'react-dom';
import { RegisteredAgentIcon } from '@/components/acp/RegisteredAgentIcon';
import { ArchivedThreadChooser, ThreadHistoryMenu } from '@/components/acp/ThreadHistoryMenu';
+import { publishReusableSession } from '@/components/reusable-session-store';
import { TabsContent } from '@/components/ui/tabs';
import { isInAppAgentEnabled } from '@/lib/acp/agent-visibility';
import { useEnabledOverrides } from '@/lib/acp/enabled-agents';
@@ -420,9 +421,13 @@ export function TerminalSessionsHost({
function setSessionPtyId(id: string, ptyId: string | null) {
if (ptyId === null) {
ptyIdBySessionRef.current.delete(id);
+ // A dead PTY makes its tab un-appendable, and the map is a ref — no
+ // render follows it, so the publish has to ride the mutation.
+ publishReusableSessionFrom(sessionsRef.current, activeSessionIdRef.current);
return;
}
ptyIdBySessionRef.current.set(id, ptyId);
+ publishReusableSessionFrom(sessionsRef.current, activeSessionIdRef.current);
const session = sessionsRef.current.find((s) => s.id === id);
if (session != null && session.kind === 'terminal') {
bridge?.terminal?.setMeta?.(ptyId, {
@@ -574,6 +579,78 @@ export function TerminalSessionsHost({
* `submit` decide how the text lands: an Ask AI surface sends a complete
* instruction and runs it; a ⌘J selection send is raw material and waits.
*/
+ /**
+ * Publish whether the ACTIVE session is one `dispatchAskAi` would reuse, so
+ * surfaces outside the dock can name the destination before a click.
+ *
+ * Deliberately re-derives the gate below rather than caching a flag: the two
+ * must agree, and the failure mode of drift is a button promising an append
+ * the host then refuses.
+ *
+ * The caller passes the session list + active id rather than this reading
+ * `sessionsRef` / `activeSessionIdRef`, because those refs are synced in an
+ * effect declared BELOW this one — an effect here reading them would see the
+ * previous commit and publish the previously-active tab. The render path
+ * passes state; the ptyId callback passes the refs, which are current by then.
+ */
+ function publishReusableSessionFrom(sessionList: readonly SessionDescriptor[], activeId: string) {
+ const active = sessionList.find((s) => s.id === activeId);
+ if (active == null) {
+ publishReusableSession(null);
+ return;
+ }
+ if (active.kind === 'thread') {
+ const info = threadInfoById.get(active.threadId);
+ publishReusableSession({
+ id: active.id,
+ kind: 'thread',
+ label: info?.agent.name ?? t`the open agent`,
+ agentId: info?.agent.id ?? '',
+ iconUrl: info?.agent.iconUrl,
+ });
+ return;
+ }
+ const livePtyId = ptyIdBySessionRef.current.get(active.id);
+ const cli = active.launch?.cli;
+ // Same three-part gate as the reuse branch below — a bare shell or a reload
+ // survivor is NOT appendable.
+ if (livePtyId == null || bridge?.terminal == null || cli == null) {
+ publishReusableSession(null);
+ return;
+ }
+ publishReusableSession({
+ id: active.id,
+ kind: 'terminal',
+ label: TERMINAL_CLIS[cli].displayName,
+ cli,
+ });
+ }
+
+ // Every input to the gate above: which tab is active, the session list (a
+ // thread arriving, a tab closing), and the thread infos that carry the label.
+ // PTY resolution is not renderable state, so `setSessionPtyId` re-publishes.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: publishes from the state it is passed; `openThreadTabs` is a label input, read via threadInfoById
+ useEffect(() => {
+ publishReusableSessionFrom(sessions, activeSessionId);
+ }, [activeSessionId, sessions, openThreadTabs]);
+
+ /**
+ * Bring a hidden dock back before writing into the session it hosts.
+ *
+ * Collapsing hides the dock without ending anything, so a reuse still resolves
+ * and still lands — into a surface nobody can see. A fresh session is already
+ * covered (a new live thread auto-reveals), and reuse is the half that wasn't:
+ * a staged draft changes nothing the dock would otherwise surface, so without
+ * this the text arrives silently and the send reads as a no-op.
+ *
+ * Revealing is enough on its own — the reveal effect focuses the active
+ * session once the dock shows, which is why the focus calls below are only
+ * load-bearing when it was open already.
+ */
+ function revealForReuse() {
+ if (!visible) onVisibleChange(true);
+ }
+
function dispatchAskAi({ text, newTab, submit }: ActiveTerminalInputDetail) {
const activeId = activeSessionIdRef.current;
const active = sessionsRef.current.find((s) => s.id === activeId);
@@ -584,6 +661,7 @@ export function TerminalSessionsHost({
// pressed enter, and a thread the user is already in behaves the same.
// `submit` only decides how a FRESH session receives the text.
stageThreadDraft(active.threadId, text);
+ revealForReuse();
queueMicrotask(() => focusSession(active));
return;
}
@@ -596,6 +674,7 @@ export function TerminalSessionsHost({
// (see the `launch.cli` gate rationale above).
if (livePtyId != null && terminal != null && active.launch?.cli != null) {
terminal.input(livePtyId, text);
+ revealForReuse();
queueMicrotask(() => focusTerminalSession(activeId));
return;
}
diff --git a/packages/app/src/components/acp/ThreadView.tsx b/packages/app/src/components/acp/ThreadView.tsx
index 5d201844e..e31bafb34 100644
--- a/packages/app/src/components/acp/ThreadView.tsx
+++ b/packages/app/src/components/acp/ThreadView.tsx
@@ -42,6 +42,14 @@ import {
useRef,
useState,
} from 'react';
+import {
+ type CommentBatchItem,
+ composeCommentBatchInstruction,
+ useQueuedComments,
+} from '@/comments/comment-chips';
+import { prepareQueuedComments } from '@/comments/queue-attachment';
+import { refresh as refreshComments } from '@/comments/store';
+import { ComposerAddContextMenu } from '@/components/ComposerAddContextMenu';
import { focusComposerInputOnCardPointer } from '@/components/focus-composer-on-card-pointer';
import { useOptionalPageList } from '@/components/PageListContext';
import { Badge } from '@/components/ui/badge';
@@ -133,6 +141,11 @@ export function ThreadView({ info }: { info: ThreadInfo }): ReactNode {
const client = getAgentThreadClient();
const workspace = useWorkspace();
const [draft, setDraft] = useState('');
+ // The comment batch riding the next message, captured when the composer's `+`
+ // switched Queue on. Held here rather than in the composer because `submit`
+ // lives here and is what folds it into the prompt — and cleared on send with
+ // the draft, so the batch never silently rides a second message.
+ const [attachedComments, setAttachedComments] = useState<CommentBatchItem[] | null>(null);
const [followFile, setFollowFile] = useState(loadFollowFilePref);
const scrollRef = useRef<HTMLDivElement>(null);
const atBottomRef = useRef(true);
@@ -293,7 +306,15 @@ export function ThreadView({ info }: { info: ThreadInfo }): ReactNode {
const [failedPrompt, setFailedPrompt] = useState<string | null>(null);
const submit = (): void => {
- const text = draft.trim();
+ // The attached batch is composed in at SEND, with the draft as its leading
+ // instruction — so the textarea holds only the user's own words while they
+ // write, and toggling Queue off leaves nothing behind to clean up.
+ const typed = draft.trim();
+ const text =
+ attachedComments !== null ? composeCommentBatchInstruction(attachedComments, typed) : typed;
+ // An attached batch is a message on its own; only a bare draft needs words.
+ // `canQueue` rides alongside `canPrompt` (from main): a busy thread accepts a
+ // queued message, and a comment batch is as queueable as typed prose.
if (text === '' || !(canPrompt || canQueue)) return;
if (archived) {
// Type-to-resume: the send respawns the agent and reconnects the
@@ -314,11 +335,13 @@ export function ThreadView({ info }: { info: ThreadInfo }): ReactNode {
})
.finally(() => setResumePending(false));
setDraft('');
+ setAttachedComments(null);
atBottomRef.current = true;
return;
}
client.prompt(info.threadId, text);
setDraft('');
+ setAttachedComments(null);
atBottomRef.current = true;
};
@@ -454,6 +477,8 @@ export function ThreadView({ info }: { info: ThreadInfo }): ReactNode {
info={info}
draft={draft}
onDraftChange={setDraft}
+ commentsAttached={attachedComments !== null}
+ onAttachComments={setAttachedComments}
onSubmit={submit}
canPrompt={canPrompt}
canQueue={canQueue}
@@ -1937,6 +1962,8 @@ function ThreadComposer({
info,
draft,
onDraftChange,
+ commentsAttached,
+ onAttachComments,
onSubmit,
canPrompt,
canQueue,
@@ -1951,6 +1978,10 @@ function ThreadComposer({
info: ThreadInfo;
draft: string;
onDraftChange: (value: string) => void;
+ /** The comment queue is riding the next message — the `+` menu's toggle state. */
+ commentsAttached: boolean;
+ /** Capture the batch (`CommentBatchItem[]`) or detach it (`null`). */
+ onAttachComments: (items: CommentBatchItem[] | null) => void;
onSubmit: () => void;
canPrompt: boolean;
/** A turn is running — sends queue behind it instead of dispatching. */
@@ -1971,6 +2002,14 @@ function ThreadComposer({
// Naming the agent in the placeholder ("Message Claude") beats a generic
// "Message the agent"; strip the "Agent" suffix so it reads as the brand.
const agentName = agentDisplayName(info.agent.name);
+ const queuedComments = useQueuedComments();
+ // The queue is project-wide state that only gets loaded when something asks
+ // for it — an editor mounting a doc, or the Comments panel opening. A thread
+ // can be the first surface you open, so pull once on mount or the `+` reports
+ // an empty queue that isn't.
+ useEffect(() => {
+ void refreshComments().catch(() => undefined);
+ }, []);
// Grow with content up to a cap. `draft` is the trigger, not read in the
// body (the element's own scrollHeight is), so the analyzer sees it as
@@ -2047,7 +2086,35 @@ function ThreadComposer({
it exposes no config options, and justify-between would then float the
lone send button to the left. */}
<div className="flex items-center gap-2 px-1.5 pt-1 pb-1.5">
- <AgentSettingsPopover info={info} />
+ {/* Settings + `+` are one cluster of ghost controls, tightened to
+ `gap-0.5`: the row's `gap-2` is spacing between GROUPS, and at that
+ width the two read as unrelated buttons that happen to be near each
+ other. The right cluster keeps its own spacing via `ml-auto`, so
+ this doesn't move it. */}
+ <div className="flex items-center gap-0.5">
+ <AgentSettingsPopover info={info} />
+ {/* The same `+` the Ask AI composer carries, so "add context" is one
+ gesture wherever you are talking to an agent — and the same
+ toggle, so it is also one gesture to take it back off. The batch
+ is folded into the prompt at send, not pasted into the draft, so
+ the textarea holds only what you typed. Still NOT a dispatch:
+ nothing resolves. */}
+ <ComposerAddContextMenu
+ // This bar is `h-6` / `text-xs` controls (the settings trigger to
+ // its left); a composer-sized button would tower over them.
+ compact
+ queueCount={queuedComments.length}
+ queueAttached={commentsAttached}
+ onAddQueue={() => {
+ void prepareQueuedComments().then((items) => {
+ if (items === null) return;
+ onAttachComments(items);
+ ref.current?.focus();
+ });
+ }}
+ onRemoveQueue={() => onAttachComments(null)}
+ />
+ </div>
<div className="ml-auto flex items-center gap-1.5">
{usagePercent !== null && usage?.used !== undefined && usage?.size !== undefined ? (
<ContextUsageRing used={usage.used} size={usage.size} percent={usagePercent} />
@@ -2073,7 +2140,11 @@ function ThreadComposer({
type="button"
size="icon-sm"
className="rounded-lg"
- disabled={!(canPrompt || canQueue) || draft.trim() === ''}
+ // An attached batch IS a message — the comments carry their own
+ // requests, so an empty draft alongside them is a send, not a
+ // no-op. Gating on the draft alone left the button dead with a
+ // full queue attached.
+ disabled={!(canPrompt || canQueue) || (draft.trim() === '' && !commentsAttached)}
onClick={onSubmit}
aria-label={canQueue ? t`Queue message` : t`Send`}
data-testid="agent-thread-send"
diff --git a/packages/app/src/components/composer-shared-draft.dom.test.tsx b/packages/app/src/components/composer-shared-draft.dom.test.tsx
index c519a5dad..da4781edc 100644
--- a/packages/app/src/components/composer-shared-draft.dom.test.tsx
+++ b/packages/app/src/components/composer-shared-draft.dom.test.tsx
@@ -67,6 +67,19 @@ vi.doMock('@/components/ui/dropdown-menu', () => ({
{children}
</button>
),
+ // The composer's `+` context menu renders a checkbox row (attach / detach the
+ // comment queue); without it every test here dies on a missing mock export.
+ DropdownMenuCheckboxItem: ({ children, disabled, checked, ...props }: MenuChild) => (
+ <button
+ type="button"
+ role="menuitemcheckbox"
+ aria-checked={checked === true}
+ disabled={disabled}
+ {...props}
+ >
+ {children}
+ </button>
+ ),
DropdownMenuLabel: ({ children, ...props }: MenuChild) => <div {...props}>{children}</div>,
DropdownMenuSeparator: () => <hr data-testid="menu-separator" />,
}));
diff --git a/packages/app/src/components/handoff/AgentSplitButton.tsx b/packages/app/src/components/handoff/AgentSplitButton.tsx
index 0cea7a45f..b72e5034f 100644
--- a/packages/app/src/components/handoff/AgentSplitButton.tsx
+++ b/packages/app/src/components/handoff/AgentSplitButton.tsx
@@ -104,6 +104,7 @@ export function AgentSplitButton({
terminal,
terminals,
menuEmptyState,
+ menuLeading,
onMenuOpenChange,
menuAlign = 'end',
triggerAriaLabel,
@@ -143,6 +144,12 @@ export function AgentSplitButton({
onOpenSettings: () => void;
/** Rendered inside the menu when there are no app agents and no terminal. */
menuEmptyState?: ReactNode;
+ /**
+ * Caller-owned rows rendered ABOVE the agent sections, separated from them.
+ * For surfaces with a second decision to make alongside which agent — the
+ * comment queue's send picks a destination here.
+ */
+ menuLeading?: ReactNode;
onMenuOpenChange?: (open: boolean) => void;
menuAlign?: 'start' | 'end';
triggerAriaLabel: string;
@@ -191,6 +198,17 @@ export function AgentSplitButton({
className="max-h-80 min-w-[200px]"
data-testid={testIds.menu}
>
+ {/* Caller-owned rows above the agent sections. The queue's send uses
+ it for WHERE the batch goes (append to the open conversation, or a
+ clean one) — a different axis from WHICH agent, and one only that
+ surface has. It leads because it is the decision being made; the
+ agent picker below is the standing preference. */}
+ {menuLeading ? (
+ <>
+ {menuLeading}
+ {showThreadAgents || hasOptions ? <DropdownMenuSeparator /> : null}
+ </>
+ ) : null}
{showThreadAgents ? (
// In-app agent threads lead the menu when any is enabled; an empty
// section (all disabled) is hidden entirely.
diff --git a/packages/app/src/components/reusable-session-store.test.ts b/packages/app/src/components/reusable-session-store.test.ts
new file mode 100644
index 000000000..17153e5f2
--- /dev/null
+++ b/packages/app/src/components/reusable-session-store.test.ts
@@ -0,0 +1,125 @@
+/**
+ * The appendable-session signal.
+ *
+ * It exists so a send button can name its destination BEFORE the click, which
+ * makes one property load-bearing above all others: it must never hold a
+ * session the dock would refuse to reuse. `null` is the safe answer — a send
+ * then starts a fresh turn, which is always possible. A false positive is a
+ * button promising an append that silently becomes something else.
+ */
+
+import { afterEach, describe, expect, test } from 'vitest';
+import {
+ _resetReusableSession,
+ getReusableSession,
+ publishReusableSession,
+ subscribeReusableSession,
+} from './reusable-session-store';
+
+afterEach(() => _resetReusableSession());
+
+describe('the reusable-session store', () => {
+ test('starts empty, so a send starts a turn until told otherwise', () => {
+ expect(getReusableSession()).toBeNull();
+ });
+
+ test('publishes what the destination needs to be drawn, not just named', () => {
+ // The consumer renders a brand mark from these; with only a name it would
+ // fall back to whatever icon it could reach — the Claude mark on a Cursor
+ // tab, which is the bug this shape exists to prevent.
+ publishReusableSession({
+ id: 'thread-1',
+ kind: 'thread',
+ label: 'Claude Agent',
+ agentId: 'claude',
+ iconUrl: 'https://example.test/claude.svg',
+ });
+ expect(getReusableSession()).toEqual({
+ id: 'thread-1',
+ kind: 'thread',
+ label: 'Claude Agent',
+ agentId: 'claude',
+ iconUrl: 'https://example.test/claude.svg',
+ });
+ });
+
+ test('notifies subscribers on a real change', () => {
+ let notified = 0;
+ subscribeReusableSession(() => {
+ notified += 1;
+ });
+
+ publishReusableSession({
+ id: 'thread-1',
+ kind: 'thread',
+ label: 'Claude Agent',
+ agentId: 'claude',
+ });
+ expect(notified).toBe(1);
+
+ publishReusableSession(null);
+ expect(notified).toBe(2);
+ expect(getReusableSession()).toBeNull();
+ });
+
+ test('a value-equal publish is a no-op', () => {
+ // The host re-publishes freely rather than tracking what changed, so the
+ // store absorbs the churn — otherwise `useSyncExternalStore` would see a
+ // new snapshot on every PTY callback and re-render the send button.
+ let notified = 0;
+ publishReusableSession({
+ id: 'terminal-session-1',
+ kind: 'terminal',
+ label: 'Claude',
+ cli: 'claude',
+ });
+ subscribeReusableSession(() => {
+ notified += 1;
+ });
+
+ publishReusableSession({
+ id: 'terminal-session-1',
+ kind: 'terminal',
+ label: 'Claude',
+ cli: 'claude',
+ });
+ expect(notified).toBe(0);
+ });
+
+ test('a swapped icon source reaches subscribers even when the id holds', () => {
+ // Same tab id, different CLI: if the equality check ignored the icon input
+ // the button would keep drawing the old brand mark.
+ let notified = 0;
+ publishReusableSession({ id: 's1', kind: 'terminal', label: 'Claude', cli: 'claude' });
+ subscribeReusableSession(() => {
+ notified += 1;
+ });
+
+ publishReusableSession({ id: 's1', kind: 'terminal', label: 'Codex', cli: 'codex' });
+ expect(notified).toBe(1);
+ expect(getReusableSession()).toMatchObject({ cli: 'codex', label: 'Codex' });
+ });
+
+ test('a thread and a terminal sharing an id are not the same session', () => {
+ let notified = 0;
+ publishReusableSession({ id: 's1', kind: 'terminal', label: 'Claude', cli: 'claude' });
+ subscribeReusableSession(() => {
+ notified += 1;
+ });
+
+ publishReusableSession({ id: 's1', kind: 'thread', label: 'Claude', agentId: 'claude' });
+ expect(notified).toBe(1);
+ expect(getReusableSession()?.kind).toBe('thread');
+ });
+
+ test('unsubscribing stops delivery', () => {
+ let notified = 0;
+ const unsubscribe = subscribeReusableSession(() => {
+ notified += 1;
+ });
+ unsubscribe();
+
+ publishReusableSession({ id: 's1', kind: 'thread', label: 'Claude Agent', agentId: 'claude' });
+ expect(notified).toBe(0);
+ });
+});
diff --git a/packages/app/src/components/reusable-session-store.ts b/packages/app/src/components/reusable-session-store.ts
new file mode 100644
index 000000000..5d9054e82
--- /dev/null
+++ b/packages/app/src/components/reusable-session-store.ts
@@ -0,0 +1,116 @@
+/**
+ * The live agent session a passage can be appended to, published for surfaces
+ * outside the sessions dock.
+ *
+ * `TerminalSessionsHost` already decides reuse-vs-launch when text arrives
+ * (`dispatchAskAi`): a live thread takes it as a staged composer draft, a live
+ * CLI tab as a no-carriage-return write into its input, and anything else falls
+ * through to a fresh launch. That decision is made AFTER the click, from state
+ * the host keeps privately — which is fine for behavior and useless for a
+ * button that has to say where a batch is going BEFORE you commit to it.
+ *
+ * This is that missing half: the host publishes the same predicate it will act
+ * on, so a caller can label the action honestly. The comment queue's send uses
+ * it — with a session live, its menu offers "append to the open conversation";
+ * with none, it falls back to the plain agent picker and starts a fresh turn.
+ *
+ * **Only ever holds a session the host would actually reuse.** A bare shell is
+ * excluded on purpose: `terminal.input` writes bytes straight to the PTY, and a
+ * shell in canonical mode treats each newline as accept-line, so appending
+ * markdown there would RUN it. A reload-survivor tab is excluded too — it
+ * rehydrates with its CLI-ness unrecoverable. Publishing either would let a
+ * button promise an append the host then refuses.
+ *
+ * Dock position is deliberately not part of it. The dock hosts the same
+ * sessions whether it sits bottom or right (`'right'` is the default), so
+ * keying off a side would make the same click behave differently for no reason
+ * a user could see.
+ */
+
+import type { TerminalCli } from '@inkeep/open-knowledge-core';
+import { useSyncExternalStore } from 'react';
+
+/**
+ * Carries what a caller needs to RENDER the destination, not just name it — the
+ * two halves of the dock draw their marks from different sources (a registry
+ * manifest vs. the CLI brand set), and a consumer that had only a name would
+ * fall back to whichever icon it could reach. That is how the send button ended
+ * up showing the Claude mark while pointing at a Cursor tab.
+ */
+export type ReusableSession =
+ | {
+ /** The dock's session id — the threadId for a thread. */
+ readonly id: string;
+ readonly kind: 'thread';
+ /** The agent's display name. */
+ readonly label: string;
+ /** Registry/custom agent id — picks the local brand mark. */
+ readonly agentId: string;
+ /** Registry-manifest icon URL, when the manifest has one. */
+ readonly iconUrl?: string;
+ }
+ | {
+ /** The dock's session id — `terminal-session-<n>`. */
+ readonly id: string;
+ readonly kind: 'terminal';
+ /** The CLI's display name. */
+ readonly label: string;
+ /** Which CLI the tab runs — picks the brand mark. */
+ readonly cli: TerminalCli;
+ };
+
+let current: ReusableSession | null = null;
+const listeners = new Set<() => void>();
+
+function same(a: ReusableSession | null, b: ReusableSession | null): boolean {
+ if (a === null || b === null) return a === b;
+ if (a.id !== b.id || a.kind !== b.kind || a.label !== b.label) return false;
+ // Compare what the icon is drawn from too, or a re-published session that
+ // swapped its mark would be treated as unchanged.
+ if (a.kind === 'thread' && b.kind === 'thread') {
+ return a.agentId === b.agentId && a.iconUrl === b.iconUrl;
+ }
+ if (a.kind === 'terminal' && b.kind === 'terminal') return a.cli === b.cli;
+ return false;
+}
+
+/**
+ * Publish the active session when it is reusable, `null` when it is not. The
+ * host calls this on every change that could flip the answer — active tab,
+ * session list, PTY resolution, thread arrival.
+ *
+ * A value-equal publish is a no-op so `useSyncExternalStore` sees a stable
+ * snapshot; the host re-publishes freely rather than tracking what changed.
+ */
+export function publishReusableSession(next: ReusableSession | null): void {
+ if (same(current, next)) return;
+ current = next;
+ for (const listener of listeners) listener();
+}
+
+/** The session an append would land in, or `null` when a send must start one. */
+export function getReusableSession(): ReusableSession | null {
+ return current;
+}
+
+export function subscribeReusableSession(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
+
+/**
+ * Subscribe to the appendable session. `getServerSnapshot` returns `null` so
+ * SSR and the node test tier render the no-session state — the conservative
+ * side, where a send starts a fresh turn instead of claiming an append.
+ */
+export function useReusableSession(): ReusableSession | null {
+ return useSyncExternalStore(subscribeReusableSession, getReusableSession, () => null);
+}
+
+/** Test-only: drop the published session between cases. */
+export function _resetReusableSession(): void {
+ current = null;
+ listeners.clear();
+}
diff --git a/packages/app/src/components/ui/panel.dom.test.tsx b/packages/app/src/components/ui/panel.dom.test.tsx
new file mode 100644
index 000000000..fe976a992
--- /dev/null
+++ b/packages/app/src/components/ui/panel.dom.test.tsx
@@ -0,0 +1,56 @@
+/**
+ * DOM tests for the panel shell's scroll structure.
+ *
+ * The load-bearing property: `PanelFooter` is a SIBLING of the scroll area, not
+ * content inside it. A panel's primary action has to stay on screen no matter
+ * how long its list grows — twenty queued comments must not push "send" off the
+ * bottom. Nesting the footer back inside `PanelBody` would look identical with
+ * three items and fail silently with twenty.
+ */
+
+import { render, screen } from '@testing-library/react';
+import { describe, expect, test } from 'vitest';
+import { Panel, PanelBody, PanelFooter, PanelHeader } from './panel';
+
+describe('PanelFooter', () => {
+ test('sits outside the scroll container, not within it', () => {
+ render(
+ <Panel>
+ <PanelHeader>Queue</PanelHeader>
+ <PanelBody>
+ <p>an item</p>
+ </PanelBody>
+ <PanelFooter>
+ <p>Send</p>
+ </PanelFooter>
+ </Panel>,
+ );
+
+ const body = document.querySelector('[data-slot="panel-body"]');
+ const footer = document.querySelector('[data-slot="panel-footer"]');
+ expect(body).not.toBeNull();
+ expect(footer).not.toBeNull();
+ expect(body?.contains(footer as Node)).toBe(false);
+ expect(screen.getByText('Send')).toBeTruthy();
+ });
+
+ test('the body scrolls and the footer does not shrink', () => {
+ render(
+ <Panel>
+ <PanelBody>
+ <p>items</p>
+ </PanelBody>
+ <PanelFooter>
+ <p>Send</p>
+ </PanelFooter>
+ </Panel>,
+ );
+
+ const body = document.querySelector('[data-slot="panel-body"]');
+ const footer = document.querySelector('[data-slot="panel-footer"]');
+ // The body owns the overflow; the footer refuses to be compressed by it.
+ expect(body?.className).toContain('overflow-y-auto');
+ expect(footer?.className).toContain('shrink-0');
+ expect(footer?.className).not.toContain('overflow-y-auto');
+ });
+});
diff --git a/packages/app/src/components/ui/panel.tsx b/packages/app/src/components/ui/panel.tsx
index e0f61de5a..616e7dd1f 100644
--- a/packages/app/src/components/ui/panel.tsx
+++ b/packages/app/src/components/ui/panel.tsx
@@ -60,6 +60,24 @@ function PanelBody({ className, ...props }: React.ComponentProps<'div'>) {
);
}
+/**
+ * Actions pinned below the scroll area. A sibling of `PanelBody` rather than
+ * content inside it, so a panel's primary action stays reachable no matter how
+ * long the list grows — twenty items must not push "send" off the bottom.
+ */
+function PanelFooter({ className, ...props }: React.ComponentProps<'div'>) {
+ return (
+ <div
+ data-slot="panel-footer"
+ className={cn(
+ 'shrink-0 flex flex-wrap items-center justify-end gap-2 px-4 pt-2 pb-3',
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
function PanelEmpty({ className, ...props }: React.ComponentProps<'p'>) {
return (
<p
@@ -76,4 +94,13 @@ function PanelError({ className, ...props }: React.ComponentProps<'p'>) {
);
}
-export { Panel, PanelBody, PanelCount, PanelEmpty, PanelError, PanelHeader, PanelTitle };
+export {
+ Panel,
+ PanelBody,
+ PanelCount,
+ PanelEmpty,
+ PanelError,
+ PanelFooter,
+ PanelHeader,
+ PanelTitle,
+};
diff --git a/packages/app/src/editor/ComposerMentionInput.tsx b/packages/app/src/editor/ComposerMentionInput.tsx
index 9d50fb36d..6f2c7bd68 100644
--- a/packages/app/src/editor/ComposerMentionInput.tsx
+++ b/packages/app/src/editor/ComposerMentionInput.tsx
@@ -52,6 +52,7 @@ export function ComposerMentionInput({
onContentChange,
onMentionsChange,
onSubmit,
+ onEscape,
className,
placeholder,
initialDoc,
@@ -71,6 +72,15 @@ export function ComposerMentionInput({
* Optional — surfaces with no top-row chips omit it. */
onMentionsChange?: (mentions: string[]) => void;
onSubmit: () => void;
+ /**
+ * Escape, when the `@`-popup is NOT open.
+ *
+ * Hosts that live inside something dismissable — the comment composer — need
+ * Escape to close that thing, and cannot tell from outside whether the popup
+ * consumed the key first. Only this side knows, so it decides. Omitted, the
+ * field blurs as before.
+ */
+ onEscape?: () => void;
className?: string;
/** Static placeholder shown while empty (TipTap Placeholder extension). The
* bottom composer omits it and overlays its own rotating placeholder. */
@@ -88,11 +98,13 @@ export function ComposerMentionInput({
const onContentChangeRef = useRef(onContentChange);
const onMentionsChangeRef = useRef(onMentionsChange);
const onSubmitRef = useRef(onSubmit);
+ const onEscapeRef = useRef(onEscape);
useEffect(() => {
onEmptyChangeRef.current = onEmptyChange;
onContentChangeRef.current = onContentChange;
onMentionsChangeRef.current = onMentionsChange;
onSubmitRef.current = onSubmit;
+ onEscapeRef.current = onEscape;
});
const editor = useEditor({
@@ -115,6 +127,10 @@ export function ComposerMentionInput({
// owns that) and must not blur the field; otherwise it dismisses.
const suggestionActive = composerMentionSuggestionKey.getState(view.state)?.active;
if (suggestionActive) return false;
+ if (onEscapeRef.current !== undefined) {
+ onEscapeRef.current();
+ return true;
+ }
(view.dom as HTMLElement).blur();
return true;
}
diff --git a/packages/app/src/editor/TiptapEditor.tsx b/packages/app/src/editor/TiptapEditor.tsx
index 0cbe6e486..1829343a1 100644
--- a/packages/app/src/editor/TiptapEditor.tsx
+++ b/packages/app/src/editor/TiptapEditor.tsx
@@ -29,6 +29,11 @@ const editorCtorStartTimes = new WeakMap<object, number>();
import type { Transaction as PMTransaction } from '@tiptap/pm/state';
import type { EditorView as PMEditorView } from '@tiptap/pm/view';
+import { CommentAnchorLayer } from '@/comments/anchor-decorations';
+import { CommentMarginRail } from '@/comments/CommentMarginRail';
+import { CommentSelectionAffordance } from '@/comments/CommentSelectionAffordance';
+import { CommentsBoundary } from '@/comments/CommentsBoundary';
+import { CommentThreadPopover } from '@/comments/CommentThreadPopover';
import { loadFollowFilePref } from '@/components/acp/follow-file';
import { OUTLINE_NAV_EVENT, type OutlineNavDetail } from '@/components/OutlinePanel';
import { anchorFromHash } from '@/lib/doc-hash';
@@ -1675,6 +1680,19 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({
{!isSourceMode && (
<BubbleMenuBar editor={editor} shortcutEnabled={docName === activeDocName} />
)}
+ {/* Comment UI, isolated so its errors can't blank the doc. */}
+ {!isSourceMode && (
+ <CommentsBoundary>
+ <CommentSelectionAffordance
+ editor={editor}
+ docName={docName}
+ shortcutEnabled={docName === activeDocName}
+ />
+ <CommentAnchorLayer editor={editor} docName={docName} />
+ <CommentThreadPopover editor={editor} docName={docName} />
+ {docName === activeDocName && <CommentMarginRail editor={editor} docName={docName} />}
+ </CommentsBoundary>
+ )}
{!isSourceMode && <TableCellHandles editor={editor} />}
{/* Drag handle + "+" chrome is registered as the imperative
`BlockDragHandle` TipTap extension in `sharedExtensions` —
diff --git a/packages/app/src/editor/bubble-menu/BubbleMenuBar.tsx b/packages/app/src/editor/bubble-menu/BubbleMenuBar.tsx
index ef831977d..328a82f5f 100644
--- a/packages/app/src/editor/bubble-menu/BubbleMenuBar.tsx
+++ b/packages/app/src/editor/bubble-menu/BubbleMenuBar.tsx
@@ -4,11 +4,11 @@ import type { Editor } from '@tiptap/react';
import { useEditorState } from '@tiptap/react';
import { BubbleMenu } from '@tiptap/react/menus';
import { useRef, useState } from 'react';
+import { CommentBubbleButton } from '@/comments/CommentBubbleButton';
import { Separator } from '@/components/ui/separator';
import { BlockTypeSelector } from './BlockTypeSelector';
import { deriveEditorClipOptions } from './bubble-menu-clip';
import { shouldShowBubbleMenu } from './bubble-menu-state';
-import { EditWithAiBubbleButton } from './EditWithAiBubbleButton';
import { FileBubbleButtons, isFileNodeSelected } from './FileBubbleButtons';
import { FootnoteBubbleButton } from './FootnoteBubbleButton';
import { ImageAlignButtons, isImageNodeSelected } from './ImageAlignButtons';
@@ -138,11 +138,7 @@ export function BubbleMenuBar({
/>
<FootnoteBubbleButton key={`${tooltipKey}-footnote`} editor={editor} />
<ViewInSourceBubbleButton key={`${tooltipKey}-view-source`} editor={editor} />
- <EditWithAiBubbleButton
- key={`${tooltipKey}-edit-ai`}
- editor={editor}
- shortcutEnabled={shortcutEnabled}
- />
+ <CommentBubbleButton key={`${tooltipKey}-comment`} />
</>
)}
</BubbleMenu>
diff --git a/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.dom.test.tsx b/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.dom.test.tsx
deleted file mode 100644
index b39a276e4..000000000
--- a/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.dom.test.tsx
+++ /dev/null
@@ -1,308 +0,0 @@
-/**
- * RTL behavior tests for `EditWithAiBubbleButton` — the WYSIWYG
- * bubble-menu "Ask AI" selection affordance.
- *
- * Covers the embedded render gate, the cross-platform button, the macOS-only
- * keyboard shortcut, and the open+focus wiring: clicking the trigger (or, on
- * macOS, pressing Cmd+Shift+I) dispatches the shared `open-ask-ai-composer`
- * window event that `BottomComposer` subscribes to — the same path the ⌘L
- * shortcut runs — rather than opening any popover. The test observes dispatches
- * through the real `subscribeToOpenAskAiComposer` subscriber, so it asserts the
- * actual cross-component contract.
- *
- * The editor is a minimal `doc > paragraph > text` fake.
- *
- * Invocation: `bun run test:dom` from `packages/app/`.
- */
-
-import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
-import userEvent from '@testing-library/user-event';
-import { Schema } from '@tiptap/pm/model';
-import type { Editor } from '@tiptap/react';
-import type { ReactNode } from 'react';
-import { afterEach, beforeEach, 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 { setEditorDocName } from '../extensions/doc-context.ts';
-
-vi.doMock('sonner', () => ({ toast: { error: () => {}, success: () => {} } }));
-
-// The click handler defers its action to the next animation frame; jsdom under
-// bun does not always define rAF, so polyfill it to a microtask and flush via
-// `waitFor` at the assertions.
-if (typeof globalThis.requestAnimationFrame === 'undefined') {
- globalThis.requestAnimationFrame = ((callback) => {
- queueMicrotask(() => callback(0));
- return 0;
- }) as typeof globalThis.requestAnimationFrame;
-}
-
-const { EditWithAiBubbleButton } = await import('./EditWithAiBubbleButton');
-
-const schema = new Schema({
- nodes: {
- doc: { content: 'block+' },
- paragraph: { group: 'block', content: 'text*', toDOM: () => ['p', 0] },
- text: { group: 'inline' },
- },
-});
-
-/** A minimal fake TipTap editor. The click handler serializes the selection to
- * markdown via `serializeWysiwygSelection` (which reads `selection.content()`);
- * `collapsed` yields an empty selection so the caret-only → composer fallback
- * can be exercised. A `null` docName leaves the editor with no registered doc
- * name (`setEditorDocName` deletes the entry), exercising the ungrounded path. */
-function makeEditor(docName: string | null, text: string, collapsed = false): Editor {
- const doc = schema.node('doc', null, [schema.node('paragraph', null, [schema.text(text)])]);
- // Position 1 is just inside the paragraph, before the first char.
- const from = 1;
- const to = collapsed ? 1 : 1 + text.length;
- const editor = {
- state: {
- schema,
- doc,
- selection: { from, to, content: () => doc.slice(from, to) },
- },
- } as unknown as Editor;
- setEditorDocName(editor, docName);
- return editor;
-}
-
-/** `@tiptap/core`'s `isMacOS()` reads `navigator.platform` at call time. */
-function setPlatform(platform: string): void {
- Object.defineProperty(globalThis.navigator, 'platform', {
- value: platform,
- configurable: true,
- });
-}
-
-/** `useIsEmbedded` reads `navigator.userAgent` (via `detectEmbeddedHostFromBrowser`). */
-function setUserAgent(userAgent: string): void {
- Object.defineProperty(globalThis.navigator, 'userAgent', {
- value: userAgent,
- configurable: true,
- });
-}
-
-const PLAIN_UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Chrome/120 Safari/537.36';
-const EMBEDDED_UA = `${PLAIN_UA} Cursor/1.2.3`;
-
-// Count open+focus requests reaching BottomComposer's subscriber path.
-let openRequests = 0;
-let unsubscribe: (() => void) | null = null;
-// Capture text routed to the active-terminal input channel (TerminalSessionsHost's
-// subscriber path in production).
-let terminalInputs: ActiveTerminalInputDetail[] = [];
-let unsubscribeTerminal: (() => void) | null = null;
-
-function renderButton({
- editor,
- shortcutEnabled = true,
- before,
-}: {
- editor: Editor;
- shortcutEnabled?: boolean;
- before?: ReactNode;
-}) {
- return render(
- <>
- {before}
- <EditWithAiBubbleButton editor={editor} shortcutEnabled={shortcutEnabled} />
- </>,
- );
-}
-
-function dispatchEditWithAiShortcut(target: EventTarget): void {
- target.dispatchEvent(
- new KeyboardEvent('keydown', {
- key: 'I',
- code: 'KeyI',
- metaKey: true,
- shiftKey: true,
- bubbles: true,
- cancelable: true,
- }),
- );
-}
-
-beforeEach(() => {
- openRequests = 0;
- terminalInputs = [];
- unsubscribe = subscribeToOpenAskAiComposer(() => {
- openRequests += 1;
- });
- unsubscribeTerminal = subscribeToActiveTerminalInput((detail) => {
- terminalInputs.push(detail);
- });
-});
-
-afterEach(() => {
- unsubscribe?.();
- unsubscribe = null;
- unsubscribeTerminal?.();
- unsubscribeTerminal = null;
- cleanup();
- setUserAgent(PLAIN_UA);
-});
-
-describe('EditWithAiBubbleButton', () => {
- test('renders the Ask AI trigger on a macOS host', () => {
- setPlatform('MacIntel');
- const editor = makeEditor('specs/foo/SPEC', 'A passage.');
- renderButton({ editor });
-
- const button = screen.getByTestId('edit-with-ai-bubble-button');
- expect(button).toBeTruthy();
- expect(button.textContent).toContain('Ask AI');
- });
-
- test('renders the Ask AI trigger on a non-macOS host too (button is cross-platform)', () => {
- setPlatform('Linux x86_64');
- const editor = makeEditor('specs/foo/SPEC', 'A passage.');
- renderButton({ editor });
-
- const button = screen.getByTestId('edit-with-ai-bubble-button');
- expect(button).toBeTruthy();
- expect(button.textContent).toContain('Ask AI');
- });
-
- test('the keyboard shortcut stays macOS-only — Ctrl+Shift+I is inert off macOS (does not steal DevTools)', async () => {
- setPlatform('Linux x86_64');
- const editor = makeEditor('specs/foo/SPEC', 'A passage.');
- renderButton({ editor });
-
- await act(async () => {
- // The real Windows/Linux chord for this shortcut IS the browser DevTools
- // shortcut; the listener must not be bound off macOS, so nothing fires.
- window.dispatchEvent(
- new KeyboardEvent('keydown', {
- key: 'I',
- code: 'KeyI',
- ctrlKey: true,
- shiftKey: true,
- bubbles: true,
- cancelable: true,
- }),
- );
- });
-
- expect(openRequests).toBe(0);
- });
-
- test('does not render anything when embedded inside an agent host', () => {
- setPlatform('MacIntel');
- setUserAgent(EMBEDDED_UA);
- const editor = makeEditor('specs/foo/SPEC', 'A passage.');
- const { container } = renderButton({ editor });
-
- expect(screen.queryByTestId('edit-with-ai-bubble-button')).toBeNull();
- expect(container.firstChild).toBeNull();
- });
-
- test('clicking the trigger sends a GROUNDED selection prompt to the active terminal', async () => {
- setPlatform('MacIntel');
- const user = userEvent.setup();
- const editor = makeEditor('specs/foo/SPEC', 'A passage.');
- renderButton({ editor });
-
- await user.click(screen.getByTestId('edit-with-ai-bubble-button'));
-
- // The button hands the selection to the terminal-input channel; the real
- // pub/sub is exercised (the `beforeEach` subscriber captures the payload),
- // only the PTY host (`TerminalSessionsHost`) is not mounted here. In
- // production that host decides reuse vs. composer-fallback. The
- // passage is NOT pasted raw — it rides as the grounded selection prompt
- // (`composeSelectionPrompt`), naming the doc as an `@`-mention alongside the
- // passage. The exact wording is `composeSelectionPrompt`'s own contract
- // (tested in core); here we assert the grounding is present. Dispatch is
- // deferred a frame, so flush it before asserting.
- await waitFor(() => expect(terminalInputs).toHaveLength(1));
- const [detail] = terminalInputs;
- expect(detail.text).toContain('@specs/foo/SPEC.md');
- expect(detail.text).toContain('A passage.');
- expect(detail.text).not.toBe('A passage.');
- // A composed, self-contained Ask AI instruction RUNS on a fresh session
- // (submit), unlike the ⌘J selection send which stages unsent.
- expect(detail.submit).toBe(true);
- expect(openRequests).toBe(0);
- });
-
- test('clicking with an empty selection opens the Ask AI composer instead', async () => {
- setPlatform('MacIntel');
- const user = userEvent.setup();
- const editor = makeEditor('specs/foo/SPEC', 'A passage.', /* collapsed */ true);
- renderButton({ editor });
-
- await user.click(screen.getByTestId('edit-with-ai-bubble-button'));
-
- await waitFor(() => expect(openRequests).toBe(1));
- expect(terminalInputs).toEqual([]);
- });
-
- test('clicking with no registered doc name opens the composer instead', async () => {
- setPlatform('MacIntel');
- const user = userEvent.setup();
- // A non-empty selection, but the editor has no registered doc name (null):
- // there is no doc to ground the passage against, so the button opens the
- // composer instead of pasting an ungrounded prompt (mirrors the empty path).
- const editor = makeEditor(null, 'A passage.');
- renderButton({ editor });
-
- await user.click(screen.getByTestId('edit-with-ai-bubble-button'));
-
- await waitFor(() => expect(openRequests).toBe(1));
- expect(terminalInputs).toEqual([]);
- });
-
- test('Cmd+Shift+I requests the Ask AI composer open+focus', async () => {
- setPlatform('MacIntel');
- const editor = makeEditor('specs/foo/SPEC', 'A passage.');
- renderButton({ editor });
-
- await act(async () => {
- dispatchEditWithAiShortcut(window);
- });
-
- expect(openRequests).toBe(1);
- });
-
- test('Cmd+Shift+I does nothing when embedded inside an agent host', async () => {
- setPlatform('MacIntel');
- setUserAgent(EMBEDDED_UA);
- const editor = makeEditor('specs/foo/SPEC', 'A passage.');
- renderButton({ editor });
-
- await act(async () => {
- dispatchEditWithAiShortcut(window);
- });
-
- expect(openRequests).toBe(0);
- });
-
- test('Cmd+Shift+I ignores inactive mounted editors', async () => {
- setPlatform('MacIntel');
- const editor = makeEditor('specs/foo/SPEC', 'A passage.');
- renderButton({ editor, shortcutEnabled: false });
-
- await act(async () => {
- dispatchEditWithAiShortcut(window);
- });
-
- expect(openRequests).toBe(0);
- });
-
- test('Cmd+Shift+I ignores native text inputs', async () => {
- setPlatform('MacIntel');
- const editor = makeEditor('specs/foo/SPEC', 'A passage.');
- renderButton({ editor, before: <input data-testid="native-input" /> });
-
- await act(async () => {
- dispatchEditWithAiShortcut(screen.getByTestId('native-input'));
- });
-
- expect(openRequests).toBe(0);
- });
-});
diff --git a/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.tsx b/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.tsx
deleted file mode 100644
index f3feedc4c..000000000
--- a/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.tsx
+++ /dev/null
@@ -1,147 +0,0 @@
-/**
- * "Ask AI" button for the WYSIWYG bubble menu. Sends the selected passage into
- * the active shell (e.g. a running `claude` TUI) via
- * `requestActiveTerminalInput` — the host owns PTY state and launches a fresh
- * Claude tab when none is open, either way pre-loaded with the same grounded
- * selection prompt (`composeSelectionPrompt` builds it: doc named as an
- * `@`-mention plus the passage inline, or a locus "read via OK MCP" pointer
- * when it is large) — so the running agent can place the passage in its doc
- * instead of receiving an unattributed blob. With no selection to send
- * (caret-only or no active doc) it opens the docked "Ask AI" composer, the
- * same path the ⌘L shortcut runs; the composer pins the live selection as a
- * removable context pill.
- *
- * Mounted only in the bubble menu's text branch: image / file node selections
- * swap the whole bar to a separate control tree, and selection handoff does
- * not apply to leaf media nodes.
- *
- * Available on every platform — the button just opens the (now cross-platform)
- * composer. Hidden only when OK is embedded inside an agent host, where the
- * composer is not shown. The ⌘/Ctrl+Shift+I keyboard shortcut, however, stays
- * macOS-only: on Windows/Linux that chord is the browser DevTools shortcut, and
- * hijacking it for end users is worse than the missing shortcut.
- *
- * The open+focus intent is dispatched through `emitOpenAskAiComposer`, a
- * window CustomEvent that `BottomComposer` subscribes to — so the button and ⌘L
- * share exactly one open+focus implementation rather than duplicating it.
- */
-
-import { Trans } from '@lingui/react/macro';
-import { isMacOS } from '@tiptap/core';
-import type { Editor } from '@tiptap/react';
-import { Sparkles } from 'lucide-react';
-import { type ReactNode, useEffect } from 'react';
-import { emitOpenAskAiComposer } from '@/components/ask-ai-composer-events';
-import { composeTerminalSelectionPaste } from '@/components/handoff/compose-terminal-selection';
-import { requestActiveTerminalInput } from '@/components/handoff/terminal-input-events';
-import { Button } from '@/components/ui/button';
-import { Separator } from '@/components/ui/separator';
-import { useIsEmbedded } from '@/hooks/use-is-embedded';
-import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';
-import { isOverlayLayerOpen } from '@/lib/overlay-layers';
-import { serializeWysiwygSelection } from '../edit-with-ai-selection';
-import { getEditorDocName } from '../extensions/doc-context';
-
-function isNativeTextControl(target: EventTarget | null): boolean {
- if (!(target instanceof HTMLElement)) return false;
- // Keep this narrower than `isEditableShortcutTarget`: ProseMirror's editable
- // root is contentEditable, and selected editor text still needs this shortcut.
- const tagName = target.tagName.toUpperCase();
- return tagName === 'INPUT' || tagName === 'TEXTAREA' || tagName === 'SELECT';
-}
-
-export function EditWithAiBubbleButton({
- editor,
- shortcutEnabled = false,
-}: {
- editor: Editor;
- shortcutEnabled?: boolean;
-}): ReactNode {
- const isEmbedded = useIsEmbedded();
- // The button is available on every platform (it opens the cross-platform
- // composer); it's hidden only inside an embedded agent host, where the
- // composer is not shown.
- if (isEmbedded) return null;
-
- return <EditWithAiBubbleMenu editor={editor} shortcutEnabled={shortcutEnabled} />;
-}
-
-function EditWithAiBubbleMenu({
- editor,
- shortcutEnabled,
-}: {
- editor: Editor;
- shortcutEnabled: boolean;
-}): ReactNode {
- // The ⌘/Ctrl+Shift+I shortcut stays macOS-only: on Windows/Linux that chord is
- // the browser DevTools shortcut, so binding a capture-phase override there
- // would steal DevTools from end users. The button itself is cross-platform.
- const shortcutBound = isMacOS();
- useEffect(() => {
- if (!shortcutBound) return;
- const handleKeyDown = (event: KeyboardEvent): void => {
- if (!shortcutEnabled) return;
- if (!matchesKeyboardShortcut(event, 'edit-with-ai')) return;
- // `shortcutEnabled` only means "this is the active doc's editor", so it
- // stays true under an overlay — the layer above owns the keyboard.
- if (isOverlayLayerOpen()) return;
- if (isNativeTextControl(event.target)) return;
-
- event.preventDefault();
- event.stopPropagation();
- event.stopImmediatePropagation();
- emitOpenAskAiComposer();
- };
-
- // Capture phase overrides Chrome DevTools' Cmd+Shift+I before it fires (macOS
- // Chrome uses Cmd+Opt+I for DevTools, so this chord is free there).
- window.addEventListener('keydown', handleKeyDown, { capture: true });
- return () => window.removeEventListener('keydown', handleKeyDown, { capture: true });
- }, [shortcutEnabled, shortcutBound]);
-
- return (
- <>
- <Separator orientation="vertical" className="mx-0.5 h-5 data-vertical:self-center" />
- <Button
- type="button"
- variant="ghost"
- size="sm"
- data-testid="edit-with-ai-bubble-button"
- className="gap-1 px-2 text-sm font-medium text-accent-foreground/80"
- // Send the selected passage into the active shell (host reuses a live
- // PTY or launches a fresh Claude tab) as a GROUNDED prompt (see
- // `composeTerminalSelectionPaste`). Caret-only / empty selection (or
- // no active doc to ground against) has nothing to send, so open the
- // composer.
- //
- // Deferred a frame: the composer focus (empty-selection branch) and
- // the terminal focus fire synchronously inside this click, before
- // ProseMirror's own focus handling on the trailing mouseup, which
- // would steal the caret back to the doc and leave the composer
- // unfocused. Reading the selection first keeps the passage from the
- // click moment even though the write runs later. Mirrors
- // LinkEditPopover's rAF focus.
- onClick={() => {
- const docName = getEditorDocName(editor);
- const selectionMarkdown = serializeWysiwygSelection(editor);
- requestAnimationFrame(() => {
- if (docName === null || selectionMarkdown.trim() === '') {
- emitOpenAskAiComposer();
- return;
- }
- // A composed, self-contained ask — runs on a fresh session (what a
- // fresh CLI has always done), on a CLI and an agent thread alike.
- requestActiveTerminalInput(composeTerminalSelectionPaste(docName, selectionMarkdown), {
- submit: true,
- });
- });
- }}
- >
- <Sparkles className="size-3.5" aria-hidden="true" />
- <span>
- <Trans>Ask AI</Trans>
- </span>
- </Button>
- </>
- );
-}
diff --git a/packages/app/src/editor/bubble-menu/FootnoteBubbleButton.dom.test.tsx b/packages/app/src/editor/bubble-menu/FootnoteBubbleButton.dom.test.tsx
index 3d2fa3373..ec1415d52 100644
--- a/packages/app/src/editor/bubble-menu/FootnoteBubbleButton.dom.test.tsx
+++ b/packages/app/src/editor/bubble-menu/FootnoteBubbleButton.dom.test.tsx
@@ -13,8 +13,8 @@
* tested through DOM observation rather than internal call patterns so the
* tests survive refactors that preserve the behavioral contract.
*
- * Repo convention (see `EditWithAiBubbleButton.dom.test.tsx`,
- * `ActivityPanelBurstRow.test.tsx`): no @testing-library/react interaction
+ * Repo convention (see `ActivityPanelBurstRow.test.tsx`): no
+ * @testing-library/react interaction
* helpers — assert through queries on the rendered DOM after `render`.
*/
diff --git a/packages/app/src/editor/extensions/suggestion-floating-ui.ts b/packages/app/src/editor/extensions/suggestion-floating-ui.ts
index 9de7ff6c6..1fead32c1 100644
--- a/packages/app/src/editor/extensions/suggestion-floating-ui.ts
+++ b/packages/app/src/editor/extensions/suggestion-floating-ui.ts
@@ -42,8 +42,18 @@ export function createSuggestionPopup(
reveal: () => void;
} {
const popup = document.createElement('div');
+ // Identifies every suggestion popup as one, from outside the editor. They are
+ // portaled to `document.body`, so a host that dismisses on outside-click — the
+ // comment composer — would otherwise read a click on `@`-mention results as a
+ // click away and close itself mid-pick.
+ popup.dataset.suggestionPopup = label;
popup.style.position = 'fixed';
- popup.style.zIndex = '50';
+ // Above every host that can own a suggestion field. At 50 it sat UNDER the
+ // comment composer's `z-[60]` card, so `@`-mention results were half-hidden by
+ // the box you were typing in. 70 is the same rung `SrcAutocomplete` picked to
+ // clear the PropPanel's `z-[60]` popover — a suggestion list has to be above
+ // whatever spawned it, and 60 is the ceiling for those hosts.
+ popup.style.zIndex = '70';
// Hide until reveal() — callers stage real content first, then unhide.
// This eliminates the "flash at wrong position" visible during the initial
// sync placement (before computePosition's first resolution) and during
diff --git a/packages/app/src/globals.css b/packages/app/src/globals.css
index 680723d9c..66056971e 100644
--- a/packages/app/src/globals.css
+++ b/packages/app/src/globals.css
@@ -5798,3 +5798,21 @@ html.electron-mode [data-slot="sidebar-inner"] {
box-shadow: none;
background: transparent;
}
+
+/* A comment highlight inside a property value.
+ *
+ * The document body tints commented passages with a ProseMirror decoration.
+ * A property value is a `<textarea>`, whose text no decoration can reach — so
+ * the highlight is the field's own selection, recoloured to match. The fill
+ * comes from `--comment-reveal-fill`, set alongside the attribute in
+ * `property-row-rect.ts`, so the amber has one definition rather than two that
+ * can drift apart.
+ *
+ * Attribute-scoped on purpose: without it every ordinary selection in the field
+ * would read as a comment. */
+[data-comment-reveal]::selection {
+ background-color: var(--comment-reveal-fill);
+}
+[data-comment-reveal]::-moz-selection {
+ background-color: var(--comment-reveal-fill);
+}
diff --git a/packages/app/src/lib/keyboard-shortcuts.ts b/packages/app/src/lib/keyboard-shortcuts.ts
index b134e9e2d..3fabe3bbf 100644
--- a/packages/app/src/lib/keyboard-shortcuts.ts
+++ b/packages/app/src/lib/keyboard-shortcuts.ts
@@ -520,6 +520,25 @@ const KEYBOARD_SHORTCUT_DEFINITIONS = [
},
],
},
+ {
+ id: 'add-comment',
+ category: 'wysiwyg',
+ title: msg`Comment on selection`,
+ description: msg`Open the comment composer on the current selection and add it to the dispatch queue.`,
+ scope: msg`Editor selection`,
+ bindings: [
+ {
+ // NOT ⌥⌘M, the comment chord most editors use: `toggle-editor-mode`
+ // already owns it here, and its matcher allows extra modifiers, so any
+ // Alt+M variant lands on the mode toggle instead. Shift keeps the M
+ // mnemonic while staying clear of it — the matcher below requires no
+ // Alt, which is what the mode toggle demands.
+ mac: '⇧⌘ M',
+ windowsLinux: 'Ctrl Shift M',
+ match: { key: 'm', mod: true, shiftKey: true },
+ },
+ ],
+ },
{
// Jumps from the visual editor to the markdown behind the caret's block,
// centered and highlighted. CmdOrCtrl+Alt+E stays clear of TipTap's ⌘E
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 91bd2bdd6..466600732 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -129,6 +129,7 @@
],
"2277Tu": ["Collapse graph"],
"237hSL": ["Ended"],
+ "253MN6": ["Couldn't send your comments — please try again."],
"25Pw6a": ["Cloning"],
"27TLNq": ["Enable ", ["displayName"], " CLI"],
"27XW26": ["Clone happens in the Project Navigator. Reclick the share link there."],
@@ -144,6 +145,7 @@
"2FnYUD": [
"App & system info, recent app logs, and project server logs: the essentials we need to reproduce the issue."
],
+ "2FoHU3": ["Resolve"],
"2G-56b": ["Failed to update markdownlint rules"],
"2GT3Hf": ["Global"],
"2H43L8": ["Secrets like API keys and tokens are redacted automatically."],
@@ -151,6 +153,7 @@
"2QM24L": ["All tags"],
"2RBzMG": ["Network error — check your connection and try again"],
"2Snes1": ["This sends the link's address off your machine"],
+ "2UgoBZ": ["gone"],
"2XQ8Ww": ["Open preview when agent edits"],
"2YOwme": ["Restarted — now running v", ["appRuntime"], "."],
"2YZwPB": ["Forward-links response did not match expected shape."],
@@ -204,6 +207,7 @@
],
"3SZrdj": ["Check for updates…"],
"3TSz9S": ["Minimize"],
+ "3V94ia": ["Couldn't send your comments — the workspace isn't ready."],
"3VbwPp": ["Open ", ["keyName"], " in browser"],
"3VsNTI": ["Loading document"],
"3YWddZ": ["No content changes in this version"],
@@ -256,9 +260,11 @@
"4XL6N4": [
"Detected from the editors this project is set up for. Adjust to control where every skill installs."
],
+ "4_5_n5": [["failed"], " of ", ["0"], " comments could not be removed from the queue."],
"4buZWd": ["Inherited from ", ["path"]],
"4cEClj": ["Sessions"],
"4c_a6S": ["Nothing set yet."],
+ "4eO-iB": ["Discard this comment"],
"4g19V6": ["Failed to update property"],
"4h3e0H": ["Couldn't update skills sharing — ", ["detail"], "."],
"4hJhzz": ["Table"],
@@ -293,6 +299,7 @@
"5ClEAu": ["Inline hashtag for cross-doc grouping."],
"5D3Ior": ["Hide folder"],
"5F5HYj": [["ahead"], " ahead, ", ["behind"], " behind"],
+ "5GBQ-F": ["Select this text in the property"],
"5GKMSz": ["Indent or outdent the current list item."],
"5GRxoA": ["Search files, folders, and commands for the current workspace."],
"5LXwX8": [
@@ -351,6 +358,7 @@
"5tcmwY": ["Add value"],
"5vAI6Z": ["It didn't fit into my workflow"],
"5vYdh9": ["New thread with ", ["0"]],
+ "5vhe0W": ["Add to queue"],
"5wV2qQ": ["and more"],
"5y_9lO": ["Waiting for authorization"],
"6-wLTJ": [["behind"], " behind origin"],
@@ -391,6 +399,7 @@
"6hfDJr": ["Server error: ", ["status"]],
"6iDEWA": ["Show panel"],
"6ibbCg": ["Create your first file"],
+ "6kVJ0m": ["Couldn't read the queued comments."],
"6ki7F2": [["0", "plural", { "one": ["#", " item"], "other": ["#", " items"] }]],
"6lGV3K": ["Show less"],
"6m_7We": ["Open this settings dialog."],
@@ -438,6 +447,7 @@
"7cAW1G": ["No API key is set for this endpoint. Add one above."],
"7d1a0d": ["Public"],
"7hctf2": ["Describe the project you want to create"],
+ "7iTyyh": [["queueCount", "plural", { "one": ["#", " comment"], "other": ["#", " comments"] }]],
"7jIIFX": ["You're all set up!"],
"7kb4LU": ["Approved"],
"7l15X4": ["failed"],
@@ -478,6 +488,7 @@
"If an update arrives for something you are editing, you choose which version to keep, like a merge conflict."
],
"8XQRON": ["Loading repositories"],
+ "8YymuQ": ["No agent is set up yet — opening Configure agents."],
"8_brI5": ["Name is required"],
"8cS0nH": ["Config sharing unavailable: ", ["0"], "."],
"8cpOa8": ["Couldn't disconnect — please try again."],
@@ -485,6 +496,7 @@
"8eW0WQ": ["No matching repositories."],
"8fRyLo": ["Invalid patch payload"],
"8fc_3j": ["Protected branch — cannot push"],
+ "8jeVmd": ["The terminal isn't available here — the comments stay queued."],
"8k6INX": ["Paste a personal access token for <0>", ["host"], "</0>."],
"8lwQlE": [["0"], " added, ", ["1"], " removed"],
"8m8diM": ["No location selected. Use Browse to choose a folder."],
@@ -499,6 +511,7 @@
"8vCZcs": ["Failed to open file."],
"8vETh9": ["Show"],
"8wu9lr": ["Queued"],
+ "8ycqHY": ["Add the queued comments to this message"],
"92rbk2": ["Mirror loading <0>", ["mirrorRef"], "</0>"],
"96G6Re": ["New folder"],
"96w9hU": ["Something went wrong opening this file (HTTP ", ["status"], ")."],
@@ -576,6 +589,7 @@
"ATGYL1": ["Email address"],
"AVW-K9": ["Failed to load orphan pages"],
"AWOSPo": ["Zoom in"],
+ "AYfna1": ["Remove from queue"],
"AaaESH": [
"Auto-sync is off for this worktree, inherited from ",
["project"],
@@ -694,6 +708,7 @@
"CooKEf": ["Dock sessions at the bottom"],
"CvsD6Y": ["via ", ["viaTags"]],
"CwOXMT": ["Value for ", ["keyName"]],
+ "CxVk-w": ["Comment on ", ["address"]],
"D-Oh1s": ["How to set up ", ["0"], " (opens in browser)"],
"D-_B7l": ["Connected — this endpoint returns ", ["0"], "-dimension vectors."],
"D12vtS": ["(detached)"],
@@ -748,6 +763,7 @@
"DhLHEb": ["Failed to load activity"],
"DiFKSL": ["Counting markdown files"],
"Dnn2XG": ["Automatic"],
+ "DpjYd6": ["Jump to the anchored text"],
"DrYM2Z": ["Sync disabled"],
"DsDwR-": [["0", "plural", { "one": ["#", " error"], "other": ["#", " errors"] }]],
"DskIkK": ["Sign-in stream ended without confirmation — please try again"],
@@ -848,6 +864,7 @@
"F4IYWe": ["Share doc"],
"F4vEsL": ["Sync status: ", ["syncStateLabel"]],
"F6pfE9": ["Active"],
+ "F9e3PM": ["That app isn't available — the comments stay queued."],
"FBknns": ["HTML"],
"FCAcjR": [
"Run a real terminal docked inside OpenKnowledge, starting in this project's folder."
@@ -903,6 +920,7 @@
"G1Gw0v": ["New template"],
"G1XxbZ": ["Checkbox"],
"G4-bgo": ["Ask AI (from selection)"],
+ "G4m8rL": ["Comment on selection"],
"G7-rf8": ["Pattern syntax error: ", ["message"]],
"G7bn_N": ["Start an agent"],
"G7cMuO": ["HTML preview"],
@@ -965,6 +983,7 @@
"H86f9p": ["Collapse"],
"HAvRAI": [["skillCount", "plural", { "one": ["skill"], "other": ["skills"] }]],
"HCn0Ay": ["Toggle strikethrough formatting."],
+ "HFqQui": ["Hide queued comments"],
"HGNCsl": ["Connection lost — keep this tab open, your edits will sync when reconnected"],
"HIb0vl": ["Network error — please try again"],
"HM56Bx": ["Creating..."],
@@ -973,6 +992,7 @@
"HTW0Zw": ["One more step: run <0>claude</0> in this project and approve OpenKnowledge once."],
"HdkSiO": ["New file"],
"HfI1dR": ["I already have it locally →"],
+ "Hhe73G": ["Couldn't queue that comment."],
"HjNrT0": [["0", "plural", { "one": ["#", " backlink"], "other": ["#", " backlinks"] }]],
"Hl89Qd": ["Loading templates"],
"HlmZBk": ["Documents response did not match expected shape."],
@@ -1018,8 +1038,10 @@
"IX7-sq": ["Something went wrong opening \"", ["docName"], "\"."],
"IX_uXB": ["my-feature"],
"IYciRC": ["Thanks for the report!"],
+ "IZXuGP": ["Couldn't open the terminal — the comments stay queued."],
"IajAbS": ["Add a starter pack"],
"If0crP": ["Open with AI ", ["targetDisplayName"], ", ", ["hint"]],
+ "IgN3LY": ["On selected text in <0>", ["address"], "</0>"],
"IgTwLt": ["Open this document in the editor and collapse the graph."],
"Ik-gP0": ["Heading H", ["level"], ": ", ["text"]],
"IlH15B": ["Start a session with the + button, or launch an agent from a page."],
@@ -1033,6 +1055,7 @@
"It9ARY": ["Toggle the right document panel."],
"ItxGi3": ["Attachments must total under 3 MB."],
"Ix0K8o": ["Hide external URL nodes"],
+ "IxHMdF": ["Couldn't delete that comment."],
"IxyZXD": ["Screenshot"],
"J2Mv98": ["Name (e.g. ", ["login"], ")"],
"J2_JuX": ["nothing (", ["0"], " cannot match a doc)"],
@@ -1147,6 +1170,7 @@
"LPAv9E": [["days"], "d ago"],
"LQdLio": ["New schema"],
"LQsCPn": ["Local commits are keeping this copy from updating"],
+ "LRLKnQ": ["Hide resolved"],
"LRgZAt": [["owner"], "/", ["name"], " already exists"],
"LTeJuX": ["Toggle Full Screen"],
"LXdWeS": ["Medium section heading."],
@@ -1189,6 +1213,7 @@
]
],
"LvdLef": ["Thanks for the feedback!"],
+ "LvoXJX": ["Couldn't read the queued comments — nothing was sent."],
"LwMxXg": ["Failed to open worktree."],
"M-IF14": ["Report reference"],
"M0jOcG": ["View in source markdown"],
@@ -1199,7 +1224,10 @@
"M5_9s2": ["Sending report"],
"M5mfAe": ["Add tag"],
"M6mvVi": ["Copy relative path"],
+ "M7SqjM": ["Reopen"],
+ "M92_0q": ["Close comment"],
"M9597s": ["Preparing share URL..."],
+ "MBe6TE": ["The quoted text is no longer in the document — the agent will be told."],
"MCjC9A": ["Delete ", ["deleteDescriptorLabel"]],
"MDBJwN": ["Hard to use"],
"MDZSJe": ["When the agent runs its scheduled work."],
@@ -1281,6 +1309,7 @@
],
"Nay2Yr": ["No agents match your search."],
"NcurBF": ["Pan down"],
+ "NeQ_0G": ["Work through these comments"],
"NgZwB0": [["enabledCount"], "/", ["0"], " on"],
"NjrIak": ["File: <0>", ["fixedName"], ".md</0>"],
"NkXEFS": ["Restore failed — document unchanged"],
@@ -1307,6 +1336,7 @@
"O2UpM1": ["Browse"],
"O3oNi5": ["Email"],
"O4PnDd": ["AI tool management is only available in the OpenKnowledge desktop app."],
+ "O6H89R": ["Resolved"],
"O6yEPk": ["Create a new OpenKnowledge project in the folder of your choice."],
"O7_W_a": ["Open with AI"],
"O9oQJS": ["Send report"],
@@ -1436,6 +1466,7 @@
"QfFBdJ": ["The template's filename (without `.md`)."],
"Qj4RL5": ["Completed:"],
"QlAG4m": ["Tell us more (optional)"],
+ "QlkiD5": ["Re-place on selected text"],
"QlxHAH": ["Showing results for \"", ["semanticResultsLabel"], "\""],
"QqBQu1": ["Label <0>(visible link text)</0>"],
"Qvls7J": ["Eng specs"],
@@ -1527,6 +1558,7 @@
"SItQRc": ["How do you like OpenKnowledge?"],
"SOPwPh": ["Restore to this edit"],
"SQWJ-i": ["Restore sessions"],
+ "SRBk2G": ["Couldn't add that comment."],
"STTOnz": [["keyName"], " type: complex value (nested; read-only)"],
"SUOoXn": ["Failed to open project."],
"SVLPt5": [["formatted"], " GitHub stars"],
@@ -1603,6 +1635,7 @@
"U9tm58": ["Hide problem indicators"],
"UBv8UK": ["Delete Permanently"],
"UDFrWm": ["Checking GitHub connection..."],
+ "UEdTEN": ["Orphaned"],
"UGeJuP": ["Allowed values (empty = any)"],
"UL8A9w": ["Tag"],
"UMrOy2": ["Skill \"", ["trimmedName"], "\" created"],
@@ -1642,6 +1675,7 @@
],
"UhpfxY": ["Pan left"],
"UkQGhd": ["Hide replace"],
+ "Uoux8m": ["Include this comment in the next send"],
"Up2_7p": ["Copy full path"],
"UpCz01": ["This doc"],
"UuYo7g": [
@@ -1671,6 +1705,7 @@
"External link previews show a card with the site name, page title, and description when you hover a link."
],
"VITWk5": ["Managed by OpenKnowledge"],
+ "VIiaFH": ["Couldn't read the queued comments: ", ["0"]],
"VIwCaD": ["Entry"],
"VM7H66": ["This file is binary and can't be shown as text."],
"VNgKZz": ["Advanced settings"],
@@ -1684,6 +1719,7 @@
"V_wltx": ["Enter a title for this template."],
"Va3xJe": ["Add field"],
"VbqhBI": ["Already at ", ["assetContentPath"], " — reusing."],
+ "VbyRUy": ["Comments"],
"VcqWBy": ["Upload may have succeeded but the sidebar is out of date — refresh to resync"],
"VdXv4D": ["Clone from GitHub"],
"Vftef5": ["Common markdown issues — hard tabs, heading increments, list markers, and more."],
@@ -1747,6 +1783,7 @@
"WyXG7w": ["Close all"],
"Wyxs0x": ["Path cannot contain \"..\""],
"X0ttSN": ["No tags match \"", ["tagListQuery"], "\"."],
+ "X2zUS5": ["Delete this comment"],
"X3MMeA": ["None of these problems have an automatic fix."],
"X7u0xR": [["0"], " templates available"],
"X8kjQX": ["Re-authenticate with GitHub"],
@@ -1780,6 +1817,7 @@
],
"XklovM": ["Working…"],
"Xl-UUg": ["guides/install or https://example.com"],
+ "Xm5tCT": ["Add context to this message"],
"XmJfZT": ["name"],
"XnlF3W": ["Add the next matching source selection."],
"XopE_I": ["Failed to parse backlinks error response (HTTP ", ["status"], ")"],
@@ -1812,6 +1850,7 @@
"YDL7N6": [
"Lint plugins — which rule families run and their per-rule settings — are configured on their own tab under This project → Plugins."
],
+ "YDX9lo": ["Remove this comment from the queue"],
"YEIS9T": ["Edits apply live. Light or dark is chosen from the background."],
"YEP3X2": ["Delete a table when the active table cell selection covers the full table."],
"YGIi_c": ["Reinstall"],
@@ -1864,6 +1903,7 @@
"ZBt4rI": ["Instruction for the AI"],
"ZBxvV3": ["New Terminal"],
"ZDOq9A": ["What you share is sent to the OpenKnowledge team."],
+ "ZHAM1l": ["Include in dispatch"],
"ZI8uvA": ["No problems found."],
"ZNK2Tq": ["root"],
"ZQJ1IV": ["Activate the last editor tab."],
@@ -1991,13 +2031,16 @@
],
"ajz9F8": ["Couldn't load conflict content for ", ["filePath"], ". Try reloading the page."],
"ak4LLg": ["Clear menu"],
+ "akmOT9": ["Edit this comment"],
"anmUZq": ["Missing a feature"],
+ "aoT2xX": ["This comment is on the whole property"],
"aoa6xA": ["network error (is `ok ui` running?)"],
"arUUsK": ["Product updates"],
"ax9kie": ["Link preview settings not yet loaded — try again in a moment"],
"axQ1h6": ["Anything you'd like to add? (optional)"],
"az8lvo": ["Off"],
"b18t0_": ["Close diff"],
+ "b24kPi": ["Queue"],
"b3Thhd": ["Upload failed"],
"b4AQFK": ["Open activity panel for ", ["tooltipName"], ", editing ", ["realCurrentDoc"]],
"b4VvP-": [
@@ -2012,6 +2055,9 @@
"bBcFK_": ["Open emoji picker for ", ["keyName"]],
"bD8I7O": ["Complete"],
"bF22t6": ["Remove field ", ["field"]],
+ "bGOTXx": [
+ "Open the comment composer on the current selection and add it to the dispatch queue."
+ ],
"bGa3Fk": ["Uploading file"],
"bH382I": ["Edit this HTML — the preview updates live."],
"bKt9Jk": ["No active or recent OpenKnowledge projects were found."],
@@ -2024,6 +2070,7 @@
"bbJ-VR": ["Zoom Out"],
"bcDHUM": [["descriptorLabel"], " — render error, source editable below"],
"bcjYUA": ["Fold or unfold source"],
+ "bcm0pR": ["the open agent"],
"bkQRMh": ["Paragraph"],
"blFttG": ["Search projects"],
"bmC18N": ["Clearing local collaboration data for \"", ["docName"], "\" before reconnecting."],
@@ -2033,6 +2080,7 @@
"When enabled, the agent opens or refreshes the preview after each edit. Disable if you manage your own preview window (OK Desktop, a browser tab on another display, etc.)."
],
"bwil08": ["Building <0>openknowledge.skill</0> and opening the Claude Desktop App"],
+ "bwy8Y7": ["On <0>", ["address"], "</0>"],
"c1LZZH": ["Link copied."],
"c2ktXL": ["Previous reports"],
"c3XJ18": ["Help"],
@@ -2143,6 +2191,7 @@
"dXCi3J": ["Something broke"],
"dXOolp": ["Syncing your changes"],
"dXWMFn": ["Removes this skill from your editors."],
+ "dXooEp": ["Nothing queued"],
"dYCvMf": ["Couldn't resume this conversation: ", ["0"]],
"darW93": [
[
@@ -2205,10 +2254,12 @@
"eazHgv": [
"Git can't track this folder — it's empty or contains only ignored files. The link won't work until you add a tracked document."
],
+ "eiUA4k": [["count", "plural", { "one": ["#", " comment"], "other": ["#", " comments"] }]],
"el312q": ["Install skills into"],
"emgiet": ["Authoritative content; mirrored verbatim everywhere it's referenced."],
"enPTnx": ["line ", ["displayLine"]],
"eneWvv": ["Draft"],
+ "eoEUI3": ["Couldn't resolve that comment."],
"epuNYK": [
"Mark a block as the source of truth. Mirrors elsewhere update live as you edit it."
],
@@ -2360,6 +2411,7 @@
"hnq8fP": ["Remove ", ["label"], " from context"],
"hpDtUm": ["External wiki link"],
"hpzRlK": ["Reopen closed tab"],
+ "hqVQbT": ["Add Comment"],
"hvZwVx": ["Convert"],
"hwFOFD": ["Settings failed to load"],
"hxBHxQ": ["A line with a footnote<0><1>[1]</1></0> and a definition shown below."],
@@ -2428,6 +2480,7 @@
"iv452l": ["Documentation for ", ["0"], " (opens in browser)"],
"iy64Li": ["Full sync — your edits are committed and pushed to your remote automatically."],
"iycx_A": ["Pushing"],
+ "j0ItfO": ["Show resolved (", ["0"], ")"],
"j2229h": ["Removing OpenKnowledge files…"],
"j2kt1j": [
"Open a new session with your preferred AI. With text selected, stage it there instead of running it."
@@ -2543,9 +2596,11 @@
"kolRU1": ["Do you want to permanently delete instead?"],
"kooyLJ": ["Failed to rename the field"],
"kpqWwG": ["This ", ["targetNoun"], " was removed from branch <0>", ["branch"], "</0>."],
+ "kq-Qj4": ["Couldn't work out where to send the comments — they stay queued."],
"ktspdq": ["Tint and badge files that have lint or link problems, without opening them."],
"ku0yLQ": ["Pages are embedded the first time a search needs them."],
"ky9Tuc": ["Edit ", ["0"], " source"],
+ "kzpkcn": ["Couldn't save that edit."],
"l-4nnw": ["Search rules"],
"l17ab4": ["Could not write project files. Try a different location."],
"l1aQKz": ["Visual editor table"],
@@ -2574,6 +2629,7 @@
["4"],
") that won't touch the rest of your system."
],
+ "l7X_SM": ["Send to AI"],
"l9HUtd": [
"Toggle the bottom terminal panel. With text selected, stage it for your preferred AI instead."
],
@@ -2583,6 +2639,7 @@
"lHCR4I": ["Clear the field to reset back to the default OpenAI endpoint."],
"lHwYMr": ["Server error: ", ["status"], " ", ["statusText"]],
"lI0Td2": ["Use letters, digits, <0>_</0> and <1>-</1> only."],
+ "lISYEX": ["Couldn't reopen that comment."],
"lKQnp-": ["Installed ", ["0"], " ", ["1"]],
"lPzyrU": ["All hunks resolved"],
"lVWEIL": ["Indexed ", ["embedded"], " of ", ["total"], " pages."],
@@ -2656,6 +2713,7 @@
]
],
"mk2poV": ["e.g. server.ts"],
+ "mlvM8g": ["Couldn't re-place that comment."],
"mmpzAq": ["Wrap long lines in the markdown source editor."],
"mo22UP": ["Toggle inline code formatting."],
"mqSwZH": [
@@ -2698,6 +2756,7 @@
". Any local edits will be replaced — your current version is saved to history first, so you can restore it."
],
"nDT8qt": ["Initialized ", ["0"], " but could not open it."],
+ "nG-XA9": ["The anchored text is gone. You can re-place it on selected text."],
"nGAFeH": [
"Reports you've generated on this Mac. Retry a send, reveal a file, or delete one you no longer need."
],
@@ -2795,10 +2854,12 @@
"ogAuyr": ["Back to document view"],
"ohUJJM": ["Plugins"],
"oi4zaa": ["Remember this for future agents"],
+ "ojGc_T": ["Open comment"],
"omXJcU": ["Close others"],
"onTlRk": ["Couldn't update skills sharing"],
"optX0N": [["0"], "h ago"],
"oqB2ez": ["Previous match"],
+ "os6dRM": ["Couldn't remove that comment from the queue."],
"osRqlv": ["Open delete confirmation for the selected file-tree items."],
"ot5BRK": ["Duplicate selected file or folder"],
"otE4aj": ["Show external URL nodes"],
@@ -2819,6 +2880,7 @@
"pBROkv": ["Thanks for subscribing. Watch your inbox for product updates."],
"pEQFsW": ["No matching projects."],
"pFPzHA": ["Emoji picker"],
+ "pFRz_E": ["Leave these comments out of this message"],
"pFagOn": ["Source editing"],
"pHYP6v": ["Open <0>Customize</0> in the sidebar <1/> <2>Skills</2>."],
"pQf2Ux": [".ok/skills is back to local-only."],
@@ -2845,6 +2907,7 @@
"pzutoc": ["Italic"],
"q2kXMG": ["Inline Math"],
"q3TWG7": ["Move to Trash"],
+ "q3W2nd": ["Couldn't add that comment: ", ["0"]],
"q4YJl_": ["The terminal session ended (exit code ", ["0"], ")."],
"q6-JVU": ["Loading pages"],
"q7F5am": ["title"],
@@ -2883,11 +2946,13 @@
"qjHMHf": ["Failed to disable sync — ", ["detail"]],
"qmL1UG": ["Uploading securely"],
"qo4zCg": ["Path cannot contain backslashes"],
+ "qokN44": ["Show queued comments"],
"qpQwGC": ["Describe what you're working on and the agent sets it up for you."],
"qribBG": ["schema ", ["deleteTarget"]],
"qvWGzP": ["Collapse all"],
"qyLmWw": ["Source editor search panel"],
"r-OJYm": ["Enter a valid branch name (no spaces, no leading dot, no \"..\")."],
+ "r0mxIn": ["Remove from the queue"],
"r2eKE3": ["Sign in to ", ["agentName"], " first"],
"r4R7AZ": ["Network error during cleanup"],
"r51jLC": ["File saved & Claude Desktop App opened"],
@@ -2918,6 +2983,7 @@
],
"rVxu1k": ["No pages link here yet."],
"rXz97P": ["Numbered list of items."],
+ "rY9lqA": ["Send queue to"],
"rZ9HZq": ["To do"],
"rZVMkf": ["Visual editor replace input focused"],
"rageVb": ["Custom HTML with a live preview pane (sandboxed iframe)."],
@@ -2934,6 +3000,7 @@
"roAe2K": ["Link URL"],
"roiUQQ": ["This page doesn't link to anything yet."],
"rppgXF": ["Disconnecting"],
+ "rscgd_": ["Go to this comment in ", ["0"]],
"rssK8c": ["Ignore patterns (raw text)"],
"rtdR4v": ["Show or hide Files"],
"rwrPbS": ["Component boundary navigation"],
@@ -2961,6 +3028,7 @@
"sIxSSP": ["Resolve conflict in your terminal"],
"sJK6pq": ["Permission denied"],
"sJWhgo": ["Unknown component: ", ["unregisteredComponentName"]],
+ "sKEgGd": ["Send to chat"],
"sNeKjP": ["Failed to store the token — try again"],
"sOxZaS": ["Failed to load graph"],
"sZ2IOu": [
@@ -2979,6 +3047,7 @@
"seeS6l": ["Setup OpenKnowledge in this folder?"],
"sgmRY8": ["Skipped downloading ", ["0"], "."],
"shNd9t": ["Slash command menu"],
+ "siXSpl": ["Sent, but the comments could not be marked done — they are still queued."],
"skf5Ix": ["Indent or outdent source editor lines."],
"sn5BEU": [
["sizeText"],
@@ -3016,6 +3085,8 @@
"t_YqKh": ["Remove"],
"tcjTlU": ["Starter packs"],
"teD0H9": ["Couldn't open a worktree for that branch."],
+ "teFjfG": ["No agent is set up yet — pick one from the send menu."],
+ "teS4nP": ["Nothing queued. Comment on a passage to add it here."],
"ten9en": ["Recent project"],
"tfDRzk": ["Save"],
"tfi40B": ["Failed to create page"],
@@ -3110,10 +3181,12 @@
"vGeNNQ": ["Copy a prompt and paste it into your agent to set up your project."],
"vIxrEk": ["Fit width"],
"vLyv1R": ["Hide"],
+ "vPF04k": ["Start a new chat"],
"vPKX2i": ["In app (beta)"],
"vPXOUw": ["Toggle source view"],
"vQIVHc": ["Folder properties"],
"vWc9a0": ["Type to edit; <0>⌘ Enter</0> saves, <1>Esc</1> cancels."],
+ "vYOUOk": ["Add a comment"],
"vYPvPB": ["Switch project…"],
"vZVeFG": ["Upload failed — please try again"],
"v_2_3v": ["Deleted ", ["file"]],
@@ -3245,6 +3318,7 @@
"xlQpTE": ["More refusal options"],
"xloBjn": ["Relative Path"],
"xnP32l": ["No description yet — add one so agents know when to use this skill."],
+ "xo6PEb": ["Choose where to send the queue"],
"xrVr_k": ["Couldn't create skill: ", ["0"]],
"xsZhu-": ["Page number"],
"xzAmL_": ["Auto-approved"],
@@ -3355,6 +3429,7 @@
"zkz0Fg": ["Set up syncing"],
"zlErBl": ["Page headings error response did not match RFC 9457"],
"zo3Dl7": ["Toggle thumbnails"],
+ "zpfN9p": ["No comments yet. Select text in the document to add one."],
"zq2eBA": ["View in source"],
"zrP8HX": [
"Frontmatter every document created from this template starts with. Values are YAML — a list is <0>[a, b]</0>; <1>{",
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index 205dfa3b6..4fbeb8023 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -225,6 +225,8 @@ msgid "{0} hex value"
msgstr "{0} hex value"
#. placeholder {0}: resolvedTarget.displayName
+#. placeholder {0}: target.displayName
+#: src/comments/use-comment-delivery.ts
#: src/components/BottomComposer.tsx
msgid "{0} isn't installed yet — opening its download page."
msgstr "{0} isn't installed yet — opening its download page."
@@ -347,6 +349,10 @@ msgstr "{conflictCount, plural, one {# conflict} other {# conflicts}}"
msgid "{conflictCount, plural, one {# file conflicted} other {# files conflicted}}"
msgstr "{conflictCount, plural, one {# file conflicted} other {# files conflicted}}"
+#: src/comments/comment-chips.tsx
+msgid "{count, plural, one {# comment} other {# comments}}"
+msgstr "{count, plural, one {# comment} other {# comments}}"
+
#: src/components/TrashFailureModal.tsx
msgid "{count, plural, one {# item could not be moved to the Trash. Do you want to permanently delete instead?} other {# items could not be moved to the Trash. Do you want to permanently delete instead?}}"
msgstr "{count, plural, one {# item could not be moved to the Trash. Do you want to permanently delete instead?} other {# items could not be moved to the Trash. Do you want to permanently delete instead?}}"
@@ -407,6 +413,7 @@ msgstr "{diffMin}m ago"
msgid "{displayName} ({bin}) isn't installed or on your PATH."
msgstr "{displayName} ({bin}) isn't installed or on your PATH."
+#: src/comments/use-comment-agent-picker.ts
#: src/components/BottomComposer.tsx
#: src/components/empty-state/CreatePromptComposer.tsx
#: src/components/handoff/OpenInAgentContextSubmenu.tsx
@@ -432,6 +439,11 @@ msgstr "{docName} is {0}. OpenKnowledge currently opens files up to {1}."
msgid "{enabledCount}/{0} on"
msgstr "{enabledCount}/{0} on"
+#. placeholder {0}: ids.length
+#: src/comments/store.ts
+msgid "{failed} of {0} comments could not be removed from the queue."
+msgstr "{failed} of {0} comments could not be removed from the queue."
+
#: src/components/FileTree.tsx
msgid "{failedCount, plural, one {1 file failed to upload} other {{failedCount} files failed to upload}}"
msgstr "{failedCount, plural, one {1 file failed to upload} other {{failedCount} files failed to upload}}"
@@ -569,6 +581,10 @@ msgstr "{phase} — {pct}%"
msgid "{propPanelDescriptorLabel} Properties"
msgstr "{propPanelDescriptorLabel} Properties"
+#: src/components/ComposerAddContextMenu.tsx
+msgid "{queueCount, plural, one {# comment} other {# comments}}"
+msgstr "{queueCount, plural, one {# comment} other {# comments}}"
+
#: src/components/ActivityModeContent.tsx
#: src/components/ActivityPanelBurstRow.tsx
#: src/components/ActivityPanelFileRow.tsx
@@ -908,6 +924,11 @@ msgstr "Actual Size"
msgid "Add"
msgstr "Add"
+#: src/comments/CommentSelectionAffordance.tsx
+#: src/comments/PropertyCommentButton.tsx
+msgid "Add a comment"
+msgstr "Add a comment"
+
#: src/components/settings/SearchSection.tsx
msgid "Add a key"
msgstr "Add a key"
@@ -928,6 +949,14 @@ msgstr "Add another pattern"
msgid "Add at least one letter or number."
msgstr "Add at least one letter or number."
+#: src/comments/CommentSelectionAffordance.tsx
+msgid "Add Comment"
+msgstr "Add Comment"
+
+#: src/components/ComposerAddContextMenu.tsx
+msgid "Add context to this message"
+msgstr "Add context to this message"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Add cursors or select matching occurrences through CodeMirror."
msgstr "Add cursors or select matching occurrences through CodeMirror."
@@ -1000,6 +1029,14 @@ msgstr "Add the <0>ok</0> command to your terminal"
msgid "Add the next matching source selection."
msgstr "Add the next matching source selection."
+#: src/comments/comment-chips.tsx
+msgid "Add the queued comments to this message"
+msgstr "Add the queued comments to this message"
+
+#: src/comments/PropertyCommentButton.tsx
+msgid "Add to queue"
+msgstr "Add to queue"
+
#: src/components/settings/frontmatter-schema-field-editor.tsx
msgid "Add value"
msgstr "Add value"
@@ -1257,11 +1294,11 @@ msgstr "Ask {0} CLI"
msgid "Ask {agentName}"
msgstr "Ask {agentName}"
+#: src/comments/CommentBubbleButton.tsx
#: src/components/BottomComposer.tsx
#: src/components/EditorFooter.tsx
#: src/components/OnboardingCard.tsx
#: src/components/ProblemsPanel.tsx
-#: src/editor/bubble-menu/EditWithAiBubbleButton.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "Ask AI"
msgstr "Ask AI"
@@ -1615,6 +1652,7 @@ msgstr "Can't safely edit this project config"
msgid "Can't safely edit this tool's config"
msgstr "Can't safely edit this tool's config"
+#: src/comments/PropertyCommentButton.tsx
#: src/components/acp/ThreadHistoryMenu.tsx
#: src/components/ActivityPanelBurstRow.tsx
#: src/components/AuthModal.tsx
@@ -1699,6 +1737,7 @@ msgstr "Checkbox"
msgid "Checked by: {0}"
msgstr "Checked by: {0}"
+#: src/comments/CommentQueuePanel.tsx
#: src/components/BottomComposer.tsx
msgid "Checking for agents"
msgstr "Checking for agents"
@@ -1745,6 +1784,10 @@ msgstr "Choose agent"
msgid "Choose what a new session starts"
msgstr "Choose what a new session starts"
+#: src/comments/CommentQueuePanel.tsx
+msgid "Choose where to send the queue"
+msgstr "Choose where to send the queue"
+
#: src/components/settings/SharingSection.tsx
msgid "Choose whether this project's OpenKnowledge setup, including its AI-tool connections, is saved with the project so teammates get it too, or kept only on your computer."
msgstr "Choose whether this project's OpenKnowledge setup, including its AI-tool connections, is saved with the project so teammates get it too, or kept only on your computer."
@@ -1781,6 +1824,7 @@ msgstr "Claude Desktop"
msgid "Cleanup log"
msgstr "Cleanup log"
+#: src/comments/CommentQueuePanel.tsx
#: src/components/settings/SearchSection.tsx
msgid "Clear"
msgstr "Clear"
@@ -1866,6 +1910,7 @@ msgstr "Cloning {repoName}..."
msgid "Cloning..."
msgstr "Cloning..."
+#: src/comments/CommentsPanel.tsx
#: src/components/EditorTabs.tsx
#: src/components/FeedbackForm.tsx
#: src/components/InstallInClaudeDesktopDialog.tsx
@@ -1895,6 +1940,10 @@ msgstr "Close all"
msgid "Close all unpinned"
msgstr "Close all unpinned"
+#: src/comments/CommentMarginRail.tsx
+msgid "Close comment"
+msgstr "Close comment"
+
#: src/components/AgentDiffPane.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Close diff"
@@ -2021,6 +2070,19 @@ msgstr "Commands"
msgid "Commands run with the full access of your macOS user account on this machine. Turn this off to disable the shell."
msgstr "Commands run with the full access of your macOS user account on this machine. Turn this off to disable the shell."
+#: src/comments/PropertyCommentButton.tsx
+msgid "Comment on {address}"
+msgstr "Comment on {address}"
+
+#: src/lib/keyboard-shortcuts.ts
+msgid "Comment on selection"
+msgstr "Comment on selection"
+
+#: src/comments/CommentsPanel.tsx
+#: src/components/DocPanel.tsx
+msgid "Comments"
+msgstr "Comments"
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "Commit or stash changes to switch:"
msgstr "Commit or stash changes to switch:"
@@ -2507,6 +2569,15 @@ msgstr "Could not validate folder. Please try again."
msgid "Could not write project files. Try a different location."
msgstr "Could not write project files. Try a different location."
+#. placeholder {0}: err.message
+#: src/comments/store.ts
+msgid "Couldn't add that comment: {0}"
+msgstr "Couldn't add that comment: {0}"
+
+#: src/comments/store.ts
+msgid "Couldn't add that comment."
+msgstr "Couldn't add that comment."
+
#. placeholder {0}: err instanceof Error ? err.message : String(err)
#: src/components/settings/AiToolsSection.tsx
#: src/components/settings/ProjectAiToolsSection.tsx
@@ -2566,6 +2637,10 @@ msgstr "Couldn't delete skill: {error}"
msgid "Couldn't delete template: {error}"
msgstr "Couldn't delete template: {error}"
+#: src/comments/store.ts
+msgid "Couldn't delete that comment."
+msgstr "Couldn't delete that comment."
+
#: src/components/settings/AccountSection.tsx
msgid "Couldn't disconnect — please try again."
msgstr "Couldn't disconnect — please try again."
@@ -2643,6 +2718,10 @@ msgstr "Couldn't open document"
msgid "Couldn't open the terminal — please try again."
msgstr "Couldn't open the terminal — please try again."
+#: src/comments/use-comment-delivery.ts
+msgid "Couldn't open the terminal — the comments stay queued."
+msgstr "Couldn't open the terminal — the comments stay queued."
+
#: src/components/NewWorktreeDialog.tsx
msgid "Couldn't open the worktree. Try again."
msgstr "Couldn't open the worktree. Try again."
@@ -2651,6 +2730,14 @@ msgstr "Couldn't open the worktree. Try again."
msgid "Couldn't pull from GitHub. Check your connection and sign-in, then retry."
msgstr "Couldn't pull from GitHub. Check your connection and sign-in, then retry."
+#: src/comments/store.ts
+msgid "Couldn't queue that comment."
+msgstr "Couldn't queue that comment."
+
+#: src/comments/store.ts
+msgid "Couldn't re-place that comment."
+msgstr "Couldn't re-place that comment."
+
#: src/components/ConnectingBanner.tsx
msgid "Couldn't reach collab server — {errorDetail}. Try <0>ok status</0> or check <1>.ok/local/last-spawn-error.log</1>."
msgstr "Couldn't reach collab server — {errorDetail}. Try <0>ok status</0> or check <1>.ok/local/last-spawn-error.log</1>."
@@ -2671,6 +2758,19 @@ msgstr "Couldn't reach the embeddings provider — retry"
msgid "Couldn't reach the endpoint. Check the URL and that the server is up."
msgstr "Couldn't reach the endpoint. Check the URL and that the server is up."
+#: src/comments/store.ts
+msgid "Couldn't read the queued comments — nothing was sent."
+msgstr "Couldn't read the queued comments — nothing was sent."
+
+#. placeholder {0}: err.message
+#: src/comments/store.ts
+msgid "Couldn't read the queued comments: {0}"
+msgstr "Couldn't read the queued comments: {0}"
+
+#: src/comments/queue-attachment.ts
+msgid "Couldn't read the queued comments."
+msgstr "Couldn't read the queued comments."
+
#: src/components/EditorActivityPool.tsx
msgid "Couldn't reconnect after server restart"
msgstr "Couldn't reconnect after server restart"
@@ -2679,6 +2779,10 @@ msgstr "Couldn't reconnect after server restart"
msgid "Couldn't remove <0>{targetGitPath}</0>: {removeGitError}"
msgstr "Couldn't remove <0>{targetGitPath}</0>: {removeGitError}"
+#: src/comments/store.ts
+msgid "Couldn't remove that comment from the queue."
+msgstr "Couldn't remove that comment from the queue."
+
#. placeholder {0}: skill.name
#. placeholder {1}: result.error
#: src/components/SkillRenameDialog.tsx
@@ -2695,6 +2799,14 @@ msgstr "Couldn't rename skill: {0}"
msgid "Couldn't rename template: {0}"
msgstr "Couldn't rename template: {0}"
+#: src/comments/store.ts
+msgid "Couldn't reopen that comment."
+msgstr "Couldn't reopen that comment."
+
+#: src/comments/store.ts
+msgid "Couldn't resolve that comment."
+msgstr "Couldn't resolve that comment."
+
#: src/components/DiffViewBoundary.tsx
msgid "Couldn't resolve the conflict for {filePath}."
msgstr "Couldn't resolve the conflict for {filePath}."
@@ -2728,6 +2840,10 @@ msgstr "Couldn't run the test. Check that OpenKnowledge is still running."
msgid "Couldn't save template: {error}"
msgstr "Couldn't save template: {error}"
+#: src/comments/store.ts
+msgid "Couldn't save that edit."
+msgstr "Couldn't save that edit."
+
#: src/components/settings/SearchSection.tsx
msgid "Couldn't save the key — please try again."
msgstr "Couldn't save the key — please try again."
@@ -2740,6 +2856,14 @@ msgstr "Couldn't save the resolution for {filePath}."
msgid "Couldn't send the report"
msgstr "Couldn't send the report"
+#: src/components/BottomComposer.tsx
+msgid "Couldn't send your comments — please try again."
+msgstr "Couldn't send your comments — please try again."
+
+#: src/comments/use-comment-delivery.ts
+msgid "Couldn't send your comments — the workspace isn't ready."
+msgstr "Couldn't send your comments — the workspace isn't ready."
+
#: src/components/BottomComposer.tsx
msgid "Couldn't send your prompt — please try again."
msgstr "Couldn't send your prompt — please try again."
@@ -2787,6 +2911,10 @@ msgstr "Couldn't update skills sharing"
msgid "Couldn't update skills sharing — {detail}."
msgstr "Couldn't update skills sharing — {detail}."
+#: src/comments/use-comment-delivery.ts
+msgid "Couldn't work out where to send the comments — they stay queued."
+msgstr "Couldn't work out where to send the comments — they stay queued."
+
#: src/components/ConsentDialogBody.tsx
msgid "Counting markdown files"
msgstr "Counting markdown files"
@@ -3081,6 +3209,10 @@ msgstr "Delete selected items"
msgid "Delete selected table"
msgstr "Delete selected table"
+#: src/comments/CommentsPanel.tsx
+msgid "Delete this comment"
+msgstr "Delete this comment"
+
#: src/components/acp/ThreadHistoryMenu.tsx
msgid "Delete this conversation?"
msgstr "Delete this conversation?"
@@ -3242,6 +3374,10 @@ msgstr "Disable Themes"
msgid "Disambiguates similarly-named templates in the menu."
msgstr "Disambiguates similarly-named templates in the menu."
+#: src/comments/CommentSelectionAffordance.tsx
+msgid "Discard this comment"
+msgstr "Discard this comment"
+
#: src/components/settings/AccountSection.tsx
msgid "Disconnect"
msgstr "Disconnect"
@@ -3521,6 +3657,10 @@ msgstr "Edit source"
msgid "Edit source pane and code property fields"
msgstr "Edit source pane and code property fields"
+#: src/comments/CommentsPanel.tsx
+msgid "Edit this comment"
+msgstr "Edit this comment"
+
#: src/editor/slash-command/embed-starter-items.tsx
msgid "Edit this HTML — the preview updates live."
msgstr "Edit this HTML — the preview updates live."
@@ -4607,6 +4747,16 @@ msgstr "Go to line {0}"
msgid "Go to line {0} in {1}"
msgstr "Go to line {0} in {1}"
+#. placeholder {0}: docBasename(thread.docName)
+#: src/comments/comment-chips.tsx
+#: src/comments/CommentQueuePanel.tsx
+msgid "Go to this comment in {0}"
+msgstr "Go to this comment in {0}"
+
+#: src/comments/comment-chips.tsx
+msgid "gone"
+msgstr "gone"
+
#: src/components/FeedbackForm.tsx
msgid "Good"
msgstr "Good"
@@ -4761,10 +4911,18 @@ msgstr "Hide panel ({panelShortcutLabel})"
msgid "Hide problem indicators"
msgstr "Hide problem indicators"
+#: src/comments/comment-chips.tsx
+msgid "Hide queued comments"
+msgstr "Hide queued comments"
+
#: src/editor/find-replace/FindReplaceBar.tsx
msgid "Hide replace"
msgstr "Hide replace"
+#: src/comments/CommentsPanel.tsx
+msgid "Hide resolved"
+msgstr "Hide resolved"
+
#: src/components/BottomComposer.tsx
msgid "Hide selection preview"
msgstr "Hide selection preview"
@@ -4928,6 +5086,14 @@ msgstr "In app (beta)"
msgid "In the Claude Desktop App"
msgstr "In the Claude Desktop App"
+#: src/comments/CommentQueuePanel.tsx
+msgid "Include in dispatch"
+msgstr "Include in dispatch"
+
+#: src/comments/comment-chips.tsx
+msgid "Include this comment in the next send"
+msgstr "Include this comment in the next send"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Indent or outdent list item"
msgstr "Indent or outdent list item"
@@ -5183,6 +5349,10 @@ msgstr "Jump to page {pageNumber}"
msgid "Jump to tab 1-8"
msgstr "Jump to tab 1-8"
+#: src/comments/CommentsPanel.tsx
+msgid "Jump to the anchored text"
+msgstr "Jump to the anchored text"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Jump to the markdown source for the block at the cursor, centered and highlighted."
msgstr "Jump to the markdown source for the block at the cursor, centered and highlighted."
@@ -5264,6 +5434,10 @@ msgstr "Learn more"
msgid "Learn more about {title}"
msgstr "Learn more about {title}"
+#: src/comments/comment-chips.tsx
+msgid "Leave these comments out of this message"
+msgstr "Leave these comments out of this message"
+
#: src/components/settings/TerminalSection.tsx
msgid "Let agents use OpenKnowledge without asking"
msgstr "Let agents use OpenKnowledge without asking"
@@ -6019,10 +6193,19 @@ msgstr "No <0>.markdownlint.*</0> file yet — every rule runs on the same defau
msgid "No active or recent OpenKnowledge projects were found."
msgstr "No active or recent OpenKnowledge projects were found."
+#: src/comments/use-comment-delivery.ts
+msgid "No agent is set up yet — opening Configure agents."
+msgstr "No agent is set up yet — opening Configure agents."
+
+#: src/components/BottomComposer.tsx
+msgid "No agent is set up yet — pick one from the send menu."
+msgstr "No agent is set up yet — pick one from the send menu."
+
#: src/components/settings/ConfigureAgentsSection.tsx
msgid "No agents available."
msgstr "No agents available."
+#: src/comments/CommentQueuePanel.tsx
#: src/components/BottomComposer.tsx
msgid "No agents enabled"
msgstr "No agents enabled"
@@ -6051,6 +6234,10 @@ msgstr "No changes"
msgid "No collab server for this worktree — run <0>ok start</0> here, or reopen the project."
msgstr "No collab server for this worktree — run <0>ok start</0> here, or reopen the project."
+#: src/comments/CommentsPanel.tsx
+msgid "No comments yet. Select text in the document to add one."
+msgstr "No comments yet. Select text in the document to add one."
+
#: src/components/AgentDiffPane.tsx
msgid "No content changes at this version."
msgstr "No content changes at this version."
@@ -6383,6 +6570,14 @@ msgstr "nothing ({0} cannot match a doc)"
msgid "nothing ({0} is not a valid pattern)"
msgstr "nothing ({0} is not a valid pattern)"
+#: src/components/ComposerAddContextMenu.tsx
+msgid "Nothing queued"
+msgstr "Nothing queued"
+
+#: src/comments/CommentQueuePanel.tsx
+msgid "Nothing queued. Comment on a passage to add it here."
+msgstr "Nothing queued. Comment on a passage to add it here."
+
#: src/components/FolderPropertiesCard.tsx
msgid "Nothing set yet."
msgstr "Nothing set yet."
@@ -6453,6 +6648,14 @@ msgstr "On — hovering an external link sends its URL to the destination site t
msgid "On — your search queries and the text of matching pages are sent to your embeddings provider (OpenAI by default) to compute embeddings."
msgstr "On — your search queries and the text of matching pages are sent to your embeddings provider (OpenAI by default) to compute embeddings."
+#: src/comments/PropertyCommentButton.tsx
+msgid "On <0>{address}</0>"
+msgstr "On <0>{address}</0>"
+
+#: src/comments/PropertyCommentButton.tsx
+msgid "On selected text in <0>{address}</0>"
+msgstr "On selected text in <0>{address}</0>"
+
#. Next step for a Cursor project MCP row — Cursor leaves project servers disabled
#: src/components/settings/ProjectAiToolsSection.tsx
msgid "One more step: enable it in Cursor → Settings → Tools & MCP (Cursor leaves project servers off until you turn them on)."
@@ -6578,6 +6781,10 @@ msgstr "Open CodeMirror's go-to-line prompt."
msgid "Open CodeMirror's lint diagnostics panel."
msgstr "Open CodeMirror's lint diagnostics panel."
+#: src/comments/CommentMarginRail.tsx
+msgid "Open comment"
+msgstr "Open comment"
+
#: src/components/FileTree.tsx
msgid "Open containing folder"
msgstr "Open containing folder"
@@ -6715,6 +6922,10 @@ msgstr "Open source: {mirrorSrc}"
msgid "Open that worktree instead"
msgstr "Open that worktree instead"
+#: src/lib/keyboard-shortcuts.ts
+msgid "Open the comment composer on the current selection and add it to the dispatch queue."
+msgstr "Open the comment composer on the current selection and add it to the dispatch queue."
+
#: src/lib/keyboard-shortcuts.ts
msgid "Open the insert menu in an empty or active text position."
msgstr "Open the insert menu in an empty or active text position."
@@ -6874,6 +7085,10 @@ msgstr "Original file — before this agent's edits."
msgid "Orphan mode"
msgstr "Orphan mode"
+#: src/comments/CommentsPanel.tsx
+msgid "Orphaned"
+msgstr "Orphaned"
+
#: src/components/GraphPanel.tsx
msgid "Orphans"
msgstr "Orphans"
@@ -7384,10 +7599,19 @@ msgstr "Push failed — check the server logs for details."
msgid "Pushing"
msgstr "Pushing"
+#: src/comments/comment-chips.tsx
+#: src/comments/CommentQueuePanel.tsx
+#: src/comments/CommentsPanel.tsx
+#: src/comments/CommentsTab.tsx
+#: src/components/ComposerAddContextMenu.tsx
+msgid "Queue"
+msgstr "Queue"
+
#: src/components/acp/ThreadView.tsx
msgid "Queue message"
msgstr "Queue message"
+#: src/comments/CommentsPanel.tsx
#: src/components/acp/ThreadView.tsx
msgid "Queued"
msgstr "Queued"
@@ -7412,6 +7636,10 @@ msgstr "Re-authenticate with GitHub Enterprise Server"
msgid "Re-embedding happens as searches run, so coverage restarts at zero and refills."
msgstr "Re-embedding happens as searches run, so coverage restarts at zero and refills."
+#: src/comments/CommentsPanel.tsx
+msgid "Re-place on selected text"
+msgstr "Re-place on selected text"
+
#: src/components/ProblemsPanel.tsx
msgid "Re-run the project audit"
msgstr "Re-run the project audit"
@@ -7598,11 +7826,19 @@ msgstr "Remove failed: {error}"
msgid "Remove field {field}"
msgstr "Remove field {field}"
+#: src/comments/CommentQueuePanel.tsx
+msgid "Remove from queue"
+msgstr "Remove from queue"
+
#: src/components/NavigatorApp.tsx
#: src/components/recent-remove-controls.tsx
msgid "Remove from recent projects"
msgstr "Remove from recent projects"
+#: src/comments/CommentsPanel.tsx
+msgid "Remove from the queue"
+msgstr "Remove from the queue"
+
#. placeholder {0}: index + 1
#: src/components/ArrayOfObjectsWidget.tsx
msgid "Remove item {0}"
@@ -7633,6 +7869,10 @@ msgstr "Remove selection"
msgid "Remove the parent <0>.git</0> folder"
msgstr "Remove the parent <0>.git</0> folder"
+#: src/comments/comment-chips.tsx
+msgid "Remove this comment from the queue"
+msgstr "Remove this comment from the queue"
+
#: src/lib/install-recent-removed-listener.ts
msgid "Removed \"{projectName}\" from recent projects. Its folder no longer exists."
msgstr "Removed \"{projectName}\" from recent projects. Its folder no longer exists."
@@ -7710,6 +7950,10 @@ msgstr "Renaming changes the file on disk and the id agents use to pick this tem
msgid "Rendered"
msgstr "Rendered"
+#: src/comments/CommentsPanel.tsx
+msgid "Reopen"
+msgstr "Reopen"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Reopen closed tab"
msgstr "Reopen closed tab"
@@ -7843,10 +8087,18 @@ msgstr "Reset view filters"
msgid "Resize {handleKey}"
msgstr "Resize {handleKey}"
+#: src/comments/CommentsPanel.tsx
+msgid "Resolve"
+msgstr "Resolve"
+
#: src/components/SyncStatusBadge.tsx
msgid "Resolve conflict in your terminal"
msgstr "Resolve conflict in your terminal"
+#: src/comments/CommentsPanel.tsx
+msgid "Resolved"
+msgstr "Resolved"
+
#: src/components/CreateProjectDialog.tsx
msgid "Resolving default location"
msgstr "Resolving default location"
@@ -8291,6 +8543,10 @@ msgstr "Select next occurrence"
msgid "Select the full source document."
msgstr "Select the full source document."
+#: src/comments/CommentsPanel.tsx
+msgid "Select this text in the property"
+msgstr "Select this text in the property"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Select, enter, or leave block components and fallback source blocks from keyboard boundaries."
msgstr "Select, enter, or leave block components and fallback source blocks from keyboard boundaries."
@@ -8349,10 +8605,22 @@ msgstr "Send feedback"
msgid "Send feedback…"
msgstr "Send feedback…"
+#: src/comments/QueueNewChatRow.tsx
+msgid "Send queue to"
+msgstr "Send queue to"
+
#: src/components/ReportBugDialogBody.tsx
msgid "Send report"
msgstr "Send report"
+#: src/comments/CommentSelectionAffordance.tsx
+msgid "Send to AI"
+msgstr "Send to AI"
+
+#: src/comments/CommentQueuePanel.tsx
+msgid "Send to chat"
+msgstr "Send to chat"
+
#: src/components/ReportBugDialogBody.tsx
msgid "Send your report by email"
msgstr "Send your report by email"
@@ -8378,6 +8646,10 @@ msgstr "Sent privately to the OpenKnowledge team, along with your note and app v
msgid "Sent to <0>{endpointHost}</0> to embed your content. Stored on this machine only (in <1>~/.ok/secrets.yml</1>), never in the project."
msgstr "Sent to <0>{endpointHost}</0> to embed your content. Stored on this machine only (in <1>~/.ok/secrets.yml</1>), never in the project."
+#: src/comments/store.ts
+msgid "Sent, but the comments could not be marked done — they are still queued."
+msgstr "Sent, but the comments could not be marked done — they are still queued."
+
#: src/editor/slash-command/items.tsx
msgid "Separator"
msgstr "Separator"
@@ -8662,10 +8934,19 @@ msgstr "Show panel ({panelShortcutLabel})"
msgid "Show problem indicators"
msgstr "Show problem indicators"
+#: src/comments/comment-chips.tsx
+msgid "Show queued comments"
+msgstr "Show queued comments"
+
#: src/editor/find-replace/FindReplaceBar.tsx
msgid "Show replace"
msgstr "Show replace"
+#. placeholder {0}: resolved.length
+#: src/comments/CommentsPanel.tsx
+msgid "Show resolved ({0})"
+msgstr "Show resolved ({0})"
+
#: src/components/BottomComposer.tsx
msgid "Show selection preview"
msgstr "Show selection preview"
@@ -8900,6 +9181,11 @@ msgstr "Start {agentName}"
msgid "Start {agentName}, {hint}"
msgstr "Start {agentName}, {hint}"
+#: src/comments/CommentQueuePanel.tsx
+#: src/comments/QueueNewChatRow.tsx
+msgid "Start a new chat"
+msgstr "Start a new chat"
+
#: src/components/NavigatorApp.tsx
msgid "Start a new OpenKnowledge project."
msgstr "Start a new OpenKnowledge project."
@@ -9370,6 +9656,10 @@ msgstr "Thanks for the feedback!"
msgid "Thanks for the report!"
msgstr "Thanks for the report!"
+#: src/comments/use-comment-delivery.ts
+msgid "That app isn't available — the comments stay queued."
+msgstr "That app isn't available — the comments stay queued."
+
#: src/components/NewWorktreeDialog.tsx
#: src/components/ShareBranchSwitchDialog.tsx
msgid "That branch is already open in another worktree."
@@ -9404,6 +9694,10 @@ msgstr "The agent isn't stopping. Force stop closes this thread and quits the ag
msgid "The agent's persona, values, and voice."
msgstr "The agent's persona, values, and voice."
+#: src/comments/CommentsPanel.tsx
+msgid "The anchored text is gone. You can re-place it on selected text."
+msgstr "The anchored text is gone. You can re-place it on selected text."
+
#: src/components/ProblemsPanel.tsx
msgid "The audit could not be completed. Try again."
msgstr "The audit could not be completed. Try again."
@@ -9467,6 +9761,10 @@ msgstr "The menu label agents pick this template by (required)."
msgid "The model id your endpoint serves. Its vector size is detected automatically — clear the field to go back to {DEFAULT_EMBEDDINGS_MODEL}."
msgstr "The model id your endpoint serves. Its vector size is detected automatically — clear the field to go back to {DEFAULT_EMBEDDINGS_MODEL}."
+#: src/components/TerminalSessionsHost.tsx
+msgid "the open agent"
+msgstr "the open agent"
+
#: src/editor/components/PreviewBlockedNotice.tsx
msgid "The preview blocks resources that don't meet its security rules (for example plain http:// URLs, or code that uses eval). The content above may render incompletely."
msgstr "The preview blocks resources that don't meet its security rules (for example plain http:// URLs, or code that uses eval). The content above may render incompletely."
@@ -9488,6 +9786,10 @@ msgstr "The provider rejected the request (HTTP {0}). Check the API key and the
msgid "The provider rejected the request. Check the API key and the model id."
msgstr "The provider rejected the request. Check the API key and the model id."
+#: src/comments/comment-chips.tsx
+msgid "The quoted text is no longer in the document — the agent will be told."
+msgstr "The quoted text is no longer in the document — the agent will be told."
+
#: src/components/ReportBugDialogBody.tsx
msgid "The report service couldn't be reached."
msgstr "The report service couldn't be reached."
@@ -9512,6 +9814,10 @@ msgstr "The template's filename (without `.md`)."
msgid "The terminal is turned off for this project. Turn it back on to run commands here."
msgstr "The terminal is turned off for this project. Turn it back on to run commands here."
+#: src/comments/use-comment-delivery.ts
+msgid "The terminal isn't available here — the comments stay queued."
+msgstr "The terminal isn't available here — the comments stay queued."
+
#. placeholder {0}: info.exitCode
#: src/components/TerminalExitNotice.tsx
msgid "The terminal session ended (exit code {0})."
@@ -9616,6 +9922,10 @@ msgstr "This agent runs through {0}, which isn't installed. Open Knowledge can d
msgid "This branch is checked out in:"
msgstr "This branch is checked out in:"
+#: src/comments/CommentsPanel.tsx
+msgid "This comment is on the whole property"
+msgstr "This comment is on the whole property"
+
#: src/components/PanelScopeHeader.tsx
msgid "This doc"
msgstr "This doc"
@@ -10537,6 +10847,10 @@ msgstr "Window"
msgid "Word wrap"
msgstr "Word wrap"
+#: src/components/BottomComposer.tsx
+msgid "Work through these comments"
+msgstr "Work through these comments"
+
#: src/components/McpConsentDialogBody.tsx
#: src/components/NewWorktreeDialog.tsx
#: src/components/SkillEditorActions.tsx
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index 65abfd0ab..3550578ec 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -129,6 +129,7 @@
],
"2277Tu": ["Ćōĺĺàƥśē ĝŕàƥĥ"],
"237hSL": ["Ēńďēď"],
+ "253MN6": ["Ćōũĺďń'ţ śēńď ŷōũŕ ćōḿḿēńţś — ƥĺēàśē ţŕŷ àĝàĩń."],
"25Pw6a": ["Ćĺōńĩńĝ"],
"27TLNq": ["Ēńàƀĺē ", ["displayName"], " ĆĹĨ"],
"27XW26": ["Ćĺōńē ĥàƥƥēńś ĩń ţĥē ƤŕōĴēćţ Ńàvĩĝàţōŕ. Ŕēćĺĩćķ ţĥē śĥàŕē ĺĩńķ ţĥēŕē."],
@@ -144,6 +145,7 @@
"2FnYUD": [
"Àƥƥ & śŷśţēḿ ĩńƒō, ŕēćēńţ àƥƥ ĺōĝś, àńď ƥŕōĴēćţ śēŕvēŕ ĺōĝś: ţĥē ēśśēńţĩàĺś ŵē ńēēď ţō ŕēƥŕōďũćē ţĥē ĩśśũē."
],
+ "2FoHU3": ["Ŕēśōĺvē"],
"2G-56b": ["Ƒàĩĺēď ţō ũƥďàţē ḿàŕķďōŵńĺĩńţ ŕũĺēś"],
"2GT3Hf": ["Ĝĺōƀàĺ"],
"2H43L8": ["Śēćŕēţś ĺĩķē ÀƤĨ ķēŷś àńď ţōķēńś àŕē ŕēďàćţēď àũţōḿàţĩćàĺĺŷ."],
@@ -151,6 +153,7 @@
"2QM24L": ["Àĺĺ ţàĝś"],
"2RBzMG": ["Ńēţŵōŕķ ēŕŕōŕ — ćĥēćķ ŷōũŕ ćōńńēćţĩōń àńď ţŕŷ àĝàĩń"],
"2Snes1": ["Ţĥĩś śēńďś ţĥē ĺĩńķ'ś àďďŕēśś ōƒƒ ŷōũŕ ḿàćĥĩńē"],
+ "2UgoBZ": ["ĝōńē"],
"2XQ8Ww": ["Ōƥēń ƥŕēvĩēŵ ŵĥēń àĝēńţ ēďĩţś"],
"2YOwme": ["Ŕēśţàŕţēď — ńōŵ ŕũńńĩńĝ v", ["appRuntime"], "."],
"2YZwPB": ["Ƒōŕŵàŕď-ĺĩńķś ŕēśƥōńśē ďĩď ńōţ ḿàţćĥ ēxƥēćţēď śĥàƥē."],
@@ -204,6 +207,7 @@
],
"3SZrdj": ["Ćĥēćķ ƒōŕ ũƥďàţēś…"],
"3TSz9S": ["Ḿĩńĩḿĩźē"],
+ "3V94ia": ["Ćōũĺďń'ţ śēńď ŷōũŕ ćōḿḿēńţś — ţĥē ŵōŕķśƥàćē ĩśń'ţ ŕēàďŷ."],
"3VbwPp": ["Ōƥēń ", ["keyName"], " ĩń ƀŕōŵśēŕ"],
"3VsNTI": ["Ĺōàďĩńĝ ďōćũḿēńţ"],
"3YWddZ": ["Ńō ćōńţēńţ ćĥàńĝēś ĩń ţĥĩś vēŕśĩōń"],
@@ -256,9 +260,11 @@
"4XL6N4": [
"Ďēţēćţēď ƒŕōḿ ţĥē ēďĩţōŕś ţĥĩś ƥŕōĴēćţ ĩś śēţ ũƥ ƒōŕ. ÀďĴũśţ ţō ćōńţŕōĺ ŵĥēŕē ēvēŕŷ śķĩĺĺ ĩńśţàĺĺś."
],
+ "4_5_n5": [["failed"], " ōƒ ", ["0"], " ćōḿḿēńţś ćōũĺď ńōţ ƀē ŕēḿōvēď ƒŕōḿ ţĥē ǫũēũē."],
"4buZWd": ["Ĩńĥēŕĩţēď ƒŕōḿ ", ["path"]],
"4cEClj": ["Śēśśĩōńś"],
"4c_a6S": ["Ńōţĥĩńĝ śēţ ŷēţ."],
+ "4eO-iB": ["Ďĩśćàŕď ţĥĩś ćōḿḿēńţ"],
"4g19V6": ["Ƒàĩĺēď ţō ũƥďàţē ƥŕōƥēŕţŷ"],
"4h3e0H": ["Ćōũĺďń'ţ ũƥďàţē śķĩĺĺś śĥàŕĩńĝ — ", ["detail"], "."],
"4hJhzz": ["Ţàƀĺē"],
@@ -293,6 +299,7 @@
"5ClEAu": ["Ĩńĺĩńē ĥàśĥţàĝ ƒōŕ ćŕōśś-ďōć ĝŕōũƥĩńĝ."],
"5D3Ior": ["Ĥĩďē ƒōĺďēŕ"],
"5F5HYj": [["ahead"], " àĥēàď, ", ["behind"], " ƀēĥĩńď"],
+ "5GBQ-F": ["Śēĺēćţ ţĥĩś ţēxţ ĩń ţĥē ƥŕōƥēŕţŷ"],
"5GKMSz": ["Ĩńďēńţ ōŕ ōũţďēńţ ţĥē ćũŕŕēńţ ĺĩśţ ĩţēḿ."],
"5GRxoA": ["Śēàŕćĥ ƒĩĺēś, ƒōĺďēŕś, àńď ćōḿḿàńďś ƒōŕ ţĥē ćũŕŕēńţ ŵōŕķśƥàćē."],
"5LXwX8": [
@@ -351,6 +358,7 @@
"5tcmwY": ["Àďď vàĺũē"],
"5vAI6Z": ["Ĩţ ďĩďń'ţ ƒĩţ ĩńţō ḿŷ ŵōŕķƒĺōŵ"],
"5vYdh9": ["Ńēŵ ţĥŕēàď ŵĩţĥ ", ["0"]],
+ "5vhe0W": ["Àďď ţō ǫũēũē"],
"5wV2qQ": ["àńď ḿōŕē"],
"5y_9lO": ["Ŵàĩţĩńĝ ƒōŕ àũţĥōŕĩźàţĩōń"],
"6-wLTJ": [["behind"], " ƀēĥĩńď ōŕĩĝĩń"],
@@ -391,6 +399,7 @@
"6hfDJr": ["Śēŕvēŕ ēŕŕōŕ: ", ["status"]],
"6iDEWA": ["Śĥōŵ ƥàńēĺ"],
"6ibbCg": ["Ćŕēàţē ŷōũŕ ƒĩŕśţ ƒĩĺē"],
+ "6kVJ0m": ["Ćōũĺďń'ţ ŕēàď ţĥē ǫũēũēď ćōḿḿēńţś."],
"6ki7F2": [["0", "plural", { "one": ["#", " ĩţēḿ"], "other": ["#", " ĩţēḿś"] }]],
"6lGV3K": ["Śĥōŵ ĺēśś"],
"6m_7We": ["Ōƥēń ţĥĩś śēţţĩńĝś ďĩàĺōĝ."],
@@ -438,6 +447,7 @@
"7cAW1G": ["Ńō ÀƤĨ ķēŷ ĩś śēţ ƒōŕ ţĥĩś ēńďƥōĩńţ. Àďď ōńē àƀōvē."],
"7d1a0d": ["Ƥũƀĺĩć"],
"7hctf2": ["Ďēśćŕĩƀē ţĥē ƥŕōĴēćţ ŷōũ ŵàńţ ţō ćŕēàţē"],
+ "7iTyyh": [["queueCount", "plural", { "one": ["#", " ćōḿḿēńţ"], "other": ["#", " ćōḿḿēńţś"] }]],
"7jIIFX": ["Ŷōũ'ŕē àĺĺ śēţ ũƥ!"],
"7kb4LU": ["Àƥƥŕōvēď"],
"7l15X4": ["ƒàĩĺēď"],
@@ -478,6 +488,7 @@
"Ĩƒ àń ũƥďàţē àŕŕĩvēś ƒōŕ śōḿēţĥĩńĝ ŷōũ àŕē ēďĩţĩńĝ, ŷōũ ćĥōōśē ŵĥĩćĥ vēŕśĩōń ţō ķēēƥ, ĺĩķē à ḿēŕĝē ćōńƒĺĩćţ."
],
"8XQRON": ["Ĺōàďĩńĝ ŕēƥōśĩţōŕĩēś"],
+ "8YymuQ": ["Ńō àĝēńţ ĩś śēţ ũƥ ŷēţ — ōƥēńĩńĝ Ćōńƒĩĝũŕē àĝēńţś."],
"8_brI5": ["Ńàḿē ĩś ŕēǫũĩŕēď"],
"8cS0nH": ["Ćōńƒĩĝ śĥàŕĩńĝ ũńàvàĩĺàƀĺē: ", ["0"], "."],
"8cpOa8": ["Ćōũĺďń'ţ ďĩśćōńńēćţ — ƥĺēàśē ţŕŷ àĝàĩń."],
@@ -485,6 +496,7 @@
"8eW0WQ": ["Ńō ḿàţćĥĩńĝ ŕēƥōśĩţōŕĩēś."],
"8fRyLo": ["Ĩńvàĺĩď ƥàţćĥ ƥàŷĺōàď"],
"8fc_3j": ["Ƥŕōţēćţēď ƀŕàńćĥ — ćàńńōţ ƥũśĥ"],
+ "8jeVmd": ["Ţĥē ţēŕḿĩńàĺ ĩśń'ţ àvàĩĺàƀĺē ĥēŕē — ţĥē ćōḿḿēńţś śţàŷ ǫũēũēď."],
"8k6INX": ["Ƥàśţē à ƥēŕśōńàĺ àććēśś ţōķēń ƒōŕ <0>", ["host"], "</0>."],
"8lwQlE": [["0"], " àďďēď, ", ["1"], " ŕēḿōvēď"],
"8m8diM": ["Ńō ĺōćàţĩōń śēĺēćţēď. Ũśē ßŕōŵśē ţō ćĥōōśē à ƒōĺďēŕ."],
@@ -499,6 +511,7 @@
"8vCZcs": ["Ƒàĩĺēď ţō ōƥēń ƒĩĺē."],
"8vETh9": ["Śĥōŵ"],
"8wu9lr": ["Ǫũēũēď"],
+ "8ycqHY": ["Àďď ţĥē ǫũēũēď ćōḿḿēńţś ţō ţĥĩś ḿēśśàĝē"],
"92rbk2": ["Ḿĩŕŕōŕ ĺōàďĩńĝ <0>", ["mirrorRef"], "</0>"],
"96G6Re": ["Ńēŵ ƒōĺďēŕ"],
"96w9hU": ["Śōḿēţĥĩńĝ ŵēńţ ŵŕōńĝ ōƥēńĩńĝ ţĥĩś ƒĩĺē (ĤŢŢƤ ", ["status"], ")."],
@@ -576,6 +589,7 @@
"ATGYL1": ["Ēḿàĩĺ àďďŕēśś"],
"AVW-K9": ["Ƒàĩĺēď ţō ĺōàď ōŕƥĥàń ƥàĝēś"],
"AWOSPo": ["Źōōḿ ĩń"],
+ "AYfna1": ["Ŕēḿōvē ƒŕōḿ ǫũēũē"],
"AaaESH": [
"Àũţō-śŷńć ĩś ōƒƒ ƒōŕ ţĥĩś ŵōŕķţŕēē, ĩńĥēŕĩţēď ƒŕōḿ ",
["project"],
@@ -694,6 +708,7 @@
"CooKEf": ["Ďōćķ śēśśĩōńś àţ ţĥē ƀōţţōḿ"],
"CvsD6Y": ["vĩà ", ["viaTags"]],
"CwOXMT": ["Vàĺũē ƒōŕ ", ["keyName"]],
+ "CxVk-w": ["Ćōḿḿēńţ ōń ", ["address"]],
"D-Oh1s": ["Ĥōŵ ţō śēţ ũƥ ", ["0"], " (ōƥēńś ĩń ƀŕōŵśēŕ)"],
"D-_B7l": ["Ćōńńēćţēď — ţĥĩś ēńďƥōĩńţ ŕēţũŕńś ", ["0"], "-ďĩḿēńśĩōń vēćţōŕś."],
"D12vtS": ["(ďēţàćĥēď)"],
@@ -748,6 +763,7 @@
"DhLHEb": ["Ƒàĩĺēď ţō ĺōàď àćţĩvĩţŷ"],
"DiFKSL": ["Ćōũńţĩńĝ ḿàŕķďōŵń ƒĩĺēś"],
"Dnn2XG": ["Àũţōḿàţĩć"],
+ "DpjYd6": ["ĵũḿƥ ţō ţĥē àńćĥōŕēď ţēxţ"],
"DrYM2Z": ["Śŷńć ďĩśàƀĺēď"],
"DsDwR-": [["0", "plural", { "one": ["#", " ēŕŕōŕ"], "other": ["#", " ēŕŕōŕś"] }]],
"DskIkK": ["Śĩĝń-ĩń śţŕēàḿ ēńďēď ŵĩţĥōũţ ćōńƒĩŕḿàţĩōń — ƥĺēàśē ţŕŷ àĝàĩń"],
@@ -848,6 +864,7 @@
"F4IYWe": ["Śĥàŕē ďōć"],
"F4vEsL": ["Śŷńć śţàţũś: ", ["syncStateLabel"]],
"F6pfE9": ["Àćţĩvē"],
+ "F9e3PM": ["Ţĥàţ àƥƥ ĩśń'ţ àvàĩĺàƀĺē — ţĥē ćōḿḿēńţś śţàŷ ǫũēũēď."],
"FBknns": ["ĤŢḾĹ"],
"FCAcjR": [
"Ŕũń à ŕēàĺ ţēŕḿĩńàĺ ďōćķēď ĩńśĩďē ŌƥēńĶńōŵĺēďĝē, śţàŕţĩńĝ ĩń ţĥĩś ƥŕōĴēćţ'ś ƒōĺďēŕ."
@@ -903,6 +920,7 @@
"G1Gw0v": ["Ńēŵ ţēḿƥĺàţē"],
"G1XxbZ": ["Ćĥēćķƀōx"],
"G4-bgo": ["Àśķ ÀĨ (ƒŕōḿ śēĺēćţĩōń)"],
+ "G4m8rL": ["Ćōḿḿēńţ ōń śēĺēćţĩōń"],
"G7-rf8": ["Ƥàţţēŕń śŷńţàx ēŕŕōŕ: ", ["message"]],
"G7bn_N": ["Śţàŕţ àń àĝēńţ"],
"G7cMuO": ["ĤŢḾĹ ƥŕēvĩēŵ"],
@@ -965,6 +983,7 @@
"H86f9p": ["Ćōĺĺàƥśē"],
"HAvRAI": [["skillCount", "plural", { "one": ["śķĩĺĺ"], "other": ["śķĩĺĺś"] }]],
"HCn0Ay": ["Ţōĝĝĺē śţŕĩķēţĥŕōũĝĥ ƒōŕḿàţţĩńĝ."],
+ "HFqQui": ["Ĥĩďē ǫũēũēď ćōḿḿēńţś"],
"HGNCsl": ["Ćōńńēćţĩōń ĺōśţ — ķēēƥ ţĥĩś ţàƀ ōƥēń, ŷōũŕ ēďĩţś ŵĩĺĺ śŷńć ŵĥēń ŕēćōńńēćţēď"],
"HIb0vl": ["Ńēţŵōŕķ ēŕŕōŕ — ƥĺēàśē ţŕŷ àĝàĩń"],
"HM56Bx": ["Ćŕēàţĩńĝ..."],
@@ -973,6 +992,7 @@
"HTW0Zw": ["Ōńē ḿōŕē śţēƥ: ŕũń <0>ćĺàũďē</0> ĩń ţĥĩś ƥŕōĴēćţ àńď àƥƥŕōvē ŌƥēńĶńōŵĺēďĝē ōńćē."],
"HdkSiO": ["Ńēŵ ƒĩĺē"],
"HfI1dR": ["Ĩ àĺŕēàďŷ ĥàvē ĩţ ĺōćàĺĺŷ →"],
+ "Hhe73G": ["Ćōũĺďń'ţ ǫũēũē ţĥàţ ćōḿḿēńţ."],
"HjNrT0": [["0", "plural", { "one": ["#", " ƀàćķĺĩńķ"], "other": ["#", " ƀàćķĺĩńķś"] }]],
"Hl89Qd": ["Ĺōàďĩńĝ ţēḿƥĺàţēś"],
"HlmZBk": ["Ďōćũḿēńţś ŕēśƥōńśē ďĩď ńōţ ḿàţćĥ ēxƥēćţēď śĥàƥē."],
@@ -1018,8 +1038,10 @@
"IX7-sq": ["Śōḿēţĥĩńĝ ŵēńţ ŵŕōńĝ ōƥēńĩńĝ \"", ["docName"], "\"."],
"IX_uXB": ["ḿŷ-ƒēàţũŕē"],
"IYciRC": ["Ţĥàńķś ƒōŕ ţĥē ŕēƥōŕţ!"],
+ "IZXuGP": ["Ćōũĺďń'ţ ōƥēń ţĥē ţēŕḿĩńàĺ — ţĥē ćōḿḿēńţś śţàŷ ǫũēũēď."],
"IajAbS": ["Àďď à śţàŕţēŕ ƥàćķ"],
"If0crP": ["Ōƥēń ŵĩţĥ ÀĨ ", ["targetDisplayName"], ", ", ["hint"]],
+ "IgN3LY": ["Ōń śēĺēćţēď ţēxţ ĩń <0>", ["address"], "</0>"],
"IgTwLt": ["Ōƥēń ţĥĩś ďōćũḿēńţ ĩń ţĥē ēďĩţōŕ àńď ćōĺĺàƥśē ţĥē ĝŕàƥĥ."],
"Ik-gP0": ["Ĥēàďĩńĝ Ĥ", ["level"], ": ", ["text"]],
"IlH15B": ["Śţàŕţ à śēśśĩōń ŵĩţĥ ţĥē + ƀũţţōń, ōŕ ĺàũńćĥ àń àĝēńţ ƒŕōḿ à ƥàĝē."],
@@ -1033,6 +1055,7 @@
"It9ARY": ["Ţōĝĝĺē ţĥē ŕĩĝĥţ ďōćũḿēńţ ƥàńēĺ."],
"ItxGi3": ["Àţţàćĥḿēńţś ḿũśţ ţōţàĺ ũńďēŕ 3 Ḿß."],
"Ix0K8o": ["Ĥĩďē ēxţēŕńàĺ ŨŔĹ ńōďēś"],
+ "IxHMdF": ["Ćōũĺďń'ţ ďēĺēţē ţĥàţ ćōḿḿēńţ."],
"IxyZXD": ["Śćŕēēńśĥōţ"],
"J2Mv98": ["Ńàḿē (ē.ĝ. ", ["login"], ")"],
"J2_JuX": ["ńōţĥĩńĝ (", ["0"], " ćàńńōţ ḿàţćĥ à ďōć)"],
@@ -1147,6 +1170,7 @@
"LPAv9E": [["days"], "ď àĝō"],
"LQdLio": ["Ńēŵ śćĥēḿà"],
"LQsCPn": ["Ĺōćàĺ ćōḿḿĩţś àŕē ķēēƥĩńĝ ţĥĩś ćōƥŷ ƒŕōḿ ũƥďàţĩńĝ"],
+ "LRLKnQ": ["Ĥĩďē ŕēśōĺvēď"],
"LRgZAt": [["owner"], "/", ["name"], " àĺŕēàďŷ ēxĩśţś"],
"LTeJuX": ["Ţōĝĝĺē Ƒũĺĺ Śćŕēēń"],
"LXdWeS": ["Ḿēďĩũḿ śēćţĩōń ĥēàďĩńĝ."],
@@ -1189,6 +1213,7 @@
]
],
"LvdLef": ["Ţĥàńķś ƒōŕ ţĥē ƒēēďƀàćķ!"],
+ "LvoXJX": ["Ćōũĺďń'ţ ŕēàď ţĥē ǫũēũēď ćōḿḿēńţś — ńōţĥĩńĝ ŵàś śēńţ."],
"LwMxXg": ["Ƒàĩĺēď ţō ōƥēń ŵōŕķţŕēē."],
"M-IF14": ["Ŕēƥōŕţ ŕēƒēŕēńćē"],
"M0jOcG": ["Vĩēŵ ĩń śōũŕćē ḿàŕķďōŵń"],
@@ -1199,7 +1224,10 @@
"M5_9s2": ["Śēńďĩńĝ ŕēƥōŕţ"],
"M5mfAe": ["Àďď ţàĝ"],
"M6mvVi": ["Ćōƥŷ ŕēĺàţĩvē ƥàţĥ"],
+ "M7SqjM": ["Ŕēōƥēń"],
+ "M92_0q": ["Ćĺōśē ćōḿḿēńţ"],
"M9597s": ["Ƥŕēƥàŕĩńĝ śĥàŕē ŨŔĹ..."],
+ "MBe6TE": ["Ţĥē ǫũōţēď ţēxţ ĩś ńō ĺōńĝēŕ ĩń ţĥē ďōćũḿēńţ — ţĥē àĝēńţ ŵĩĺĺ ƀē ţōĺď."],
"MCjC9A": ["Ďēĺēţē ", ["deleteDescriptorLabel"]],
"MDBJwN": ["Ĥàŕď ţō ũśē"],
"MDZSJe": ["Ŵĥēń ţĥē àĝēńţ ŕũńś ĩţś śćĥēďũĺēď ŵōŕķ."],
@@ -1281,6 +1309,7 @@
],
"Nay2Yr": ["Ńō àĝēńţś ḿàţćĥ ŷōũŕ śēàŕćĥ."],
"NcurBF": ["Ƥàń ďōŵń"],
+ "NeQ_0G": ["Ŵōŕķ ţĥŕōũĝĥ ţĥēśē ćōḿḿēńţś"],
"NgZwB0": [["enabledCount"], "/", ["0"], " ōń"],
"NjrIak": ["Ƒĩĺē: <0>", ["fixedName"], ".ḿď</0>"],
"NkXEFS": ["Ŕēśţōŕē ƒàĩĺēď — ďōćũḿēńţ ũńćĥàńĝēď"],
@@ -1307,6 +1336,7 @@
"O2UpM1": ["ßŕōŵśē"],
"O3oNi5": ["Ēḿàĩĺ"],
"O4PnDd": ["ÀĨ ţōōĺ ḿàńàĝēḿēńţ ĩś ōńĺŷ àvàĩĺàƀĺē ĩń ţĥē ŌƥēńĶńōŵĺēďĝē ďēśķţōƥ àƥƥ."],
+ "O6H89R": ["Ŕēśōĺvēď"],
"O6yEPk": ["Ćŕēàţē à ńēŵ ŌƥēńĶńōŵĺēďĝē ƥŕōĴēćţ ĩń ţĥē ƒōĺďēŕ ōƒ ŷōũŕ ćĥōĩćē."],
"O7_W_a": ["Ōƥēń ŵĩţĥ ÀĨ"],
"O9oQJS": ["Śēńď ŕēƥōŕţ"],
@@ -1436,6 +1466,7 @@
"QfFBdJ": ["Ţĥē ţēḿƥĺàţē'ś ƒĩĺēńàḿē (ŵĩţĥōũţ `.ḿď`)."],
"Qj4RL5": ["Ćōḿƥĺēţēď:"],
"QlAG4m": ["Ţēĺĺ ũś ḿōŕē (ōƥţĩōńàĺ)"],
+ "QlkiD5": ["Ŕē-ƥĺàćē ōń śēĺēćţēď ţēxţ"],
"QlxHAH": ["Śĥōŵĩńĝ ŕēśũĺţś ƒōŕ \"", ["semanticResultsLabel"], "\""],
"QqBQu1": ["Ĺàƀēĺ <0>(vĩśĩƀĺē ĺĩńķ ţēxţ)</0>"],
"Qvls7J": ["Ēńĝ śƥēćś"],
@@ -1527,6 +1558,7 @@
"SItQRc": ["Ĥōŵ ďō ŷōũ ĺĩķē ŌƥēńĶńōŵĺēďĝē?"],
"SOPwPh": ["Ŕēśţōŕē ţō ţĥĩś ēďĩţ"],
"SQWJ-i": ["Ŕēśţōŕē śēśśĩōńś"],
+ "SRBk2G": ["Ćōũĺďń'ţ àďď ţĥàţ ćōḿḿēńţ."],
"STTOnz": [["keyName"], " ţŷƥē: ćōḿƥĺēx vàĺũē (ńēśţēď; ŕēàď-ōńĺŷ)"],
"SUOoXn": ["Ƒàĩĺēď ţō ōƥēń ƥŕōĴēćţ."],
"SVLPt5": [["formatted"], " ĜĩţĤũƀ śţàŕś"],
@@ -1603,6 +1635,7 @@
"U9tm58": ["Ĥĩďē ƥŕōƀĺēḿ ĩńďĩćàţōŕś"],
"UBv8UK": ["Ďēĺēţē Ƥēŕḿàńēńţĺŷ"],
"UDFrWm": ["Ćĥēćķĩńĝ ĜĩţĤũƀ ćōńńēćţĩōń..."],
+ "UEdTEN": ["Ōŕƥĥàńēď"],
"UGeJuP": ["Àĺĺōŵēď vàĺũēś (ēḿƥţŷ = àńŷ)"],
"UL8A9w": ["Ţàĝ"],
"UMrOy2": ["Śķĩĺĺ \"", ["trimmedName"], "\" ćŕēàţēď"],
@@ -1642,6 +1675,7 @@
],
"UhpfxY": ["Ƥàń ĺēƒţ"],
"UkQGhd": ["Ĥĩďē ŕēƥĺàćē"],
+ "Uoux8m": ["Ĩńćĺũďē ţĥĩś ćōḿḿēńţ ĩń ţĥē ńēxţ śēńď"],
"Up2_7p": ["Ćōƥŷ ƒũĺĺ ƥàţĥ"],
"UpCz01": ["Ţĥĩś ďōć"],
"UuYo7g": [
@@ -1671,6 +1705,7 @@
"Ēxţēŕńàĺ ĺĩńķ ƥŕēvĩēŵś śĥōŵ à ćàŕď ŵĩţĥ ţĥē śĩţē ńàḿē, ƥàĝē ţĩţĺē, àńď ďēśćŕĩƥţĩōń ŵĥēń ŷōũ ĥōvēŕ à ĺĩńķ."
],
"VITWk5": ["Ḿàńàĝēď ƀŷ ŌƥēńĶńōŵĺēďĝē"],
+ "VIiaFH": ["Ćōũĺďń'ţ ŕēàď ţĥē ǫũēũēď ćōḿḿēńţś: ", ["0"]],
"VIwCaD": ["Ēńţŕŷ"],
"VM7H66": ["Ţĥĩś ƒĩĺē ĩś ƀĩńàŕŷ àńď ćàń'ţ ƀē śĥōŵń àś ţēxţ."],
"VNgKZz": ["Àďvàńćēď śēţţĩńĝś"],
@@ -1684,6 +1719,7 @@
"V_wltx": ["Ēńţēŕ à ţĩţĺē ƒōŕ ţĥĩś ţēḿƥĺàţē."],
"Va3xJe": ["Àďď ƒĩēĺď"],
"VbqhBI": ["Àĺŕēàďŷ àţ ", ["assetContentPath"], " — ŕēũśĩńĝ."],
+ "VbyRUy": ["Ćōḿḿēńţś"],
"VcqWBy": ["Ũƥĺōàď ḿàŷ ĥàvē śũććēēďēď ƀũţ ţĥē śĩďēƀàŕ ĩś ōũţ ōƒ ďàţē — ŕēƒŕēśĥ ţō ŕēśŷńć"],
"VdXv4D": ["Ćĺōńē ƒŕōḿ ĜĩţĤũƀ"],
"Vftef5": ["Ćōḿḿōń ḿàŕķďōŵń ĩśśũēś — ĥàŕď ţàƀś, ĥēàďĩńĝ ĩńćŕēḿēńţś, ĺĩśţ ḿàŕķēŕś, àńď ḿōŕē."],
@@ -1747,6 +1783,7 @@
"WyXG7w": ["Ćĺōśē àĺĺ"],
"Wyxs0x": ["Ƥàţĥ ćàńńōţ ćōńţàĩń \"..\""],
"X0ttSN": ["Ńō ţàĝś ḿàţćĥ \"", ["tagListQuery"], "\"."],
+ "X2zUS5": ["Ďēĺēţē ţĥĩś ćōḿḿēńţ"],
"X3MMeA": ["Ńōńē ōƒ ţĥēśē ƥŕōƀĺēḿś ĥàvē àń àũţōḿàţĩć ƒĩx."],
"X7u0xR": [["0"], " ţēḿƥĺàţēś àvàĩĺàƀĺē"],
"X8kjQX": ["Ŕē-àũţĥēńţĩćàţē ŵĩţĥ ĜĩţĤũƀ"],
@@ -1780,6 +1817,7 @@
],
"XklovM": ["Ŵōŕķĩńĝ…"],
"Xl-UUg": ["ĝũĩďēś/ĩńśţàĺĺ ōŕ ĥţţƥś://ēxàḿƥĺē.ćōḿ"],
+ "Xm5tCT": ["Àďď ćōńţēxţ ţō ţĥĩś ḿēśśàĝē"],
"XmJfZT": ["ńàḿē"],
"XnlF3W": ["Àďď ţĥē ńēxţ ḿàţćĥĩńĝ śōũŕćē śēĺēćţĩōń."],
"XopE_I": ["Ƒàĩĺēď ţō ƥàŕśē ƀàćķĺĩńķś ēŕŕōŕ ŕēśƥōńśē (ĤŢŢƤ ", ["status"], ")"],
@@ -1812,6 +1850,7 @@
"YDL7N6": [
"Ĺĩńţ ƥĺũĝĩńś — ŵĥĩćĥ ŕũĺē ƒàḿĩĺĩēś ŕũń àńď ţĥēĩŕ ƥēŕ-ŕũĺē śēţţĩńĝś — àŕē ćōńƒĩĝũŕēď ōń ţĥēĩŕ ōŵń ţàƀ ũńďēŕ Ţĥĩś ƥŕōĴēćţ → Ƥĺũĝĩńś."
],
+ "YDX9lo": ["Ŕēḿōvē ţĥĩś ćōḿḿēńţ ƒŕōḿ ţĥē ǫũēũē"],
"YEIS9T": ["Ēďĩţś àƥƥĺŷ ĺĩvē. Ĺĩĝĥţ ōŕ ďàŕķ ĩś ćĥōśēń ƒŕōḿ ţĥē ƀàćķĝŕōũńď."],
"YEP3X2": ["Ďēĺēţē à ţàƀĺē ŵĥēń ţĥē àćţĩvē ţàƀĺē ćēĺĺ śēĺēćţĩōń ćōvēŕś ţĥē ƒũĺĺ ţàƀĺē."],
"YGIi_c": ["Ŕēĩńśţàĺĺ"],
@@ -1864,6 +1903,7 @@
"ZBt4rI": ["Ĩńśţŕũćţĩōń ƒōŕ ţĥē ÀĨ"],
"ZBxvV3": ["Ńēŵ Ţēŕḿĩńàĺ"],
"ZDOq9A": ["Ŵĥàţ ŷōũ śĥàŕē ĩś śēńţ ţō ţĥē ŌƥēńĶńōŵĺēďĝē ţēàḿ."],
+ "ZHAM1l": ["Ĩńćĺũďē ĩń ďĩśƥàţćĥ"],
"ZI8uvA": ["Ńō ƥŕōƀĺēḿś ƒōũńď."],
"ZNK2Tq": ["ŕōōţ"],
"ZQJ1IV": ["Àćţĩvàţē ţĥē ĺàśţ ēďĩţōŕ ţàƀ."],
@@ -1991,13 +2031,16 @@
],
"ajz9F8": ["Ćōũĺďń'ţ ĺōàď ćōńƒĺĩćţ ćōńţēńţ ƒōŕ ", ["filePath"], ". Ţŕŷ ŕēĺōàďĩńĝ ţĥē ƥàĝē."],
"ak4LLg": ["Ćĺēàŕ ḿēńũ"],
+ "akmOT9": ["Ēďĩţ ţĥĩś ćōḿḿēńţ"],
"anmUZq": ["Ḿĩśśĩńĝ à ƒēàţũŕē"],
+ "aoT2xX": ["Ţĥĩś ćōḿḿēńţ ĩś ōń ţĥē ŵĥōĺē ƥŕōƥēŕţŷ"],
"aoa6xA": ["ńēţŵōŕķ ēŕŕōŕ (ĩś `ōķ ũĩ` ŕũńńĩńĝ?)"],
"arUUsK": ["Ƥŕōďũćţ ũƥďàţēś"],
"ax9kie": ["Ĺĩńķ ƥŕēvĩēŵ śēţţĩńĝś ńōţ ŷēţ ĺōàďēď — ţŕŷ àĝàĩń ĩń à ḿōḿēńţ"],
"axQ1h6": ["Àńŷţĥĩńĝ ŷōũ'ď ĺĩķē ţō àďď? (ōƥţĩōńàĺ)"],
"az8lvo": ["Ōƒƒ"],
"b18t0_": ["Ćĺōśē ďĩƒƒ"],
+ "b24kPi": ["Ǫũēũē"],
"b3Thhd": ["Ũƥĺōàď ƒàĩĺēď"],
"b4AQFK": ["Ōƥēń àćţĩvĩţŷ ƥàńēĺ ƒōŕ ", ["tooltipName"], ", ēďĩţĩńĝ ", ["realCurrentDoc"]],
"b4VvP-": [
@@ -2012,6 +2055,9 @@
"bBcFK_": ["Ōƥēń ēḿōĴĩ ƥĩćķēŕ ƒōŕ ", ["keyName"]],
"bD8I7O": ["Ćōḿƥĺēţē"],
"bF22t6": ["Ŕēḿōvē ƒĩēĺď ", ["field"]],
+ "bGOTXx": [
+ "Ōƥēń ţĥē ćōḿḿēńţ ćōḿƥōśēŕ ōń ţĥē ćũŕŕēńţ śēĺēćţĩōń àńď àďď ĩţ ţō ţĥē ďĩśƥàţćĥ ǫũēũē."
+ ],
"bGa3Fk": ["Ũƥĺōàďĩńĝ ƒĩĺē"],
"bH382I": ["Ēďĩţ ţĥĩś ĤŢḾĹ — ţĥē ƥŕēvĩēŵ ũƥďàţēś ĺĩvē."],
"bKt9Jk": ["Ńō àćţĩvē ōŕ ŕēćēńţ ŌƥēńĶńōŵĺēďĝē ƥŕōĴēćţś ŵēŕē ƒōũńď."],
@@ -2024,6 +2070,7 @@
"bbJ-VR": ["Źōōḿ Ōũţ"],
"bcDHUM": [["descriptorLabel"], " — ŕēńďēŕ ēŕŕōŕ, śōũŕćē ēďĩţàƀĺē ƀēĺōŵ"],
"bcjYUA": ["Ƒōĺď ōŕ ũńƒōĺď śōũŕćē"],
+ "bcm0pR": ["ţĥē ōƥēń àĝēńţ"],
"bkQRMh": ["Ƥàŕàĝŕàƥĥ"],
"blFttG": ["Śēàŕćĥ ƥŕōĴēćţś"],
"bmC18N": ["Ćĺēàŕĩńĝ ĺōćàĺ ćōĺĺàƀōŕàţĩōń ďàţà ƒōŕ \"", ["docName"], "\" ƀēƒōŕē ŕēćōńńēćţĩńĝ."],
@@ -2033,6 +2080,7 @@
"Ŵĥēń ēńàƀĺēď, ţĥē àĝēńţ ōƥēńś ōŕ ŕēƒŕēśĥēś ţĥē ƥŕēvĩēŵ àƒţēŕ ēàćĥ ēďĩţ. Ďĩśàƀĺē ĩƒ ŷōũ ḿàńàĝē ŷōũŕ ōŵń ƥŕēvĩēŵ ŵĩńďōŵ (ŌĶ Ďēśķţōƥ, à ƀŕōŵśēŕ ţàƀ ōń àńōţĥēŕ ďĩśƥĺàŷ, ēţć.)."
],
"bwil08": ["ßũĩĺďĩńĝ <0>ōƥēńķńōŵĺēďĝē.śķĩĺĺ</0> àńď ōƥēńĩńĝ ţĥē Ćĺàũďē Ďēśķţōƥ Àƥƥ"],
+ "bwy8Y7": ["Ōń <0>", ["address"], "</0>"],
"c1LZZH": ["Ĺĩńķ ćōƥĩēď."],
"c2ktXL": ["Ƥŕēvĩōũś ŕēƥōŕţś"],
"c3XJ18": ["Ĥēĺƥ"],
@@ -2143,6 +2191,7 @@
"dXCi3J": ["Śōḿēţĥĩńĝ ƀŕōķē"],
"dXOolp": ["Śŷńćĩńĝ ŷōũŕ ćĥàńĝēś"],
"dXWMFn": ["Ŕēḿōvēś ţĥĩś śķĩĺĺ ƒŕōḿ ŷōũŕ ēďĩţōŕś."],
+ "dXooEp": ["Ńōţĥĩńĝ ǫũēũēď"],
"dYCvMf": ["Ćōũĺďń'ţ ŕēśũḿē ţĥĩś ćōńvēŕśàţĩōń: ", ["0"]],
"darW93": [
[
@@ -2205,10 +2254,12 @@
"eazHgv": [
"Ĝĩţ ćàń'ţ ţŕàćķ ţĥĩś ƒōĺďēŕ — ĩţ'ś ēḿƥţŷ ōŕ ćōńţàĩńś ōńĺŷ ĩĝńōŕēď ƒĩĺēś. Ţĥē ĺĩńķ ŵōń'ţ ŵōŕķ ũńţĩĺ ŷōũ àďď à ţŕàćķēď ďōćũḿēńţ."
],
+ "eiUA4k": [["count", "plural", { "one": ["#", " ćōḿḿēńţ"], "other": ["#", " ćōḿḿēńţś"] }]],
"el312q": ["Ĩńśţàĺĺ śķĩĺĺś ĩńţō"],
"emgiet": ["Àũţĥōŕĩţàţĩvē ćōńţēńţ; ḿĩŕŕōŕēď vēŕƀàţĩḿ ēvēŕŷŵĥēŕē ĩţ'ś ŕēƒēŕēńćēď."],
"enPTnx": ["ĺĩńē ", ["displayLine"]],
"eneWvv": ["Ďŕàƒţ"],
+ "eoEUI3": ["Ćōũĺďń'ţ ŕēśōĺvē ţĥàţ ćōḿḿēńţ."],
"epuNYK": [
"Ḿàŕķ à ƀĺōćķ àś ţĥē śōũŕćē ōƒ ţŕũţĥ. Ḿĩŕŕōŕś ēĺśēŵĥēŕē ũƥďàţē ĺĩvē àś ŷōũ ēďĩţ ĩţ."
],
@@ -2360,6 +2411,7 @@
"hnq8fP": ["Ŕēḿōvē ", ["label"], " ƒŕōḿ ćōńţēxţ"],
"hpDtUm": ["Ēxţēŕńàĺ ŵĩķĩ ĺĩńķ"],
"hpzRlK": ["Ŕēōƥēń ćĺōśēď ţàƀ"],
+ "hqVQbT": ["Àďď Ćōḿḿēńţ"],
"hvZwVx": ["Ćōńvēŕţ"],
"hwFOFD": ["Śēţţĩńĝś ƒàĩĺēď ţō ĺōàď"],
"hxBHxQ": ["À ĺĩńē ŵĩţĥ à ƒōōţńōţē<0><1>[1]</1></0> àńď à ďēƒĩńĩţĩōń śĥōŵń ƀēĺōŵ."],
@@ -2428,6 +2480,7 @@
"iv452l": ["Ďōćũḿēńţàţĩōń ƒōŕ ", ["0"], " (ōƥēńś ĩń ƀŕōŵśēŕ)"],
"iy64Li": ["Ƒũĺĺ śŷńć — ŷōũŕ ēďĩţś àŕē ćōḿḿĩţţēď àńď ƥũśĥēď ţō ŷōũŕ ŕēḿōţē àũţōḿàţĩćàĺĺŷ."],
"iycx_A": ["Ƥũśĥĩńĝ"],
+ "j0ItfO": ["Śĥōŵ ŕēśōĺvēď (", ["0"], ")"],
"j2229h": ["Ŕēḿōvĩńĝ ŌƥēńĶńōŵĺēďĝē ƒĩĺēś…"],
"j2kt1j": [
"Ōƥēń à ńēŵ śēśśĩōń ŵĩţĥ ŷōũŕ ƥŕēƒēŕŕēď ÀĨ. Ŵĩţĥ ţēxţ śēĺēćţēď, śţàĝē ĩţ ţĥēŕē ĩńśţēàď ōƒ ŕũńńĩńĝ ĩţ."
@@ -2543,9 +2596,11 @@
"kolRU1": ["Ďō ŷōũ ŵàńţ ţō ƥēŕḿàńēńţĺŷ ďēĺēţē ĩńśţēàď?"],
"kooyLJ": ["Ƒàĩĺēď ţō ŕēńàḿē ţĥē ƒĩēĺď"],
"kpqWwG": ["Ţĥĩś ", ["targetNoun"], " ŵàś ŕēḿōvēď ƒŕōḿ ƀŕàńćĥ <0>", ["branch"], "</0>."],
+ "kq-Qj4": ["Ćōũĺďń'ţ ŵōŕķ ōũţ ŵĥēŕē ţō śēńď ţĥē ćōḿḿēńţś — ţĥēŷ śţàŷ ǫũēũēď."],
"ktspdq": ["Ţĩńţ àńď ƀàďĝē ƒĩĺēś ţĥàţ ĥàvē ĺĩńţ ōŕ ĺĩńķ ƥŕōƀĺēḿś, ŵĩţĥōũţ ōƥēńĩńĝ ţĥēḿ."],
"ku0yLQ": ["Ƥàĝēś àŕē ēḿƀēďďēď ţĥē ƒĩŕśţ ţĩḿē à śēàŕćĥ ńēēďś ţĥēḿ."],
"ky9Tuc": ["Ēďĩţ ", ["0"], " śōũŕćē"],
+ "kzpkcn": ["Ćōũĺďń'ţ śàvē ţĥàţ ēďĩţ."],
"l-4nnw": ["Śēàŕćĥ ŕũĺēś"],
"l17ab4": ["Ćōũĺď ńōţ ŵŕĩţē ƥŕōĴēćţ ƒĩĺēś. Ţŕŷ à ďĩƒƒēŕēńţ ĺōćàţĩōń."],
"l1aQKz": ["Vĩśũàĺ ēďĩţōŕ ţàƀĺē"],
@@ -2574,6 +2629,7 @@
["4"],
") ţĥàţ ŵōń'ţ ţōũćĥ ţĥē ŕēśţ ōƒ ŷōũŕ śŷśţēḿ."
],
+ "l7X_SM": ["Śēńď ţō ÀĨ"],
"l9HUtd": [
"Ţōĝĝĺē ţĥē ƀōţţōḿ ţēŕḿĩńàĺ ƥàńēĺ. Ŵĩţĥ ţēxţ śēĺēćţēď, śţàĝē ĩţ ƒōŕ ŷōũŕ ƥŕēƒēŕŕēď ÀĨ ĩńśţēàď."
],
@@ -2583,6 +2639,7 @@
"lHCR4I": ["Ćĺēàŕ ţĥē ƒĩēĺď ţō ŕēśēţ ƀàćķ ţō ţĥē ďēƒàũĺţ ŌƥēńÀĨ ēńďƥōĩńţ."],
"lHwYMr": ["Śēŕvēŕ ēŕŕōŕ: ", ["status"], " ", ["statusText"]],
"lI0Td2": ["Ũśē ĺēţţēŕś, ďĩĝĩţś, <0>_</0> àńď <1>-</1> ōńĺŷ."],
+ "lISYEX": ["Ćōũĺďń'ţ ŕēōƥēń ţĥàţ ćōḿḿēńţ."],
"lKQnp-": ["Ĩńśţàĺĺēď ", ["0"], " ", ["1"]],
"lPzyrU": ["Àĺĺ ĥũńķś ŕēśōĺvēď"],
"lVWEIL": ["Ĩńďēxēď ", ["embedded"], " ōƒ ", ["total"], " ƥàĝēś."],
@@ -2656,6 +2713,7 @@
]
],
"mk2poV": ["ē.ĝ. śēŕvēŕ.ţś"],
+ "mlvM8g": ["Ćōũĺďń'ţ ŕē-ƥĺàćē ţĥàţ ćōḿḿēńţ."],
"mmpzAq": ["Ŵŕàƥ ĺōńĝ ĺĩńēś ĩń ţĥē ḿàŕķďōŵń śōũŕćē ēďĩţōŕ."],
"mo22UP": ["Ţōĝĝĺē ĩńĺĩńē ćōďē ƒōŕḿàţţĩńĝ."],
"mqSwZH": [
@@ -2698,6 +2756,7 @@
". Àńŷ ĺōćàĺ ēďĩţś ŵĩĺĺ ƀē ŕēƥĺàćēď — ŷōũŕ ćũŕŕēńţ vēŕśĩōń ĩś śàvēď ţō ĥĩśţōŕŷ ƒĩŕśţ, śō ŷōũ ćàń ŕēśţōŕē ĩţ."
],
"nDT8qt": ["Ĩńĩţĩàĺĩźēď ", ["0"], " ƀũţ ćōũĺď ńōţ ōƥēń ĩţ."],
+ "nG-XA9": ["Ţĥē àńćĥōŕēď ţēxţ ĩś ĝōńē. Ŷōũ ćàń ŕē-ƥĺàćē ĩţ ōń śēĺēćţēď ţēxţ."],
"nGAFeH": [
"Ŕēƥōŕţś ŷōũ'vē ĝēńēŕàţēď ōń ţĥĩś Ḿàć. Ŕēţŕŷ à śēńď, ŕēvēàĺ à ƒĩĺē, ōŕ ďēĺēţē ōńē ŷōũ ńō ĺōńĝēŕ ńēēď."
],
@@ -2795,10 +2854,12 @@
"ogAuyr": ["ßàćķ ţō ďōćũḿēńţ vĩēŵ"],
"ohUJJM": ["Ƥĺũĝĩńś"],
"oi4zaa": ["Ŕēḿēḿƀēŕ ţĥĩś ƒōŕ ƒũţũŕē àĝēńţś"],
+ "ojGc_T": ["Ōƥēń ćōḿḿēńţ"],
"omXJcU": ["Ćĺōśē ōţĥēŕś"],
"onTlRk": ["Ćōũĺďń'ţ ũƥďàţē śķĩĺĺś śĥàŕĩńĝ"],
"optX0N": [["0"], "ĥ àĝō"],
"oqB2ez": ["Ƥŕēvĩōũś ḿàţćĥ"],
+ "os6dRM": ["Ćōũĺďń'ţ ŕēḿōvē ţĥàţ ćōḿḿēńţ ƒŕōḿ ţĥē ǫũēũē."],
"osRqlv": ["Ōƥēń ďēĺēţē ćōńƒĩŕḿàţĩōń ƒōŕ ţĥē śēĺēćţēď ƒĩĺē-ţŕēē ĩţēḿś."],
"ot5BRK": ["Ďũƥĺĩćàţē śēĺēćţēď ƒĩĺē ōŕ ƒōĺďēŕ"],
"otE4aj": ["Śĥōŵ ēxţēŕńàĺ ŨŔĹ ńōďēś"],
@@ -2819,6 +2880,7 @@
"pBROkv": ["Ţĥàńķś ƒōŕ śũƀśćŕĩƀĩńĝ. Ŵàţćĥ ŷōũŕ ĩńƀōx ƒōŕ ƥŕōďũćţ ũƥďàţēś."],
"pEQFsW": ["Ńō ḿàţćĥĩńĝ ƥŕōĴēćţś."],
"pFPzHA": ["ĒḿōĴĩ ƥĩćķēŕ"],
+ "pFRz_E": ["Ĺēàvē ţĥēśē ćōḿḿēńţś ōũţ ōƒ ţĥĩś ḿēśśàĝē"],
"pFagOn": ["Śōũŕćē ēďĩţĩńĝ"],
"pHYP6v": ["Ōƥēń <0>Ćũśţōḿĩźē</0> ĩń ţĥē śĩďēƀàŕ <1/> <2>Śķĩĺĺś</2>."],
"pQf2Ux": [".ōķ/śķĩĺĺś ĩś ƀàćķ ţō ĺōćàĺ-ōńĺŷ."],
@@ -2845,6 +2907,7 @@
"pzutoc": ["Ĩţàĺĩć"],
"q2kXMG": ["Ĩńĺĩńē Ḿàţĥ"],
"q3TWG7": ["Ḿōvē ţō Ţŕàśĥ"],
+ "q3W2nd": ["Ćōũĺďń'ţ àďď ţĥàţ ćōḿḿēńţ: ", ["0"]],
"q4YJl_": ["Ţĥē ţēŕḿĩńàĺ śēśśĩōń ēńďēď (ēxĩţ ćōďē ", ["0"], ")."],
"q6-JVU": ["Ĺōàďĩńĝ ƥàĝēś"],
"q7F5am": ["ţĩţĺē"],
@@ -2883,11 +2946,13 @@
"qjHMHf": ["Ƒàĩĺēď ţō ďĩśàƀĺē śŷńć — ", ["detail"]],
"qmL1UG": ["Ũƥĺōàďĩńĝ śēćũŕēĺŷ"],
"qo4zCg": ["Ƥàţĥ ćàńńōţ ćōńţàĩń ƀàćķśĺàśĥēś"],
+ "qokN44": ["Śĥōŵ ǫũēũēď ćōḿḿēńţś"],
"qpQwGC": ["Ďēśćŕĩƀē ŵĥàţ ŷōũ'ŕē ŵōŕķĩńĝ ōń àńď ţĥē àĝēńţ śēţś ĩţ ũƥ ƒōŕ ŷōũ."],
"qribBG": ["śćĥēḿà ", ["deleteTarget"]],
"qvWGzP": ["Ćōĺĺàƥśē àĺĺ"],
"qyLmWw": ["Śōũŕćē ēďĩţōŕ śēàŕćĥ ƥàńēĺ"],
"r-OJYm": ["Ēńţēŕ à vàĺĩď ƀŕàńćĥ ńàḿē (ńō śƥàćēś, ńō ĺēàďĩńĝ ďōţ, ńō \"..\")."],
+ "r0mxIn": ["Ŕēḿōvē ƒŕōḿ ţĥē ǫũēũē"],
"r2eKE3": ["Śĩĝń ĩń ţō ", ["agentName"], " ƒĩŕśţ"],
"r4R7AZ": ["Ńēţŵōŕķ ēŕŕōŕ ďũŕĩńĝ ćĺēàńũƥ"],
"r51jLC": ["Ƒĩĺē śàvēď & Ćĺàũďē Ďēśķţōƥ Àƥƥ ōƥēńēď"],
@@ -2918,6 +2983,7 @@
],
"rVxu1k": ["Ńō ƥàĝēś ĺĩńķ ĥēŕē ŷēţ."],
"rXz97P": ["Ńũḿƀēŕēď ĺĩśţ ōƒ ĩţēḿś."],
+ "rY9lqA": ["Śēńď ǫũēũē ţō"],
"rZ9HZq": ["Ţō ďō"],
"rZVMkf": ["Vĩśũàĺ ēďĩţōŕ ŕēƥĺàćē ĩńƥũţ ƒōćũśēď"],
"rageVb": ["Ćũśţōḿ ĤŢḾĹ ŵĩţĥ à ĺĩvē ƥŕēvĩēŵ ƥàńē (śàńďƀōxēď ĩƒŕàḿē)."],
@@ -2934,6 +3000,7 @@
"roAe2K": ["Ĺĩńķ ŨŔĹ"],
"roiUQQ": ["Ţĥĩś ƥàĝē ďōēśń'ţ ĺĩńķ ţō àńŷţĥĩńĝ ŷēţ."],
"rppgXF": ["Ďĩśćōńńēćţĩńĝ"],
+ "rscgd_": ["Ĝō ţō ţĥĩś ćōḿḿēńţ ĩń ", ["0"]],
"rssK8c": ["Ĩĝńōŕē ƥàţţēŕńś (ŕàŵ ţēxţ)"],
"rtdR4v": ["Śĥōŵ ōŕ ĥĩďē Ƒĩĺēś"],
"rwrPbS": ["Ćōḿƥōńēńţ ƀōũńďàŕŷ ńàvĩĝàţĩōń"],
@@ -2961,6 +3028,7 @@
"sIxSSP": ["Ŕēśōĺvē ćōńƒĺĩćţ ĩń ŷōũŕ ţēŕḿĩńàĺ"],
"sJK6pq": ["Ƥēŕḿĩśśĩōń ďēńĩēď"],
"sJWhgo": ["Ũńķńōŵń ćōḿƥōńēńţ: ", ["unregisteredComponentName"]],
+ "sKEgGd": ["Śēńď ţō ćĥàţ"],
"sNeKjP": ["Ƒàĩĺēď ţō śţōŕē ţĥē ţōķēń — ţŕŷ àĝàĩń"],
"sOxZaS": ["Ƒàĩĺēď ţō ĺōàď ĝŕàƥĥ"],
"sZ2IOu": [
@@ -2979,6 +3047,7 @@
"seeS6l": ["Śēţũƥ ŌƥēńĶńōŵĺēďĝē ĩń ţĥĩś ƒōĺďēŕ?"],
"sgmRY8": ["Śķĩƥƥēď ďōŵńĺōàďĩńĝ ", ["0"], "."],
"shNd9t": ["Śĺàśĥ ćōḿḿàńď ḿēńũ"],
+ "siXSpl": ["Śēńţ, ƀũţ ţĥē ćōḿḿēńţś ćōũĺď ńōţ ƀē ḿàŕķēď ďōńē — ţĥēŷ àŕē śţĩĺĺ ǫũēũēď."],
"skf5Ix": ["Ĩńďēńţ ōŕ ōũţďēńţ śōũŕćē ēďĩţōŕ ĺĩńēś."],
"sn5BEU": [
["sizeText"],
@@ -3016,6 +3085,8 @@
"t_YqKh": ["Ŕēḿōvē"],
"tcjTlU": ["Śţàŕţēŕ ƥàćķś"],
"teD0H9": ["Ćōũĺďń'ţ ōƥēń à ŵōŕķţŕēē ƒōŕ ţĥàţ ƀŕàńćĥ."],
+ "teFjfG": ["Ńō àĝēńţ ĩś śēţ ũƥ ŷēţ — ƥĩćķ ōńē ƒŕōḿ ţĥē śēńď ḿēńũ."],
+ "teS4nP": ["Ńōţĥĩńĝ ǫũēũēď. Ćōḿḿēńţ ōń à ƥàśśàĝē ţō àďď ĩţ ĥēŕē."],
"ten9en": ["Ŕēćēńţ ƥŕōĴēćţ"],
"tfDRzk": ["Śàvē"],
"tfi40B": ["Ƒàĩĺēď ţō ćŕēàţē ƥàĝē"],
@@ -3110,10 +3181,12 @@
"vGeNNQ": ["Ćōƥŷ à ƥŕōḿƥţ àńď ƥàśţē ĩţ ĩńţō ŷōũŕ àĝēńţ ţō śēţ ũƥ ŷōũŕ ƥŕōĴēćţ."],
"vIxrEk": ["Ƒĩţ ŵĩďţĥ"],
"vLyv1R": ["Ĥĩďē"],
+ "vPF04k": ["Śţàŕţ à ńēŵ ćĥàţ"],
"vPKX2i": ["Ĩń àƥƥ (ƀēţà)"],
"vPXOUw": ["Ţōĝĝĺē śōũŕćē vĩēŵ"],
"vQIVHc": ["Ƒōĺďēŕ ƥŕōƥēŕţĩēś"],
"vWc9a0": ["Ţŷƥē ţō ēďĩţ; <0>⌘ Ēńţēŕ</0> śàvēś, <1>Ēść</1> ćàńćēĺś."],
+ "vYOUOk": ["Àďď à ćōḿḿēńţ"],
"vYPvPB": ["Śŵĩţćĥ ƥŕōĴēćţ…"],
"vZVeFG": ["Ũƥĺōàď ƒàĩĺēď — ƥĺēàśē ţŕŷ àĝàĩń"],
"v_2_3v": ["Ďēĺēţēď ", ["file"]],
@@ -3245,6 +3318,7 @@
"xlQpTE": ["Ḿōŕē ŕēƒũśàĺ ōƥţĩōńś"],
"xloBjn": ["Ŕēĺàţĩvē Ƥàţĥ"],
"xnP32l": ["Ńō ďēśćŕĩƥţĩōń ŷēţ — àďď ōńē śō àĝēńţś ķńōŵ ŵĥēń ţō ũśē ţĥĩś śķĩĺĺ."],
+ "xo6PEb": ["Ćĥōōśē ŵĥēŕē ţō śēńď ţĥē ǫũēũē"],
"xrVr_k": ["Ćōũĺďń'ţ ćŕēàţē śķĩĺĺ: ", ["0"]],
"xsZhu-": ["Ƥàĝē ńũḿƀēŕ"],
"xzAmL_": ["Àũţō-àƥƥŕōvēď"],
@@ -3355,6 +3429,7 @@
"zkz0Fg": ["Śēţ ũƥ śŷńćĩńĝ"],
"zlErBl": ["Ƥàĝē ĥēàďĩńĝś ēŕŕōŕ ŕēśƥōńśē ďĩď ńōţ ḿàţćĥ ŔƑĆ 9457"],
"zo3Dl7": ["Ţōĝĝĺē ţĥũḿƀńàĩĺś"],
+ "zpfN9p": ["Ńō ćōḿḿēńţś ŷēţ. Śēĺēćţ ţēxţ ĩń ţĥē ďōćũḿēńţ ţō àďď ōńē."],
"zq2eBA": ["Vĩēŵ ĩń śōũŕćē"],
"zrP8HX": [
"Ƒŕōńţḿàţţēŕ ēvēŕŷ ďōćũḿēńţ ćŕēàţēď ƒŕōḿ ţĥĩś ţēḿƥĺàţē śţàŕţś ŵĩţĥ. Vàĺũēś àŕē ŶÀḾĹ — à ĺĩśţ ĩś <0>[à, ƀ]</0>; <1>{",
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 6d4d94737..3b2e55ae9 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -225,6 +225,8 @@ msgid "{0} hex value"
msgstr ""
#. placeholder {0}: resolvedTarget.displayName
+#. placeholder {0}: target.displayName
+#: src/comments/use-comment-delivery.ts
#: src/components/BottomComposer.tsx
msgid "{0} isn't installed yet — opening its download page."
msgstr ""
@@ -347,6 +349,10 @@ msgstr ""
msgid "{conflictCount, plural, one {# file conflicted} other {# files conflicted}}"
msgstr ""
+#: src/comments/comment-chips.tsx
+msgid "{count, plural, one {# comment} other {# comments}}"
+msgstr ""
+
#: src/components/TrashFailureModal.tsx
msgid "{count, plural, one {# item could not be moved to the Trash. Do you want to permanently delete instead?} other {# items could not be moved to the Trash. Do you want to permanently delete instead?}}"
msgstr ""
@@ -407,6 +413,7 @@ msgstr ""
msgid "{displayName} ({bin}) isn't installed or on your PATH."
msgstr ""
+#: src/comments/use-comment-agent-picker.ts
#: src/components/BottomComposer.tsx
#: src/components/empty-state/CreatePromptComposer.tsx
#: src/components/handoff/OpenInAgentContextSubmenu.tsx
@@ -432,6 +439,11 @@ msgstr ""
msgid "{enabledCount}/{0} on"
msgstr ""
+#. placeholder {0}: ids.length
+#: src/comments/store.ts
+msgid "{failed} of {0} comments could not be removed from the queue."
+msgstr ""
+
#: src/components/FileTree.tsx
msgid "{failedCount, plural, one {1 file failed to upload} other {{failedCount} files failed to upload}}"
msgstr ""
@@ -569,6 +581,10 @@ msgstr ""
msgid "{propPanelDescriptorLabel} Properties"
msgstr ""
+#: src/components/ComposerAddContextMenu.tsx
+msgid "{queueCount, plural, one {# comment} other {# comments}}"
+msgstr ""
+
#: src/components/ActivityModeContent.tsx
#: src/components/ActivityPanelBurstRow.tsx
#: src/components/ActivityPanelFileRow.tsx
@@ -904,6 +920,11 @@ msgstr ""
msgid "Add"
msgstr ""
+#: src/comments/CommentSelectionAffordance.tsx
+#: src/comments/PropertyCommentButton.tsx
+msgid "Add a comment"
+msgstr ""
+
#: src/components/settings/SearchSection.tsx
msgid "Add a key"
msgstr ""
@@ -924,6 +945,14 @@ msgstr ""
msgid "Add at least one letter or number."
msgstr ""
+#: src/comments/CommentSelectionAffordance.tsx
+msgid "Add Comment"
+msgstr ""
+
+#: src/components/ComposerAddContextMenu.tsx
+msgid "Add context to this message"
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Add cursors or select matching occurrences through CodeMirror."
msgstr ""
@@ -996,6 +1025,14 @@ msgstr ""
msgid "Add the next matching source selection."
msgstr ""
+#: src/comments/comment-chips.tsx
+msgid "Add the queued comments to this message"
+msgstr ""
+
+#: src/comments/PropertyCommentButton.tsx
+msgid "Add to queue"
+msgstr ""
+
#: src/components/settings/frontmatter-schema-field-editor.tsx
msgid "Add value"
msgstr ""
@@ -1253,11 +1290,11 @@ msgstr ""
msgid "Ask {agentName}"
msgstr ""
+#: src/comments/CommentBubbleButton.tsx
#: src/components/BottomComposer.tsx
#: src/components/EditorFooter.tsx
#: src/components/OnboardingCard.tsx
#: src/components/ProblemsPanel.tsx
-#: src/editor/bubble-menu/EditWithAiBubbleButton.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "Ask AI"
msgstr ""
@@ -1611,6 +1648,7 @@ msgstr ""
msgid "Can't safely edit this tool's config"
msgstr ""
+#: src/comments/PropertyCommentButton.tsx
#: src/components/acp/ThreadHistoryMenu.tsx
#: src/components/ActivityPanelBurstRow.tsx
#: src/components/AuthModal.tsx
@@ -1695,6 +1733,7 @@ msgstr ""
msgid "Checked by: {0}"
msgstr ""
+#: src/comments/CommentQueuePanel.tsx
#: src/components/BottomComposer.tsx
msgid "Checking for agents"
msgstr ""
@@ -1741,6 +1780,10 @@ msgstr ""
msgid "Choose what a new session starts"
msgstr ""
+#: src/comments/CommentQueuePanel.tsx
+msgid "Choose where to send the queue"
+msgstr ""
+
#: src/components/settings/SharingSection.tsx
msgid "Choose whether this project's OpenKnowledge setup, including its AI-tool connections, is saved with the project so teammates get it too, or kept only on your computer."
msgstr ""
@@ -1777,6 +1820,7 @@ msgstr ""
msgid "Cleanup log"
msgstr ""
+#: src/comments/CommentQueuePanel.tsx
#: src/components/settings/SearchSection.tsx
msgid "Clear"
msgstr ""
@@ -1862,6 +1906,7 @@ msgstr ""
msgid "Cloning..."
msgstr ""
+#: src/comments/CommentsPanel.tsx
#: src/components/EditorTabs.tsx
#: src/components/FeedbackForm.tsx
#: src/components/InstallInClaudeDesktopDialog.tsx
@@ -1891,6 +1936,10 @@ msgstr ""
msgid "Close all unpinned"
msgstr ""
+#: src/comments/CommentMarginRail.tsx
+msgid "Close comment"
+msgstr ""
+
#: src/components/AgentDiffPane.tsx
#: src/components/TimelineDiffPane.tsx
msgid "Close diff"
@@ -2017,6 +2066,19 @@ msgstr ""
msgid "Commands run with the full access of your macOS user account on this machine. Turn this off to disable the shell."
msgstr ""
+#: src/comments/PropertyCommentButton.tsx
+msgid "Comment on {address}"
+msgstr ""
+
+#: src/lib/keyboard-shortcuts.ts
+msgid "Comment on selection"
+msgstr ""
+
+#: src/comments/CommentsPanel.tsx
+#: src/components/DocPanel.tsx
+msgid "Comments"
+msgstr ""
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "Commit or stash changes to switch:"
msgstr ""
@@ -2503,6 +2565,15 @@ msgstr ""
msgid "Could not write project files. Try a different location."
msgstr ""
+#. placeholder {0}: err.message
+#: src/comments/store.ts
+msgid "Couldn't add that comment: {0}"
+msgstr ""
+
+#: src/comments/store.ts
+msgid "Couldn't add that comment."
+msgstr ""
+
#. placeholder {0}: err instanceof Error ? err.message : String(err)
#: src/components/settings/AiToolsSection.tsx
#: src/components/settings/ProjectAiToolsSection.tsx
@@ -2562,6 +2633,10 @@ msgstr ""
msgid "Couldn't delete template: {error}"
msgstr ""
+#: src/comments/store.ts
+msgid "Couldn't delete that comment."
+msgstr ""
+
#: src/components/settings/AccountSection.tsx
msgid "Couldn't disconnect — please try again."
msgstr ""
@@ -2639,6 +2714,10 @@ msgstr ""
msgid "Couldn't open the terminal — please try again."
msgstr ""
+#: src/comments/use-comment-delivery.ts
+msgid "Couldn't open the terminal — the comments stay queued."
+msgstr ""
+
#: src/components/NewWorktreeDialog.tsx
msgid "Couldn't open the worktree. Try again."
msgstr ""
@@ -2647,6 +2726,14 @@ msgstr ""
msgid "Couldn't pull from GitHub. Check your connection and sign-in, then retry."
msgstr ""
+#: src/comments/store.ts
+msgid "Couldn't queue that comment."
+msgstr ""
+
+#: src/comments/store.ts
+msgid "Couldn't re-place that comment."
+msgstr ""
+
#: src/components/ConnectingBanner.tsx
msgid "Couldn't reach collab server — {errorDetail}. Try <0>ok status</0> or check <1>.ok/local/last-spawn-error.log</1>."
msgstr ""
@@ -2667,6 +2754,19 @@ msgstr ""
msgid "Couldn't reach the endpoint. Check the URL and that the server is up."
msgstr ""
+#: src/comments/store.ts
+msgid "Couldn't read the queued comments — nothing was sent."
+msgstr ""
+
+#. placeholder {0}: err.message
+#: src/comments/store.ts
+msgid "Couldn't read the queued comments: {0}"
+msgstr ""
+
+#: src/comments/queue-attachment.ts
+msgid "Couldn't read the queued comments."
+msgstr ""
+
#: src/components/EditorActivityPool.tsx
msgid "Couldn't reconnect after server restart"
msgstr ""
@@ -2675,6 +2775,10 @@ msgstr ""
msgid "Couldn't remove <0>{targetGitPath}</0>: {removeGitError}"
msgstr ""
+#: src/comments/store.ts
+msgid "Couldn't remove that comment from the queue."
+msgstr ""
+
#. placeholder {0}: skill.name
#. placeholder {1}: result.error
#: src/components/SkillRenameDialog.tsx
@@ -2691,6 +2795,14 @@ msgstr ""
msgid "Couldn't rename template: {0}"
msgstr ""
+#: src/comments/store.ts
+msgid "Couldn't reopen that comment."
+msgstr ""
+
+#: src/comments/store.ts
+msgid "Couldn't resolve that comment."
+msgstr ""
+
#: src/components/DiffViewBoundary.tsx
msgid "Couldn't resolve the conflict for {filePath}."
msgstr ""
@@ -2724,6 +2836,10 @@ msgstr ""
msgid "Couldn't save template: {error}"
msgstr ""
+#: src/comments/store.ts
+msgid "Couldn't save that edit."
+msgstr ""
+
#: src/components/settings/SearchSection.tsx
msgid "Couldn't save the key — please try again."
msgstr ""
@@ -2736,6 +2852,14 @@ msgstr ""
msgid "Couldn't send the report"
msgstr ""
+#: src/components/BottomComposer.tsx
+msgid "Couldn't send your comments — please try again."
+msgstr ""
+
+#: src/comments/use-comment-delivery.ts
+msgid "Couldn't send your comments — the workspace isn't ready."
+msgstr ""
+
#: src/components/BottomComposer.tsx
msgid "Couldn't send your prompt — please try again."
msgstr ""
@@ -2783,6 +2907,10 @@ msgstr ""
msgid "Couldn't update skills sharing — {detail}."
msgstr ""
+#: src/comments/use-comment-delivery.ts
+msgid "Couldn't work out where to send the comments — they stay queued."
+msgstr ""
+
#: src/components/ConsentDialogBody.tsx
msgid "Counting markdown files"
msgstr ""
@@ -3077,6 +3205,10 @@ msgstr ""
msgid "Delete selected table"
msgstr ""
+#: src/comments/CommentsPanel.tsx
+msgid "Delete this comment"
+msgstr ""
+
#: src/components/acp/ThreadHistoryMenu.tsx
msgid "Delete this conversation?"
msgstr ""
@@ -3238,6 +3370,10 @@ msgstr ""
msgid "Disambiguates similarly-named templates in the menu."
msgstr ""
+#: src/comments/CommentSelectionAffordance.tsx
+msgid "Discard this comment"
+msgstr ""
+
#: src/components/settings/AccountSection.tsx
msgid "Disconnect"
msgstr ""
@@ -3517,6 +3653,10 @@ msgstr ""
msgid "Edit source pane and code property fields"
msgstr ""
+#: src/comments/CommentsPanel.tsx
+msgid "Edit this comment"
+msgstr ""
+
#: src/editor/slash-command/embed-starter-items.tsx
msgid "Edit this HTML — the preview updates live."
msgstr ""
@@ -4603,6 +4743,16 @@ msgstr ""
msgid "Go to line {0} in {1}"
msgstr ""
+#. placeholder {0}: docBasename(thread.docName)
+#: src/comments/comment-chips.tsx
+#: src/comments/CommentQueuePanel.tsx
+msgid "Go to this comment in {0}"
+msgstr ""
+
+#: src/comments/comment-chips.tsx
+msgid "gone"
+msgstr ""
+
#: src/components/FeedbackForm.tsx
msgid "Good"
msgstr ""
@@ -4757,10 +4907,18 @@ msgstr ""
msgid "Hide problem indicators"
msgstr ""
+#: src/comments/comment-chips.tsx
+msgid "Hide queued comments"
+msgstr ""
+
#: src/editor/find-replace/FindReplaceBar.tsx
msgid "Hide replace"
msgstr ""
+#: src/comments/CommentsPanel.tsx
+msgid "Hide resolved"
+msgstr ""
+
#: src/components/BottomComposer.tsx
msgid "Hide selection preview"
msgstr ""
@@ -4924,6 +5082,14 @@ msgstr ""
msgid "In the Claude Desktop App"
msgstr ""
+#: src/comments/CommentQueuePanel.tsx
+msgid "Include in dispatch"
+msgstr ""
+
+#: src/comments/comment-chips.tsx
+msgid "Include this comment in the next send"
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Indent or outdent list item"
msgstr ""
@@ -5179,6 +5345,10 @@ msgstr ""
msgid "Jump to tab 1-8"
msgstr ""
+#: src/comments/CommentsPanel.tsx
+msgid "Jump to the anchored text"
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Jump to the markdown source for the block at the cursor, centered and highlighted."
msgstr ""
@@ -5260,6 +5430,10 @@ msgstr ""
msgid "Learn more about {title}"
msgstr ""
+#: src/comments/comment-chips.tsx
+msgid "Leave these comments out of this message"
+msgstr ""
+
#: src/components/settings/TerminalSection.tsx
msgid "Let agents use OpenKnowledge without asking"
msgstr ""
@@ -6015,10 +6189,19 @@ msgstr ""
msgid "No active or recent OpenKnowledge projects were found."
msgstr ""
+#: src/comments/use-comment-delivery.ts
+msgid "No agent is set up yet — opening Configure agents."
+msgstr ""
+
+#: src/components/BottomComposer.tsx
+msgid "No agent is set up yet — pick one from the send menu."
+msgstr ""
+
#: src/components/settings/ConfigureAgentsSection.tsx
msgid "No agents available."
msgstr ""
+#: src/comments/CommentQueuePanel.tsx
#: src/components/BottomComposer.tsx
msgid "No agents enabled"
msgstr ""
@@ -6047,6 +6230,10 @@ msgstr ""
msgid "No collab server for this worktree — run <0>ok start</0> here, or reopen the project."
msgstr ""
+#: src/comments/CommentsPanel.tsx
+msgid "No comments yet. Select text in the document to add one."
+msgstr ""
+
#: src/components/AgentDiffPane.tsx
msgid "No content changes at this version."
msgstr ""
@@ -6379,6 +6566,14 @@ msgstr ""
msgid "nothing ({0} is not a valid pattern)"
msgstr ""
+#: src/components/ComposerAddContextMenu.tsx
+msgid "Nothing queued"
+msgstr ""
+
+#: src/comments/CommentQueuePanel.tsx
+msgid "Nothing queued. Comment on a passage to add it here."
+msgstr ""
+
#: src/components/FolderPropertiesCard.tsx
msgid "Nothing set yet."
msgstr ""
@@ -6449,6 +6644,14 @@ msgstr ""
msgid "On — your search queries and the text of matching pages are sent to your embeddings provider (OpenAI by default) to compute embeddings."
msgstr ""
+#: src/comments/PropertyCommentButton.tsx
+msgid "On <0>{address}</0>"
+msgstr ""
+
+#: src/comments/PropertyCommentButton.tsx
+msgid "On selected text in <0>{address}</0>"
+msgstr ""
+
#. Next step for a Cursor project MCP row — Cursor leaves project servers disabled
#: src/components/settings/ProjectAiToolsSection.tsx
msgid "One more step: enable it in Cursor → Settings → Tools & MCP (Cursor leaves project servers off until you turn them on)."
@@ -6574,6 +6777,10 @@ msgstr ""
msgid "Open CodeMirror's lint diagnostics panel."
msgstr ""
+#: src/comments/CommentMarginRail.tsx
+msgid "Open comment"
+msgstr ""
+
#: src/components/FileTree.tsx
msgid "Open containing folder"
msgstr ""
@@ -6711,6 +6918,10 @@ msgstr ""
msgid "Open that worktree instead"
msgstr ""
+#: src/lib/keyboard-shortcuts.ts
+msgid "Open the comment composer on the current selection and add it to the dispatch queue."
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Open the insert menu in an empty or active text position."
msgstr ""
@@ -6870,6 +7081,10 @@ msgstr ""
msgid "Orphan mode"
msgstr ""
+#: src/comments/CommentsPanel.tsx
+msgid "Orphaned"
+msgstr ""
+
#: src/components/GraphPanel.tsx
msgid "Orphans"
msgstr ""
@@ -7380,10 +7595,19 @@ msgstr ""
msgid "Pushing"
msgstr ""
+#: src/comments/comment-chips.tsx
+#: src/comments/CommentQueuePanel.tsx
+#: src/comments/CommentsPanel.tsx
+#: src/comments/CommentsTab.tsx
+#: src/components/ComposerAddContextMenu.tsx
+msgid "Queue"
+msgstr ""
+
#: src/components/acp/ThreadView.tsx
msgid "Queue message"
msgstr ""
+#: src/comments/CommentsPanel.tsx
#: src/components/acp/ThreadView.tsx
msgid "Queued"
msgstr ""
@@ -7408,6 +7632,10 @@ msgstr ""
msgid "Re-embedding happens as searches run, so coverage restarts at zero and refills."
msgstr ""
+#: src/comments/CommentsPanel.tsx
+msgid "Re-place on selected text"
+msgstr ""
+
#: src/components/ProblemsPanel.tsx
msgid "Re-run the project audit"
msgstr ""
@@ -7594,11 +7822,19 @@ msgstr ""
msgid "Remove field {field}"
msgstr ""
+#: src/comments/CommentQueuePanel.tsx
+msgid "Remove from queue"
+msgstr ""
+
#: src/components/NavigatorApp.tsx
#: src/components/recent-remove-controls.tsx
msgid "Remove from recent projects"
msgstr ""
+#: src/comments/CommentsPanel.tsx
+msgid "Remove from the queue"
+msgstr ""
+
#. placeholder {0}: index + 1
#: src/components/ArrayOfObjectsWidget.tsx
msgid "Remove item {0}"
@@ -7629,6 +7865,10 @@ msgstr ""
msgid "Remove the parent <0>.git</0> folder"
msgstr ""
+#: src/comments/comment-chips.tsx
+msgid "Remove this comment from the queue"
+msgstr ""
+
#: src/lib/install-recent-removed-listener.ts
msgid "Removed \"{projectName}\" from recent projects. Its folder no longer exists."
msgstr ""
@@ -7706,6 +7946,10 @@ msgstr ""
msgid "Rendered"
msgstr ""
+#: src/comments/CommentsPanel.tsx
+msgid "Reopen"
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Reopen closed tab"
msgstr ""
@@ -7839,10 +8083,18 @@ msgstr ""
msgid "Resize {handleKey}"
msgstr ""
+#: src/comments/CommentsPanel.tsx
+msgid "Resolve"
+msgstr ""
+
#: src/components/SyncStatusBadge.tsx
msgid "Resolve conflict in your terminal"
msgstr ""
+#: src/comments/CommentsPanel.tsx
+msgid "Resolved"
+msgstr ""
+
#: src/components/CreateProjectDialog.tsx
msgid "Resolving default location"
msgstr ""
@@ -8287,6 +8539,10 @@ msgstr ""
msgid "Select the full source document."
msgstr ""
+#: src/comments/CommentsPanel.tsx
+msgid "Select this text in the property"
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Select, enter, or leave block components and fallback source blocks from keyboard boundaries."
msgstr ""
@@ -8345,10 +8601,22 @@ msgstr ""
msgid "Send feedback…"
msgstr ""
+#: src/comments/QueueNewChatRow.tsx
+msgid "Send queue to"
+msgstr ""
+
#: src/components/ReportBugDialogBody.tsx
msgid "Send report"
msgstr ""
+#: src/comments/CommentSelectionAffordance.tsx
+msgid "Send to AI"
+msgstr ""
+
+#: src/comments/CommentQueuePanel.tsx
+msgid "Send to chat"
+msgstr ""
+
#: src/components/ReportBugDialogBody.tsx
msgid "Send your report by email"
msgstr ""
@@ -8374,6 +8642,10 @@ msgstr ""
msgid "Sent to <0>{endpointHost}</0> to embed your content. Stored on this machine only (in <1>~/.ok/secrets.yml</1>), never in the project."
msgstr ""
+#: src/comments/store.ts
+msgid "Sent, but the comments could not be marked done — they are still queued."
+msgstr ""
+
#: src/editor/slash-command/items.tsx
msgid "Separator"
msgstr ""
@@ -8658,10 +8930,19 @@ msgstr ""
msgid "Show problem indicators"
msgstr ""
+#: src/comments/comment-chips.tsx
+msgid "Show queued comments"
+msgstr ""
+
#: src/editor/find-replace/FindReplaceBar.tsx
msgid "Show replace"
msgstr ""
+#. placeholder {0}: resolved.length
+#: src/comments/CommentsPanel.tsx
+msgid "Show resolved ({0})"
+msgstr ""
+
#: src/components/BottomComposer.tsx
msgid "Show selection preview"
msgstr ""
@@ -8896,6 +9177,11 @@ msgstr ""
msgid "Start {agentName}, {hint}"
msgstr ""
+#: src/comments/CommentQueuePanel.tsx
+#: src/comments/QueueNewChatRow.tsx
+msgid "Start a new chat"
+msgstr ""
+
#: src/components/NavigatorApp.tsx
msgid "Start a new OpenKnowledge project."
msgstr ""
@@ -9366,6 +9652,10 @@ msgstr ""
msgid "Thanks for the report!"
msgstr ""
+#: src/comments/use-comment-delivery.ts
+msgid "That app isn't available — the comments stay queued."
+msgstr ""
+
#: src/components/NewWorktreeDialog.tsx
#: src/components/ShareBranchSwitchDialog.tsx
msgid "That branch is already open in another worktree."
@@ -9400,6 +9690,10 @@ msgstr ""
msgid "The agent's persona, values, and voice."
msgstr ""
+#: src/comments/CommentsPanel.tsx
+msgid "The anchored text is gone. You can re-place it on selected text."
+msgstr ""
+
#: src/components/ProblemsPanel.tsx
msgid "The audit could not be completed. Try again."
msgstr ""
@@ -9463,6 +9757,10 @@ msgstr ""
msgid "The model id your endpoint serves. Its vector size is detected automatically — clear the field to go back to {DEFAULT_EMBEDDINGS_MODEL}."
msgstr ""
+#: src/components/TerminalSessionsHost.tsx
+msgid "the open agent"
+msgstr ""
+
#: src/editor/components/PreviewBlockedNotice.tsx
msgid "The preview blocks resources that don't meet its security rules (for example plain http:// URLs, or code that uses eval). The content above may render incompletely."
msgstr ""
@@ -9484,6 +9782,10 @@ msgstr ""
msgid "The provider rejected the request. Check the API key and the model id."
msgstr ""
+#: src/comments/comment-chips.tsx
+msgid "The quoted text is no longer in the document — the agent will be told."
+msgstr ""
+
#: src/components/ReportBugDialogBody.tsx
msgid "The report service couldn't be reached."
msgstr ""
@@ -9508,6 +9810,10 @@ msgstr ""
msgid "The terminal is turned off for this project. Turn it back on to run commands here."
msgstr ""
+#: src/comments/use-comment-delivery.ts
+msgid "The terminal isn't available here — the comments stay queued."
+msgstr ""
+
#. placeholder {0}: info.exitCode
#: src/components/TerminalExitNotice.tsx
msgid "The terminal session ended (exit code {0})."
@@ -9612,6 +9918,10 @@ msgstr ""
msgid "This branch is checked out in:"
msgstr ""
+#: src/comments/CommentsPanel.tsx
+msgid "This comment is on the whole property"
+msgstr ""
+
#: src/components/PanelScopeHeader.tsx
msgid "This doc"
msgstr ""
@@ -10533,6 +10843,10 @@ msgstr ""
msgid "Word wrap"
msgstr ""
+#: src/components/BottomComposer.tsx
+msgid "Work through these comments"
+msgstr ""
+
#: src/components/McpConsentDialogBody.tsx
#: src/components/NewWorktreeDialog.tsx
#: src/components/SkillEditorActions.tsx
diff --git a/packages/app/tests/integration/api-error-envelope/comment-counts.test.ts b/packages/app/tests/integration/api-error-envelope/comment-counts.test.ts
new file mode 100644
index 000000000..14b3f4648
--- /dev/null
+++ b/packages/app/tests/integration/api-error-envelope/comment-counts.test.ts
@@ -0,0 +1,140 @@
+/**
+ * Per-handler narrow-integration smoke test for `handleCommentCounts`.
+ *
+ * `GET /api/comment-counts` is the read-side door MCP enrichment knocks on to
+ * annotate every file and folder `exec` reports, so its wire contract is pinned
+ * the same way `/api/backlink-counts` is:
+ * - both query modes (`docNames` exact set, `prefix` folder rollup) return
+ * 200 + `application/json` parsing against `CommentCountsSuccessSchema`.
+ * - neither param → `urn:ok:error:invalid-request`.
+ * - a malformed `prefix` is a 400 rather than a silent drop — dropping it
+ * would widen the query to the whole project.
+ * - method-not-allowed on POST emits `urn:ok:error:method-not-allowed` +
+ * `Allow: GET`.
+ *
+ * It also pins the route as READ-ONLY: unlike `/api/comments` (whose POST
+ * creates threads) this one is deliberately outside `MUTATING_ROUTES`, so a
+ * plain GET must not trip the loopback/Host gate.
+ */
+
+import { CommentCountsSuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
+import { createTestServer, type TestServer } from '../test-harness';
+
+let server: TestServer;
+
+beforeAll(async () => {
+ server = await createTestServer();
+}, HARNESS_BOOT_TIMEOUT_MS);
+
+afterAll(async () => {
+ await server.cleanup();
+});
+
+describe('comment-counts envelope (RFC 9457)', () => {
+ test('docNames mode answers for every doc asked about', async () => {
+ const res = await fetch(
+ `http://127.0.0.1:${server.port}/api/comment-counts?docNames=alpha,beta`,
+ );
+ expect(res.status).toBe(200);
+ expect(res.headers.get('content-type')).toBe('application/json');
+
+ const body = await res.json();
+ const parsed = CommentCountsSuccessSchema.safeParse(body);
+ expect(parsed.success).toBe(true);
+ if (parsed.success) {
+ // Zero, not absent: the caller has to tell "no comments" from "not asked".
+ expect(parsed.data.counts).toEqual({ alpha: 0, beta: 0 });
+ }
+ expect((body as Record<string, unknown>).ok).toBeUndefined();
+ });
+
+ test('prefix mode is sparse — a clean subtree returns no rows', async () => {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/comment-counts?prefix=docs`);
+ expect(res.status).toBe(200);
+
+ const parsed = CommentCountsSuccessSchema.safeParse(await res.json());
+ expect(parsed.success).toBe(true);
+ if (parsed.success) expect(parsed.data.counts).toEqual({});
+ });
+
+ test('neither param emits urn:ok:error:invalid-request', async () => {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/comment-counts`);
+ expect(res.status).toBe(400);
+ expect(res.headers.get('content-type')).toBe('application/problem+json');
+
+ const parsed = ProblemDetailsSchema.safeParse(await res.json());
+ expect(parsed.success).toBe(true);
+ if (parsed.success) {
+ expect(parsed.data.type).toBe('urn:ok:error:invalid-request');
+ expect(parsed.data.title).toContain('docNames');
+ }
+ });
+
+ test('a malformed prefix is rejected, not silently widened', async () => {
+ const res = await fetch(
+ `http://127.0.0.1:${server.port}/api/comment-counts?prefix=${encodeURIComponent('../escape')}`,
+ );
+ expect(res.status).toBe(400);
+
+ const parsed = ProblemDetailsSchema.safeParse(await res.json());
+ expect(parsed.success).toBe(true);
+ if (parsed.success) {
+ expect(parsed.data.type).toBe('urn:ok:error:invalid-request');
+ expect(parsed.data.title).toContain('prefix');
+ }
+ });
+
+ test('a real comment shows up in both modes', async () => {
+ // End-to-end through the chain the MCP read path depends on: create a doc,
+ // comment on it, and the counts must move. Pins that the index the
+ // endpoint reads is the same one the create path writes.
+ const docName = 'rollout-notes';
+ const created = await fetch(`http://127.0.0.1:${server.port}/api/create-page`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ path: `${docName}.md` }),
+ });
+ expect(created.status).toBe(200);
+
+ await fetch(`http://127.0.0.1:${server.port}/api/agent-write-md`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ docName,
+ markdown: 'Ship with minimal downtime.\n',
+ position: 'replace',
+ }),
+ });
+
+ const posted = await fetch(`http://127.0.0.1:${server.port}/api/comments`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ docName, quote: 'minimal downtime', body: 'still accurate?' }),
+ });
+ expect(posted.status).toBe(201);
+
+ const exact = await fetch(
+ `http://127.0.0.1:${server.port}/api/comment-counts?docNames=${docName}`,
+ );
+ expect(((await exact.json()) as { counts: Record<string, number> }).counts[docName]).toBe(1);
+
+ const rollup = await fetch(`http://127.0.0.1:${server.port}/api/comment-counts?prefix=`);
+ expect(((await rollup.json()) as { counts: Record<string, number> }).counts[docName]).toBe(1);
+ });
+
+ test('method-not-allowed on POST emits problem+json with Allow: GET', async () => {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/comment-counts`, {
+ method: 'POST',
+ });
+ expect(res.status).toBe(405);
+ expect(res.headers.get('allow')).toBe('GET');
+
+ const parsed = ProblemDetailsSchema.safeParse(await res.json());
+ expect(parsed.success).toBe(true);
+ if (parsed.success) {
+ expect(parsed.data.type).toBe('urn:ok:error:method-not-allowed');
+ }
+ });
+});
diff --git a/packages/app/tests/integration/attribution-sweep-coverage.test.ts b/packages/app/tests/integration/attribution-sweep-coverage.test.ts
index 172dd32c6..5bee25ad8 100644
--- a/packages/app/tests/integration/attribution-sweep-coverage.test.ts
+++ b/packages/app/tests/integration/attribution-sweep-coverage.test.ts
@@ -104,6 +104,11 @@ const EXEMPT_HANDLERS = new Set([
'handleAssetText',
'handleBacklinks',
'handleBacklinkCounts',
+ // GET /api/comment-counts — read-only count lookup over the comment index.
+ // It creates and edits nothing, so there is no authorship to attribute; the
+ // thread mutations that DO need identity go through `/api/comment`'s
+ // `extractActorIdentity` boundary.
+ 'handleCommentCounts',
'handleForwardLinks',
// POST /api/link-preview — read-only external metadata fetch for the editor
// hover card. No Y.Doc / vault mutation and no agent-authored content; its
@@ -221,6 +226,15 @@ const EXEMPT_HANDLERS = new Set([
// to the `renderer` pino log (diagnostics), no Y.Docs / agent content; gated
// by `checkLocalOpSecurity` like the local-op handlers. No identity needed.
'handleClientLogs',
+ // `/api/comments` + `/api/comment` — comment-thread dispatchers (methodRouter
+ // GET list/read + POST create/mutate). Same posture as the `handleSkill` /
+ // `handleTemplate` dispatchers: the route-registry entry is the dispatcher,
+ // and the mutating sub-handlers thread `extractActorIdentity` themselves in
+ // `packages/server/src/comments/comment-api.ts`. Thread text is machine-local
+ // (`.ok/local/comments/`), never committed, and the app is the only client
+ // (agents reach comments via dispatch, not MCP).
+ 'handleCommentsRoute',
+ 'handleCommentRoute',
'handleWorkspace',
'handleRescueList',
'handleSyncStatus',
diff --git a/packages/app/tests/integration/conflict-gate-coverage.test.ts b/packages/app/tests/integration/conflict-gate-coverage.test.ts
index c6caa87c9..556428ef9 100644
--- a/packages/app/tests/integration/conflict-gate-coverage.test.ts
+++ b/packages/app/tests/integration/conflict-gate-coverage.test.ts
@@ -97,6 +97,11 @@ const EXEMPT_HANDLERS = new Set([
'handleAssetText',
'handleBacklinks',
'handleBacklinkCounts',
+ // GET /api/comment-counts — read-only unresolved-comment counts served from
+ // the in-memory comment index (per-doc or per-folder-prefix), feeding MCP
+ // read enrichment. No Y.Doc mutation, so the conflict-refusal gate doesn't
+ // apply; the thread-mutating routes are `/api/comments` + `/api/comment`.
+ 'handleCommentCounts',
'handleForwardLinks',
// POST /api/link-preview — read-only external metadata fetch; never writes a
// doc, so there is no in-conflict write to gate.
@@ -164,6 +169,14 @@ const EXEMPT_HANDLERS = new Set([
// `renderer` pino log (diagnostics), targets no Y.Doc, so the per-doc
// conflict gate does not apply.
'handleClientLogs',
+ // `/api/comments` + `/api/comment` — comment-thread dispatchers. Threads live
+ // in `.ok/local/comments/`, entirely outside the CRDT/content plane: these
+ // routes never write document bytes, so the conflict-refusal gate has nothing
+ // to refuse. A doc in conflict can still be commented on (the comment is
+ // about the text, not a change to it); the anchor re-find reads the body but
+ // never mutates it.
+ 'handleCommentsRoute',
+ 'handleCommentRoute',
'handleWorkspace',
// `/api/config` — collab-bootstrap payload. GET reads server-lock. Does not
// target a Y.Doc, so the per-doc conflict gate does not apply.
diff --git a/packages/core/src/comments/passage-match.test.ts b/packages/core/src/comments/passage-match.test.ts
new file mode 100644
index 000000000..577ca6711
--- /dev/null
+++ b/packages/core/src/comments/passage-match.test.ts
@@ -0,0 +1,157 @@
+/**
+ * Markdown/rendered passage matching.
+ *
+ * The cases below are the ones that reached users as a bare 400 "the quoted
+ * passage is not in the document": a comment on a bullet whose text starts
+ * after a bold run, and a selection spanning a heading and the list under it.
+ */
+
+import { describe, expect, test } from 'vitest';
+import { findAllPassages, findPassage } from './passage-match.ts';
+
+const BODY = `## Ingredients
+
+- 1½ cups shelled edamame (frozen, thawed)
+- **Peanut sauce:** 3 tbsp peanut butter, 2 tbsp soy sauce, water to loosen
+- Scallions, chopped peanuts, to serve
+
+## Steps
+
+1. Toss the tofu with the cornstarch and a pinch of salt.
+2. Stir-fry the bell pepper 2–3 min, then add the edamame.
+`;
+
+/** The body slice a caller would store as the anchor's exact quote. */
+function slice(needle: string, syntaxIn: 'haystack' | 'needle' = 'haystack'): string | null {
+ const hit = findPassage(BODY, needle, { syntaxIn });
+ return hit ? BODY.slice(hit.start, hit.end) : null;
+}
+
+describe('rendered text against a markdown body', () => {
+ test('finds a passage that starts after a bold run inside a bullet', () => {
+ // The reported failure: the source line is
+ // `- **Peanut sauce:** 3 tbsp ...`, so neither the rendered text nor a
+ // serialized partial selection is a literal substring of the body.
+ expect(slice('3 tbsp peanut butter, 2 tbsp soy sauce')).toBe(
+ '3 tbsp peanut butter, 2 tbsp soy sauce',
+ );
+ });
+
+ test('spans the emphasis markers when the passage crosses them', () => {
+ expect(slice('Peanut sauce: 3 tbsp peanut butter')).toBe(
+ 'Peanut sauce:** 3 tbsp peanut butter',
+ );
+ });
+
+ test('skips the leading `**` rather than opening the range on it', () => {
+ const hit = findPassage(BODY, 'Peanut sauce:', { syntaxIn: 'haystack' });
+ expect(BODY.slice(hit?.start ?? 0, hit?.end ?? 0)).toBe('Peanut sauce:');
+ });
+
+ test('crosses a heading marker and an ordered-list marker', () => {
+ expect(slice('Steps Toss the tofu with the cornstarch')).toBe(
+ 'Steps\n\n1. Toss the tofu with the cornstarch',
+ );
+ });
+
+ test('crosses bullet markers between list items', () => {
+ expect(slice('thawed) Peanut sauce:')).toBe('thawed)\n- **Peanut sauce:');
+ });
+
+ test('still refuses a passage that is not there', () => {
+ expect(findPassage(BODY, 'gochujang to taste', { syntaxIn: 'haystack' })).toBeNull();
+ });
+
+ test('does not let syntax elasticity bridge different words', () => {
+ // `peanut butter` and `soy sauce` both occur, but not adjacently — a fuzzy
+ // matcher would happily join them.
+ expect(findPassage(BODY, 'peanut soy', { syntaxIn: 'haystack' })).toBeNull();
+ });
+
+ test('an exact substring resolves to itself', () => {
+ expect(slice('Scallions, chopped peanuts, to serve')).toBe(
+ 'Scallions, chopped peanuts, to serve',
+ );
+ });
+
+ test('reports every occurrence in document order', () => {
+ const hits = findAllPassages('a soy b soy', 'soy', { syntaxIn: 'haystack' });
+ expect(hits.map((h) => h.start)).toEqual([2, 8]);
+ });
+
+ test('an empty needle matches nothing', () => {
+ expect(findAllPassages(BODY, '', { syntaxIn: 'haystack' })).toEqual([]);
+ });
+});
+
+describe('a markdown quote against rendered text', () => {
+ // The mirror direction: a stored anchor is markdown, the editor's text index
+ // is rendered, so the syntax now sits in the needle.
+ const RENDERED = 'Peanut sauce: 3 tbsp peanut butter, 2 tbsp soy sauce, water to loosen';
+
+ test('finds a bolded quote in rendered text', () => {
+ const hit = findPassage(RENDERED, '**Peanut sauce:** 3 tbsp', { syntaxIn: 'needle' });
+ expect(RENDERED.slice(hit?.start ?? -1, hit?.end ?? -1)).toBe('Peanut sauce: 3 tbsp');
+ });
+
+ test('finds a quote carrying a list marker it no longer renders', () => {
+ const hit = findPassage(RENDERED, '- **Peanut sauce:** 3 tbsp', { syntaxIn: 'needle' });
+ expect(hit?.start).toBe(0);
+ });
+
+ test('rejects a quote whose words are absent', () => {
+ expect(findPassage(RENDERED, '**Chili crisp:**', { syntaxIn: 'needle' })).toBeNull();
+ });
+});
+
+describe('links', () => {
+ // A link renders as its label alone, so `](target)` is invisible to anyone
+ // selecting rendered text. Missing that made every passage containing a link
+ // unmatchable — which, in a linked wiki, is most of the interesting ones.
+ const BODY =
+ '- **Leftovers:** any half-finished tin goes into [Sardine Toast](../sardine/toast.md) or [[lemon-garlic]] the next day.';
+
+ test('matches across an inline link', () => {
+ const hit = findPassage(BODY, 'goes into Sardine Toast or', { syntaxIn: 'haystack' });
+ expect(hit).not.toBeNull();
+ expect(BODY.slice(hit?.start, hit?.end)).toContain('Sardine Toast');
+ });
+
+ test('matches across a wiki link', () => {
+ expect(
+ findPassage(BODY, 'or lemon-garlic the next day.', { syntaxIn: 'haystack' }),
+ ).not.toBeNull();
+ });
+
+ test('matches a whole bullet containing two links', () => {
+ const hit = findPassage(
+ BODY,
+ 'Leftovers: any half-finished tin goes into Sardine Toast or lemon-garlic the next day.',
+ { syntaxIn: 'haystack' },
+ );
+ expect(hit).not.toBeNull();
+ // The resolved range covers the real source text, target and all.
+ expect(BODY.slice(hit?.start, hit?.end)).toContain('../sardine/toast.md');
+ });
+
+ test('a match never begins on a bracket', () => {
+ // Otherwise the reported range opens with syntax the caller never selected.
+ const hit = findPassage(BODY, 'Sardine Toast', { syntaxIn: 'haystack' });
+ expect(BODY[hit?.start ?? -1]).toBe('S');
+ });
+
+ test('the mirror direction: a stored markdown quote against rendered text', () => {
+ const rendered = 'any half-finished tin goes into Sardine Toast or lemon-garlic the next day.';
+ const stored = 'goes into [Sardine Toast](../sardine/toast.md) or [[lemon-garlic]]';
+ expect(findPassage(rendered, stored, { syntaxIn: 'needle' })).not.toBeNull();
+ });
+
+ test('still refuses different words inside a link', () => {
+ expect(findPassage(BODY, 'goes into Anchovy Toast or', { syntaxIn: 'haystack' })).toBeNull();
+ });
+
+ test('a bare bracket in prose is not treated as syntax', () => {
+ const prose = 'the array[0] value is fine';
+ expect(findPassage(prose, 'array[0] value', { syntaxIn: 'haystack' })).not.toBeNull();
+ });
+});
diff --git a/packages/core/src/comments/passage-match.ts b/packages/core/src/comments/passage-match.ts
new file mode 100644
index 000000000..1d1972cdc
--- /dev/null
+++ b/packages/core/src/comments/passage-match.ts
@@ -0,0 +1,153 @@
+/**
+ * Locate a passage across the markdown / rendered-text boundary.
+ *
+ * A comment anchor is measured against a document's markdown BODY, but the
+ * editor only ever knows RENDERED text. The same passage differs between the
+ * two by exactly the characters markdown spends on formatting: `**bold**`
+ * renders as `bold`, a list item renders without its `- `, a heading without
+ * its `##`. Converting one side to the other is not reliable — serializing a
+ * partial ProseMirror selection fabricates the block marker of whatever block
+ * the selection happens to sit in, so a pick starting mid-bullet comes back as
+ * `- 3 tbsp peanut butter` when the source line reads
+ * `- **Peanut sauce:** 3 tbsp peanut butter`.
+ *
+ * So instead of converting, match the characters that survive rendering and
+ * treat markdown syntax as elastic on whichever side carries it. Every other
+ * character must still match, in order: this is not a fuzzy match and cannot
+ * land on different words.
+ */
+
+/** A located passage as `[start, end)` offsets into the haystack. */
+export interface PassageMatch {
+ readonly start: number;
+ readonly end: number;
+}
+
+export interface PassageMatchOptions {
+ /**
+ * Which side is the markdown one, and may therefore carry syntax the other
+ * side lacks. Searching a markdown body for rendered text is `'haystack'`;
+ * searching rendered editor text for a stored markdown quote is `'needle'`.
+ */
+ readonly syntaxIn: 'haystack' | 'needle';
+}
+
+/** Emphasis, strong, code, strikethrough, escape — anywhere in a line. */
+const INLINE_SYNTAX = new Set(['*', '_', '`', '~', '\\']);
+
+/**
+ * The tail of an inline link or image: `](target)`.
+ *
+ * A link renders as its label alone, so everything from the closing bracket
+ * through the closing paren is invisible to anyone selecting rendered text —
+ * and unlike `*` or `` ` ``, it is a multi-character run that has to be skipped
+ * whole. Missing this is why a passage containing any link could not be
+ * matched at all, which in a linked wiki is most of the interesting passages.
+ *
+ * A target containing an unescaped `)` truncates here; that is rare enough to
+ * accept, and it fails safe — the match simply doesn't happen.
+ */
+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]+)/;
+
+/** Widest block marker worth considering; bounds the slice the regex runs on. */
+const BLOCK_MARKER_WINDOW = 32;
+
+function isSpace(ch: string): boolean {
+ return ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r' || ch === '\f' || ch === '\v';
+}
+
+/** True when only indentation separates `i` from the start of its line. */
+function isLineStart(text: string, i: number): boolean {
+ for (let k = i - 1; k >= 0; k -= 1) {
+ const ch = text[k];
+ if (ch === '\n') return true;
+ if (ch !== ' ' && ch !== '\t') return false;
+ }
+ return true;
+}
+
+/** Length of the markdown syntax run at `i`, or 0 when `i` is content. */
+function syntaxRunAt(text: string, i: number): number {
+ const ch = text[i];
+ if (ch === undefined) return 0;
+ 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
+ // from rendered text.
+ if (ch === '[') return 1;
+ if (ch === ']') {
+ // Wiki-link close first: `]]` is never the start of a link tail.
+ if (text[i + 1] === ']') return 2;
+ return LINK_TAIL.exec(text.slice(i, i + LINK_TAIL_WINDOW))?.[0].length ?? 0;
+ }
+ if (!isLineStart(text, i)) return 0;
+ return BLOCK_MARKER.exec(text.slice(i, i + BLOCK_MARKER_WINDOW))?.[0].length ?? 0;
+}
+
+/**
+ * Every place `needle` occurs in `haystack`, in document order, allowing the
+ * markdown side to carry extra syntax characters and both sides to disagree
+ * about whitespace (a selection spanning blocks arrives with the blocks joined
+ * differently than the `\n\n` in the source).
+ */
+export function findAllPassages(
+ haystack: string,
+ needle: string,
+ { syntaxIn }: PassageMatchOptions,
+): PassageMatch[] {
+ const out: PassageMatch[] = [];
+ if (needle.length === 0) return out;
+ const syntaxInHaystack = syntaxIn === 'haystack';
+
+ for (let start = 0; start < haystack.length; start += 1) {
+ // A match never begins on a character the other side can't see, or the
+ // reported range would open with syntax the caller never selected.
+ const first = haystack[start];
+ if (first === undefined || isSpace(first)) continue;
+ if (syntaxInHaystack && syntaxRunAt(haystack, start) > 0) continue;
+
+ let hi = start;
+ let ni = 0;
+ while (hi < haystack.length && ni < needle.length) {
+ const hc = haystack[hi] as string;
+ const nc = needle[ni] as string;
+ if (hc === nc) {
+ hi += 1;
+ ni += 1;
+ continue;
+ }
+ if (isSpace(nc)) {
+ ni += 1;
+ continue;
+ }
+ if (isSpace(hc)) {
+ hi += 1;
+ continue;
+ }
+ const run = syntaxInHaystack ? syntaxRunAt(haystack, hi) : syntaxRunAt(needle, ni);
+ if (run > 0) {
+ if (syntaxInHaystack) hi += run;
+ else ni += run;
+ continue;
+ }
+ break;
+ }
+ if (ni === needle.length) out.push({ start, end: hi });
+ }
+ return out;
+}
+
+/** First occurrence of `needle`, or null. See {@link findAllPassages}. */
+export function findPassage(
+ haystack: string,
+ needle: string,
+ options: PassageMatchOptions,
+): PassageMatch | null {
+ return findAllPassages(haystack, needle, options)[0] ?? null;
+}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index be222d898..730830605 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -108,6 +108,12 @@ export {
type MenuPlatform,
type MenuSection,
} from './commands/command-identity.ts';
+export {
+ findAllPassages,
+ findPassage,
+ type PassageMatch,
+ type PassageMatchOptions,
+} from './comments/passage-match.ts';
// Sync-mode vocabulary + resolution rules (off/follow/full). Browser+node compatible.
export {
displayActiveMode,
@@ -710,6 +716,7 @@ export {
AgentWriteRequestSchema,
type AgentWriteSuccess,
AgentWriteSuccessSchema,
+ type Anchor,
type ApiConfigSuccess,
ApiConfigSuccessSchema,
assertNeverProblemType,
@@ -741,6 +748,12 @@ export {
ClientLogsRequestSchema,
type ClientLogsSuccess,
ClientLogsSuccessSchema,
+ type CommentCountsSuccess,
+ CommentCountsSuccessSchema,
+ type CommentTarget,
+ type CommentThreadMeta,
+ CommentThreadMetaSchema,
+ CompleteBatchSuccessSchema,
ConflictEntrySchema,
type ConflictEntryWire,
type ContentDivergenceCurrentState,
@@ -767,8 +780,11 @@ export {
DeletePathRequestSchema,
type DeletePathSuccess,
DeletePathSuccessSchema,
+ DeleteSuccessSchema,
type DiskEditReconciledWarning,
DiskEditReconciledWarningSchema,
+ type DispatchPayload,
+ DispatchPayloadSchema,
type DocumentListEntry,
DocumentListEntrySchema,
type DocumentListSuccess,
@@ -901,17 +917,21 @@ export {
PageHeadingsSuccessSchema,
type PagesSuccess,
PagesSuccessSchema,
+ PrepareBatchSuccessSchema,
+ PrepareDispatchSuccessSchema,
type PrincipalSuccess,
PrincipalSuccessSchema,
type ProblemDetails,
ProblemDetailsSchema,
type ProblemType,
ProblemTypeSchema,
+ type PropertyPath,
PULL_OUTCOMES,
type PullOutcome,
PullOutcomeSchema,
PushPermissionSchema,
type PushPermissionWire,
+ QueueSuccessSchema,
type RenamedAssetMapping,
RenamedAssetMappingSchema,
type RenamedDocMapping,
@@ -1140,6 +1160,7 @@ export {
TestRescanFilesSuccessSchema,
type TestResetSuccess,
TestResetSuccessSchema,
+ ThreadListSuccessSchema,
type TrashCleanupRequest,
TrashCleanupRequestSchema,
type TrashCleanupSuccess,
diff --git a/packages/core/src/schemas/api/comments.ts b/packages/core/src/schemas/api/comments.ts
new file mode 100644
index 000000000..4571fa960
--- /dev/null
+++ b/packages/core/src/schemas/api/comments.ts
@@ -0,0 +1,179 @@
+/**
+ * Comment threads — the shape shared by the store on disk and the wire.
+ *
+ * Here rather than in the server because the app consumes the same objects from
+ * `/api/comments`, and it used to carry a hand-written copy of this interface
+ * that had to be updated in lock-step. A field added on one side and forgotten
+ * on the other is a silent runtime mismatch, which is exactly what a shared
+ * schema removes.
+ *
+ * NOTE the absence of `.loose()`, which the response schemas in this directory
+ * carry. This schema also parses the on-disk thread file, where stripping
+ * unknown keys is load-bearing: a `version: 1` written by an older build has to
+ * parse and then disappear on the next write. `.loose()` would persist it
+ * instead, so the wire shape inherits the storage shape's strictness rather
+ * than the other way round.
+ */
+
+import { z } from 'zod';
+
+/**
+ * Content-addressed anchor. `exact` (+ widened `prefix`/`suffix`) is the
+ * durable record; `start`/`end` are a position hint only — a fast path, never
+ * the authority (they drift the moment text above the anchor changes).
+ */
+const AnchorSchema = z.object({
+ exact: z.string().min(1),
+ prefix: z.string(),
+ suffix: z.string(),
+ start: z.number().int().nonnegative(),
+ end: z.number().int().nonnegative(),
+});
+export type Anchor = z.infer<typeof AnchorSchema>;
+
+/**
+ * Which TEXT a thread's anchor is measured against — not the whole story of
+ * what it points at, which is `target` plus `anchor` together.
+ *
+ * `body` is the markdown after the frontmatter. `property` narrows to one
+ * frontmatter value: `key` alone is the whole property, and `path` walks into it
+ * (`['tags', 2]` → the third tag; `['author', 'name']` → a nested field).
+ *
+ * The split is deliberate. Structure is addressed by NAME, which is exact and
+ * needs no re-find — a key or an index either resolves or it does not. Prose
+ * inside a value is addressed by its WORDS, which is what `anchor` is for. So a
+ * paragraph-length `description` gets the same passage anchoring the body gets,
+ * just with a haystack of one value instead of the whole document, where the
+ * repeated-quote problem is far smaller.
+ *
+ * Absent on threads written before property targets existed, which are all body
+ * threads; the default makes those parse unchanged.
+ */
+const PropertyPathSchema = z.array(z.union([z.string(), z.number().int().nonnegative()]));
+const CommentTargetSchema = z
+ .discriminatedUnion('kind', [
+ z.object({ kind: z.literal('body') }),
+ z.object({
+ kind: z.literal('property'),
+ key: z.string().min(1),
+ /** Steps INTO the key's value. Omitted / empty means the value itself. */
+ path: PropertyPathSchema.default([]),
+ }),
+ ])
+ .default({ kind: 'body' });
+export type CommentTarget = z.infer<typeof CommentTargetSchema>;
+export type PropertyPath = z.infer<typeof PropertyPathSchema>;
+
+/**
+ * A thread's single primary state: open+healthy, open with a lost anchor, or
+ * closed. `resolved` subsumes the anchor distinction — a resolved thread isn't
+ * highlighted, and its anchor is recomputed by re-find when it reopens, so
+ * there is nothing to remember underneath.
+ */
+const ThreadStateSchema = z.enum(['anchored', 'orphaned', 'resolved']);
+
+export const CommentThreadMetaSchema = z.object({
+ threadId: z.string().min(1),
+ docName: z.string().min(1),
+ target: CommentTargetSchema,
+ /**
+ * A passage within the text `target` selects, or null for the whole thing.
+ *
+ * One field, two haystacks: with a `body` target it is a passage in the
+ * markdown; with a `property` target it is a passage inside that value — which
+ * is how a paragraph-length description gets commented on a sentence at a
+ * time. Null means the target itself is the comment's subject: the whole
+ * document is never that, so null + `body` cannot occur, but null + `property`
+ * is the ordinary "comment on this field" case.
+ *
+ * Nullable rather than a filler anchor on purpose: every re-find call site has
+ * to learn that some threads have no passage, and a stand-in `exact` would let
+ * one that forgot go looking for the key's NAME in the body and match it. That
+ * is the silently-wrong-target failure this whole subsystem is built to avoid,
+ * so the type makes forgetting a compile error instead.
+ */
+ anchor: AnchorSchema.nullable(),
+ state: ThreadStateSchema,
+ /** In the dispatch queue, waiting to be sent in the next batch. */
+ queued: z.boolean(),
+ /**
+ * What the thread is asking for. Editing replaces it — a thread holds one
+ * comment that can be revised, not a discussion, because the reader is an
+ * agent rather than a teammate.
+ */
+ latestComment: z.string(),
+ createdBy: z.string().min(1),
+ createdAt: z.number(),
+});
+export type CommentThreadMeta = z.infer<typeof CommentThreadMetaSchema>;
+
+/**
+ * What the client needs to hand one comment to an agent.
+ *
+ * Shared for the same reason the thread shape is: the app carried a
+ * hand-written copy of this interface, and `property` had to be added to both
+ * by hand when value-level targets landed. A second edit nobody is reminded to
+ * make is the whole failure mode.
+ */
+export const DispatchPayloadSchema = z
+ .object({
+ docName: z.string(),
+ instruction: z.string(),
+ /** The addressed property (`tags`, `tags[2]`, `author.name`); null for a body passage. */
+ property: z.string().nullable(),
+ /** Null when the comment is on a whole thing; with `property`, a passage inside that value. */
+ passage: z.object({ exact: z.string(), prefix: z.string(), suffix: z.string() }).nullable(),
+ /** The passage or key is gone — say so in the prompt, never silently retarget. */
+ anchorLost: z.boolean(),
+ /** The quote repeats in its document — the prompt must say which one is meant. */
+ passageRepeats: z.boolean(),
+ })
+ .loose();
+export type DispatchPayload = z.infer<typeof DispatchPayloadSchema>;
+
+/**
+ * Response envelopes. `.loose()` here, unlike the thread schema above: these are
+ * wire-only, so an unknown key from a newer server should pass through rather
+ * than fail the parse.
+ *
+ * One batch entry per requested id, in the requested order. A thread that has
+ * since been deleted is reported in place rather than failing the whole batch —
+ * the ids were chosen earlier and one going stale must not take the rest down.
+ */
+const BatchEntryBaseSchema = z.object({ threadId: z.string(), ok: z.literal(true) });
+const BatchMissingSchema = z.object({
+ threadId: z.string(),
+ ok: z.literal(false),
+ error: z.literal('not-found'),
+});
+
+export const ThreadListSuccessSchema = z
+ .object({ threads: z.array(CommentThreadMetaSchema) })
+ .loose();
+export const QueueSuccessSchema = z
+ .object({ meta: CommentThreadMetaSchema, orphaned: z.boolean() })
+ .loose();
+export const DeleteSuccessSchema = z.object({ threadId: z.string() }).loose();
+export const PrepareDispatchSuccessSchema = z
+ .object({ meta: CommentThreadMetaSchema, payload: DispatchPayloadSchema })
+ .loose();
+export const PrepareBatchSuccessSchema = z
+ .object({
+ results: z.array(
+ z.union([
+ BatchEntryBaseSchema.extend({
+ meta: CommentThreadMetaSchema,
+ payload: DispatchPayloadSchema,
+ }),
+ BatchMissingSchema,
+ ]),
+ ),
+ })
+ .loose();
+export const CompleteBatchSuccessSchema = z
+ .object({
+ results: z.array(
+ z.union([BatchEntryBaseSchema.extend({ meta: CommentThreadMetaSchema }), BatchMissingSchema]),
+ ),
+ })
+ .loose();
diff --git a/packages/core/src/schemas/api/document-read.ts b/packages/core/src/schemas/api/document-read.ts
index 9cba124be..c002da03f 100644
--- a/packages/core/src/schemas/api/document-read.ts
+++ b/packages/core/src/schemas/api/document-read.ts
@@ -211,6 +211,24 @@ export const BacklinkCountsSuccessSchema = z
.loose() satisfies StandardSchemaV1;
export type BacklinkCountsSuccess = z.infer<typeof BacklinkCountsSuccessSchema>;
+/**
+ * Success body for `GET /api/comment-counts?docNames=a,b,c` or `?prefix=folder`
+ * — unresolved comment threads per doc, the read-side signal MCP enrichment
+ * folds into `exec` output.
+ *
+ * Same `{ counts }` shape as backlink-counts, with the two modes differing in
+ * density: `docNames` answers for exactly the docs asked about (0 included, so
+ * "no comments" is distinguishable from "not asked"), while `prefix` returns
+ * only the docs under it that carry threads — a folder with no comments
+ * anywhere yields `{}` rather than a row per file.
+ */
+export const CommentCountsSuccessSchema = z
+ .object({
+ counts: z.record(z.string().min(1), z.number().int().nonnegative()),
+ })
+ .loose() satisfies StandardSchemaV1;
+export type CommentCountsSuccess = z.infer<typeof CommentCountsSuccessSchema>;
+
/**
* Single forward-link entry returned by `/api/forward-links`. Discriminated
* by `kind`: `'doc'` carries `docName` + optional `anchor`; `'external'`
diff --git a/packages/core/src/schemas/api/index.ts b/packages/core/src/schemas/api/index.ts
index 0df13e4ca..9ef1d7e90 100644
--- a/packages/core/src/schemas/api/index.ts
+++ b/packages/core/src/schemas/api/index.ts
@@ -22,6 +22,7 @@
export * from './_envelope.ts';
export * from './agent-write.ts';
export * from './client-logs.ts';
+export * from './comments.ts';
export * from './document-read.ts';
export * from './embed-detect.ts';
export * from './history.ts';
diff --git a/packages/core/src/schemas/cc1.ts b/packages/core/src/schemas/cc1.ts
index 475f6bde4..62d584f09 100644
--- a/packages/core/src/schemas/cc1.ts
+++ b/packages/core/src/schemas/cc1.ts
@@ -104,6 +104,7 @@ export const DerivedViewChannelSchema = z.enum([
'sync-status',
'session-activity',
'tags',
+ 'comments',
'lint-config',
]);
export type DerivedViewChannel = z.infer<typeof DerivedViewChannelSchema>;
diff --git a/packages/server/src/api-extension.test-helper.ts b/packages/server/src/api-extension.test-helper.ts
index 1bb60c1dc..965dfd85a 100644
--- a/packages/server/src/api-extension.test-helper.ts
+++ b/packages/server/src/api-extension.test-helper.ts
@@ -16,7 +16,7 @@ interface LegacyIndexOptions {
}
type LegacySignalChannel = (
- channel: 'files' | 'backlinks' | 'graph' | 'tags' | 'lint-config',
+ channel: 'files' | 'backlinks' | 'graph' | 'tags' | 'lint-config' | 'comments',
) => void;
export function createDerivedDocumentIndexApiPortStub(
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index e9c03f67f..9cb90bcb9 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -59,6 +59,7 @@ import {
ClientLogsRequestSchema,
ClientLogsSuccessSchema,
CONFIG_DOC_NAME_OKIGNORE,
+ CommentCountsSuccessSchema,
CreateFolderRequestSchema,
CreateFolderSuccessSchema,
CreatePageRequestSchema,
@@ -124,6 +125,7 @@ import {
LintFixRequestSchema,
LintFixResultSchema,
type LintViolationWarning,
+ LOCAL_DIR,
LocalOpAuthCancelRequestSchema,
LocalOpAuthEmptySuccessSchema,
type LocalOpAuthHostRequest,
@@ -311,6 +313,10 @@ import { isAllowedApiOrigin } from './api-origin.ts';
import { collectReferencedAssets, toContentRelativePath } from './asset-references.ts';
import { assetContentTypeForPath } from './asset-serve-middleware.ts';
import { collabUrlFromRequestHeaders } from './collab-bootstrap-url.ts';
+import { createCommentApi } from './comments/comment-api.ts';
+import { CommentIndex } from './comments/comment-index.ts';
+import { CommentService } from './comments/comment-service.ts';
+import { CommentThreadStore } from './comments/thread-store.ts';
import { getLocalDir } from './config/paths.ts';
import { CONFIG_VALIDATION_REVERT_ORIGIN } from './config-edit-origin.ts';
import { DocInConflictError, isDocInConflict, respondDocInConflict } from './conflict-errors.ts';
@@ -2793,7 +2799,16 @@ export interface ApiExtensionOptions {
getDiskAckSVs?: () => Record<string, string>;
contentRoot?: string;
derivedDocumentIndex?: DerivedDocumentIndexApiPort;
- signalChannel?: (channel: 'files' | 'lint-config') => void;
+ // `comments` joins main's narrowed channel union: the comment views are
+ // derived from document text the same way files and lint-config are, and the
+ // panel refetches off this signal.
+ signalChannel?: (channel: 'files' | 'lint-config' | 'comments') => void;
+ /**
+ * Optional seam for the document-lifecycle hooks that comments care about.
+ * Both callers (the settle extension, the file watcher) are constructed
+ * before the comment service exists, so they read this at call time.
+ */
+ commentDocHooksRef?: { current: CommentDocHooks | null };
/**
* Optional. When present, agent write handlers publish per-write attribution
* entries on `__system__` awareness (`agentFocus` map) with writeKind +
@@ -3066,6 +3081,18 @@ function applyDiskEventToLiveAllFilesIndex(
}
}
+/**
+ * Document-lifecycle events comment threads have to follow. Both are fired from
+ * subsystems built before the comment service exists, so they arrive through a
+ * ref rather than a direct dependency.
+ */
+export interface CommentDocHooks {
+ /** The doc's content settled — re-anchor its threads. */
+ changed: (docName: string) => void;
+ /** The doc is gone — its threads go with it. */
+ deleted: (docName: string) => void;
+}
+
export function createApiExtension(options: ApiExtensionOptions): Extension {
const { durabilityState, remotePublicHost } = options;
// Every local-op call site in this factory inherits the remote-origin
@@ -3269,6 +3296,93 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
return filePath;
}
+ // Comments (v1) — anchored threads stored under
+ // `<contentDir>/.ok/local/comments/`, machine-local and never committed.
+ // App-only HTTP surface (agents reach comments through dispatch, not MCP).
+ // Constructed here rather than by the routes map so the rename walk below can
+ // call `commentService.renameDoc(...)`. The store's directory is created
+ // lazily on first write, so constructing without awaiting is safe.
+ const commentService = new CommentService({
+ store: new CommentThreadStore(resolve(contentDir, OK_DIR, LOCAL_DIR), log),
+ index: new CommentIndex(),
+ getDocBody: (docName) => {
+ // Prefer the live CRDT body; fall back to disk. Offsets are measured
+ // against the body text (everything after the frontmatter).
+ try {
+ const doc = hocuspocus.documents.get(docName);
+ if (doc) return stripFrontmatter(doc.getText('source').toString()).body;
+ } catch {
+ /* fall through to disk */
+ }
+ try {
+ const filePath = resolveDocPath(docName);
+ if (filePath && existsSync(filePath)) {
+ return stripFrontmatter(readFileSync(filePath, 'utf-8')).body;
+ }
+ } catch {
+ /* unreadable — treat as absent */
+ }
+ return null;
+ },
+ // Property threads address a frontmatter key — and optionally a path into
+ // its value, and optionally a passage inside that. All of it re-finds
+ // against the parsed record. Same live-CRDT-then-disk order as the body read
+ // above, and the same null contract: null means the document could not be
+ // read, which leaves thread state alone rather than orphaning it. A doc with
+ // no frontmatter at all is an empty record — readable, just empty.
+ getDocFrontmatter: (docName: string): Record<string, unknown> | null => {
+ try {
+ const doc = hocuspocus.documents.get(docName);
+ if (doc) return parseFrontmatterRecord(doc.getText('source').toString()) ?? {};
+ } catch {
+ /* fall through to disk */
+ }
+ try {
+ const filePath = resolveDocPath(docName);
+ if (filePath && existsSync(filePath)) {
+ return parseFrontmatterRecord(readFileSync(filePath, 'utf-8')) ?? {};
+ }
+ } catch {
+ /* unreadable — treat as absent */
+ }
+ return null;
+ },
+ });
+
+ // A doc's threads follow its lifecycle.
+ if (options.commentDocHooksRef) {
+ options.commentDocHooksRef.current = {
+ // Settling a change re-anchors them, so a deleted passage reads as
+ // orphaned instead of staying healthy-looking until someone tries to send
+ // it. Only a state change is broadcast — the sweep runs on every settle
+ // and is silent when nothing crossed.
+ changed: (docName: string) => {
+ void commentService
+ .refindDoc(docName)
+ .then((changed) => {
+ if (changed) signalChannel?.('comments');
+ })
+ .catch((err) => {
+ log.warn({ err, docName }, '[comments] re-anchor after document change failed');
+ });
+ },
+ // The document is gone, so its comments go with it. Every delete route
+ // reaches disk, so the watcher sees all of them and this one hook covers
+ // in-app deletes, the desktop trash flow, and a file removed outside the
+ // app alike.
+ deleted: (docName: string) => {
+ void commentService
+ .deleteDoc(docName)
+ .then((count) => {
+ if (count > 0) signalChannel?.('comments');
+ })
+ .catch((err) => {
+ log.warn({ err, docName }, '[comments] cleanup after document delete failed');
+ });
+ },
+ };
+ }
+
function readPageTitleForDocName(docName: string): string {
const filePath = resolveDocPath(docName);
if (!filePath || !existsSync(filePath)) return docName;
@@ -5029,6 +5143,21 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
newDocumentName: toDocName,
markdown: renamedSource.markdown,
});
+ // Comment threads follow the doc. Awaited, so the rename cannot
+ // report done while cover sheets are still being rewritten — an
+ // in-flight rewrite leaves a window where a racing read sees the
+ // old docName. Still non-fatal: the in-memory index is updated
+ // synchronously inside renameDoc and a failed cover-sheet write is
+ // rebuilt from disk at boot, so a failure here must not take the
+ // rename down with it.
+ try {
+ await commentService.renameDoc(fromDocName, toDocName);
+ } catch (err) {
+ log.warn(
+ { err, fromDocName, toDocName },
+ '[comments] cover-sheet rename failed; index updated, disk self-corrects at boot',
+ );
+ }
if (renamedSource.rewrites > 0) {
rewrittenDocs.push({ docName: toDocName, rewrites: renamedSource.rewrites });
}
@@ -7400,6 +7529,75 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
{ handler: 'backlink-counts', method: 'GET', skipBodyParse: true },
);
+ /**
+ * Bulk unresolved-comment-count lookup, the read-side counterpart to
+ * `/api/backlink-counts`. `GET /api/comment-counts?docNames=a,b,c` returns
+ * `{ counts: { a: 2, b: 0 } }`; `?prefix=folder` returns the same shape for
+ * every doc under that folder that carries threads (sparse — a comment-free
+ * subtree yields `{}`), which is how an `ls` entry gets a folder rollup
+ * without a request per file.
+ *
+ * Read-only, so it stays out of `MUTATING_ROUTES` — unlike `/api/comments`,
+ * whose POST creates threads. docNames failing `isSafeDocName` are silently
+ * dropped, matching backlink-counts; a malformed `prefix` is a 400 because
+ * dropping it would silently widen the query to the whole project.
+ */
+ const handleCommentCounts = withValidation(
+ EmptyRequestSchema,
+ async (req, res) => {
+ try {
+ const url = new URL(req.url ?? '', 'http://localhost');
+ const prefix = url.searchParams.get('prefix');
+ const raw = url.searchParams.get('docNames');
+ if (prefix === null && raw === null) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Missing docNames or prefix parameter.',
+ { handler: 'comment-counts' },
+ );
+ return;
+ }
+ let counts: Record<string, number> = {};
+ if (prefix !== null) {
+ const trimmed = prefix.trim();
+ if (trimmed !== '' && !isSafeDocName(trimmed)) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Invalid prefix parameter.', {
+ handler: 'comment-counts',
+ });
+ return;
+ }
+ counts = Object.fromEntries(await commentService.countThreads({ prefix: trimmed }));
+ } else {
+ const docNames = (raw ?? '')
+ .split(',')
+ .map((name) => name.trim())
+ .filter((name) => name !== '' && isSafeDocName(name));
+ counts = Object.fromEntries(await commentService.countThreads({ docNames }));
+ }
+ successResponse(
+ res,
+ 200,
+ CommentCountsSuccessSchema,
+ { counts },
+ {
+ handler: 'comment-counts',
+ },
+ );
+ } catch (e) {
+ errorResponse(
+ res,
+ 500,
+ 'urn:ok:error:internal-server-error',
+ 'Failed to read comment counts.',
+ { handler: 'comment-counts', cause: e },
+ );
+ }
+ },
+ { handler: 'comment-counts', method: 'GET', skipBodyParse: true },
+ );
+
const handleForwardLinks = withValidation(
EmptyRequestSchema,
async (req, res) => {
@@ -20591,14 +20789,36 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
},
);
+ // The comment store + service are constructed near `resolveDocPath` above so
+ // the rename walk can follow renames. Two dispatchers keep the surface to two
+ // paths; the mutating sub-handlers in `comment-api.ts` thread
+ // `extractActorIdentity` (same posture as the `handleSkill` / `handleTemplate`
+ // dispatchers in the attribution sweep).
+ const commentApi = createCommentApi({
+ service: commentService,
+ getPrincipal,
+ onChanged: () => signalChannel?.('comments'),
+ });
+ const handleCommentsRoute = methodRouter(
+ { GET: commentApi.list, POST: commentApi.create },
+ { handler: 'comments' },
+ );
+ const handleCommentRoute = methodRouter(
+ { GET: commentApi.read, POST: commentApi.mutate, DELETE: commentApi.remove },
+ { handler: 'comment' },
+ );
+
const routes: Record<string, (req: IncomingMessage, res: ServerResponse) => Promise<void>> = {
'/api/config': handleApiConfig,
+ '/api/comments': handleCommentsRoute,
+ '/api/comment': handleCommentRoute,
'/api/asset': handleAsset,
'/api/asset-text': handleAssetText,
'/api/document': handleDocumentRead,
'/api/documents': handleDocumentList,
'/api/backlinks': handleBacklinks,
'/api/backlink-counts': handleBacklinkCounts,
+ '/api/comment-counts': handleCommentCounts,
'/api/link-preview': handleLinkPreview,
'/api/forward-links': handleForwardLinks,
'/api/link-graph': handleLinkGraph,
@@ -20711,6 +20931,8 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
// UI can bootstrap against the collab server; mutations require a
// loopback Host header. /api/workspace enforces this inline already.
const MUTATING_ROUTES: ReadonlySet<string> = new Set([
+ '/api/comments',
+ '/api/comment',
'/api/upload',
'/api/lint/markdownlint-config',
'/api/lint/frontmatter-schema',
diff --git a/packages/server/src/comments/anchor.test.ts b/packages/server/src/comments/anchor.test.ts
new file mode 100644
index 000000000..587f99445
--- /dev/null
+++ b/packages/server/src/comments/anchor.test.ts
@@ -0,0 +1,193 @@
+import { describe, expect, test } from 'vitest';
+import { assertAnchorConsistent, createAnchor, refind } from './anchor.ts';
+
+describe('createAnchor', () => {
+ test('captures the exact quote and surrounding context', () => {
+ const body = 'The rollout is scheduled for Q3. We expect minimal downtime.';
+ const start = body.indexOf('minimal downtime');
+ const anchor = createAnchor(body, start, start + 'minimal downtime'.length);
+ expect(anchor.exact).toBe('minimal downtime');
+ expect(body.slice(anchor.start, anchor.end)).toBe('minimal downtime');
+ expect(anchor.prefix.endsWith('We expect ')).toBe(true);
+ expect(anchor.suffix.startsWith('.')).toBe(true);
+ });
+
+ test('honors the requested context length', () => {
+ const body = 'abcdefghij TARGET klmnopqrst';
+ const start = body.indexOf('TARGET');
+ const anchor = createAnchor(body, start, start + 'TARGET'.length, 4);
+ expect(anchor.exact).toBe('TARGET');
+ expect(anchor.prefix).toBe(body.slice(start - 4, start));
+ expect(anchor.suffix).toBe(body.slice(start + 6, start + 6 + 4));
+ expect(anchor.prefix.length).toBe(4);
+ expect(anchor.suffix.length).toBe(4);
+ });
+
+ test('widens context until a repeated quote is a unique triple', () => {
+ const body = 'alpha X beta. gamma X delta.';
+ // "X" appears twice; a 1-char context must widen to disambiguate.
+ const first = body.indexOf('X');
+ const anchor = createAnchor(body, first, first + 1, 1);
+ const triple = anchor.prefix + anchor.exact + anchor.suffix;
+ const occurrences = body.split(triple).length - 1;
+ expect(occurrences).toBe(1);
+ });
+
+ test('rejects an invalid range', () => {
+ const body = 'short';
+ expect(() => createAnchor(body, 3, 3)).toThrow();
+ expect(() => createAnchor(body, -1, 2)).toThrow();
+ expect(() => createAnchor(body, 2, 99)).toThrow();
+ });
+});
+
+describe('assertAnchorConsistent', () => {
+ test('passes when the quote matches the offsets', () => {
+ const body = 'hello world';
+ const anchor = createAnchor(body, 6, 11);
+ expect(() => assertAnchorConsistent(body, anchor)).not.toThrow();
+ });
+
+ test('throws when the client measured against a different body', () => {
+ const body = 'hello world';
+ const stale = { exact: 'world', prefix: '', suffix: '', start: 0, end: 5 };
+ expect(() => assertAnchorConsistent(body, stale)).toThrow(/write-time invariant/);
+ });
+});
+
+describe('refind', () => {
+ const body = 'The rollout is scheduled for Q3. We expect minimal downtime.';
+ const start = body.indexOf('minimal downtime');
+ const anchor = createAnchor(body, start, start + 'minimal downtime'.length);
+
+ test('fast path: unchanged body returns the same offsets', () => {
+ const res = refind(body, anchor);
+ expect(res).toEqual({ status: 'anchored', start, end: start + 'minimal downtime'.length });
+ });
+
+ test('re-finds after text is inserted above the anchor (position drifted)', () => {
+ const shifted = `Heads up: dates may slip. ${body}`;
+ const res = refind(shifted, anchor);
+ expect(res.status).toBe('anchored');
+ if (res.status === 'anchored') {
+ expect(shifted.slice(res.start, res.end)).toBe('minimal downtime');
+ // the raw saved offsets would have pointed at the wrong words
+ expect(res.start).not.toBe(anchor.start);
+ }
+ });
+
+ test('orphans when the quoted text is gone', () => {
+ const rewritten = 'The rollout is scheduled for Q3. Everything is fine now.';
+ expect(refind(rewritten, anchor).status).toBe('orphaned');
+ });
+
+ test('disambiguates a repeated quote by surrounding context', () => {
+ const dup = 'alpha TARGET omega ... beta TARGET zeta';
+ const first = dup.indexOf('TARGET');
+ const a = createAnchor(dup, first, first + 'TARGET'.length, 6);
+ // Insert text above so the fast path misses and quote-search runs.
+ const shifted = `PADDING PADDING ${dup}`;
+ const res = refind(shifted, a);
+ expect(res.status).toBe('anchored');
+ if (res.status === 'anchored') {
+ // should land on the FIRST occurrence (its context matches "alpha ")
+ expect(shifted.slice(res.start, res.end)).toBe('TARGET');
+ expect(shifted.slice(0, res.start).endsWith('alpha ')).toBe(true);
+ }
+ });
+
+ test('never lands on the wrong words: prefers nearest when context ties', () => {
+ // identical context around two hits → nearest-to-old-position wins
+ const line = 'x TARGET y x TARGET y';
+ const first = line.indexOf('TARGET');
+ const second = line.indexOf('TARGET', first + 1);
+ const a = createAnchor(line, second, second + 'TARGET'.length, 2);
+ const res = refind(line, a);
+ // fast path hits (unchanged body) → exact same offsets
+ expect(res).toEqual({ status: 'anchored', start: second, end: second + 'TARGET'.length });
+ });
+});
+
+describe('refind — a passage that was edited, not removed', () => {
+ // The reported behaviour: commenting on "needs space", then editing it to
+ // "needs more space", dropped the comment. Editing the text you commented on
+ // is the likeliest next action, so orphaning there was backwards.
+ const BODY = 'Intro line.\n\nThe layout needs space around the header.\n\nOutro line.';
+
+ function anchorOn(quote: string, body = BODY) {
+ const at = body.indexOf(quote);
+ return createAnchor(body, at, at + quote.length);
+ }
+
+ test('follows an insertion inside the passage', () => {
+ const anchor = anchorOn('needs space');
+ const edited = BODY.replace('needs space', 'needs more space');
+
+ const result = refind(edited, anchor);
+ expect(result.status).toBe('anchored');
+ if (result.status !== 'anchored') return;
+ expect(edited.slice(result.start, result.end)).toBe('needs more space');
+ // Flagged so the caller re-captures the quote; a stale `exact` would be
+ // handed to an agent as text to act on.
+ expect(result.rewritten).toBe(true);
+ });
+
+ test('follows a deletion inside the passage', () => {
+ const anchor = anchorOn('needs space around');
+ const edited = BODY.replace('needs space around', 'needs space near');
+
+ const result = refind(edited, anchor);
+ expect(result.status).toBe('anchored');
+ if (result.status !== 'anchored') return;
+ expect(edited.slice(result.start, result.end)).toBe('needs space near');
+ });
+
+ test('an unchanged passage still takes the exact path, unflagged', () => {
+ const result = refind(BODY, anchorOn('needs space'));
+ expect(result.status).toBe('anchored');
+ if (result.status !== 'anchored') return;
+ expect(result.rewritten).toBeUndefined();
+ });
+
+ test('a passage deleted outright still orphans', () => {
+ const anchor = anchorOn('needs space');
+ // Brackets collapse together — nothing between them is a removal, not an edit.
+ const edited = BODY.replace('needs space ', '');
+ const result = refind(edited, anchor);
+ expect(result.status).toBe('orphaned');
+ });
+
+ test('refuses to swallow a wholesale replacement between the brackets', () => {
+ const anchor = anchorOn('needs space');
+ const huge = 'x'.repeat(500);
+ const edited = BODY.replace('needs space', huge);
+ // The boundaries still match, but growing 11 chars to 500 is a replacement.
+ expect(refind(edited, anchor).status).toBe('orphaned');
+ });
+
+ test('orphans rather than guessing when the brackets are ambiguous', () => {
+ // Brackets that repeat cannot identify which span the reviewer meant, so
+ // the bracket path declines instead of picking one. Constructed directly:
+ // via `createAnchor` the context would widen until unique, which is exactly
+ // what keeps this case rare in practice.
+ const anchor = { exact: 'mid', prefix: 'X ', suffix: ' Y', start: 2, end: 5 };
+ const edited = 'X changed Y and later X other Y';
+
+ expect(refind(edited, anchor).status).toBe('orphaned');
+ });
+
+ test('a repeated quote edited in one place does not drag the comment elsewhere', () => {
+ // The exact text still exists at the other occurrences, so the pre-existing
+ // quote search handles it — the bracket path never runs. Pinned because the
+ // two paths must not fight: whatever it picks has to be real text.
+ const repeated = 'The layout needs space around the header.\n'.repeat(3);
+ const at = repeated.indexOf('needs space');
+ const anchor = createAnchor(repeated, at, at + 'needs space'.length);
+ const edited = repeated.replace('needs space', 'needs more space');
+
+ const result = refind(edited, anchor);
+ if (result.status === 'anchored') {
+ expect(edited.slice(result.start, result.end)).toBe('needs space');
+ }
+ });
+});
diff --git a/packages/server/src/comments/anchor.ts b/packages/server/src/comments/anchor.ts
new file mode 100644
index 000000000..7f5a0e9eb
--- /dev/null
+++ b/packages/server/src/comments/anchor.ts
@@ -0,0 +1,261 @@
+/**
+ * Content-addressed anchoring — "remember the words, not the position."
+ *
+ * The durable record is the exact quoted text plus widened context; the
+ * position is a fast-path hint only. Re-find runs an ordered fallback and
+ * fails SAFE (flags orphaned) rather than ever guessing a wrong location. No
+ * fuzzy matching: the quote is matched exactly; context only disambiguates
+ * between multiple exact hits.
+ */
+
+import type { Anchor } from './types.ts';
+
+/** Hypothesis uses 32 chars of context for web text; a reasonable markdown default. */
+const DEFAULT_CONTEXT_LEN = 32;
+
+/** A located passage as `[start, end)` — what both re-find and the create path score. */
+export interface Span {
+ start: number;
+ end: number;
+}
+
+export type RefindResult =
+ | {
+ status: 'anchored';
+ start: number;
+ end: number;
+ /**
+ * The quote itself changed — the range was recovered from its surrounding
+ * context, so the stored `exact` is stale and must be re-captured.
+ */
+ rewritten?: boolean;
+ }
+ | { status: 'orphaned' };
+
+/**
+ * How much the passage may grow when recovered from its brackets.
+ *
+ * Editing inside a commented passage is normal ("needs space" → "needs more
+ * space"); replacing whole paragraphs between the same two boundaries is not,
+ * and silently swallowing them would attach the comment to text nobody pointed
+ * at. Generous but finite: past this, treat it as a replacement and orphan.
+ */
+const MAX_REWRITE_GROWTH = 4;
+const REWRITE_GROWTH_FLOOR = 64;
+
+/**
+ * Build an anchor for the selection `[start, end)` against `body`. Captures the
+ * exact quote plus context on each side, widening the context until
+ * `prefix+exact+suffix` is a unique literal so re-find can disambiguate a
+ * repeated quote. Throws on an invalid range.
+ */
+export function createAnchor(
+ body: string,
+ start: number,
+ end: number,
+ contextLen: number = DEFAULT_CONTEXT_LEN,
+): Anchor {
+ if (
+ !Number.isInteger(start) ||
+ !Number.isInteger(end) ||
+ start < 0 ||
+ end > body.length ||
+ start >= end
+ ) {
+ throw new Error(`invalid selection range [${start}, ${end}) for body length ${body.length}`);
+ }
+ const exact = body.slice(start, end);
+ let prefix = body.slice(Math.max(0, start - contextLen), start);
+ let suffix = body.slice(end, Math.min(body.length, end + contextLen));
+
+ // Widen context only when the quote is ambiguous on its own. Grow the window
+ // (capped at whole-doc) until the triple is unique; if the surrounding text
+ // is genuinely identical, the position hint is the remaining tie-break.
+ if (countOccurrences(body, exact) > 1) {
+ let len = contextLen;
+ while (!isUniqueTriple(body, prefix, exact, suffix) && len < body.length) {
+ len = Math.min(len * 2, body.length);
+ prefix = body.slice(Math.max(0, start - len), start);
+ suffix = body.slice(end, Math.min(body.length, end + len));
+ }
+ }
+ return { exact, prefix, suffix, start, end };
+}
+
+/**
+ * Semiont "reconcile at write time": the stored quote must be exactly what sits
+ * at the offsets. Route handlers call this on a client-supplied anchor before
+ * persisting — a mismatch means the client measured against a different body.
+ */
+export function assertAnchorConsistent(body: string, anchor: Anchor): void {
+ if (body.slice(anchor.start, anchor.end) !== anchor.exact) {
+ throw new Error('anchor write-time invariant violated: quote does not match offsets');
+ }
+}
+
+/** Every literal occurrence of `needle`, as spans. */
+export function literalSpans(haystack: string, needle: string): Span[] {
+ return allOccurrences(haystack, needle).map((start) => ({ start, end: start + needle.length }));
+}
+
+/**
+ * Narrow candidate occurrences to the ones whose surroundings best match the
+ * context a caller captured. Returns EVERY candidate tied for the best score,
+ * so a caller with a further tie-break of its own can apply it — this never
+ * invents one, and with no context every candidate ties and the whole set comes
+ * back untouched.
+ *
+ * Scoring is a raw common-character run on each side, deliberately tolerant:
+ * the context may have been captured against RENDERED text while `body` is
+ * markdown, so an exact comparison would collapse to zero the moment a `**`
+ * falls inside the window. A partial run still ranks the right occurrence first,
+ * and every candidate is scored the same way.
+ */
+export function bestByContext<T extends Span>(
+ body: string,
+ hits: readonly T[],
+ context: { prefix?: string; suffix?: string },
+): T[] {
+ const prefix = context.prefix ?? '';
+ const suffix = context.suffix ?? '';
+ let best: T[] = [];
+ let bestScore = -1;
+ for (const hit of hits) {
+ const score =
+ commonSuffixLen(prefix, body.slice(0, hit.start)) +
+ commonPrefixLen(suffix, body.slice(hit.end));
+ if (score > bestScore) {
+ bestScore = score;
+ best = [hit];
+ } else if (score === bestScore) {
+ best.push(hit);
+ }
+ }
+ return best;
+}
+
+/**
+ * Locate the anchor in the current `body`. Ordered, stop at first hit:
+ * 1. fast path — the quote is still at the saved offsets;
+ * 2. quote search — find the quote; disambiguate multiple hits by context,
+ * then by nearest-to-old-position;
+ * 3. orphan — nothing matched, or still ambiguous. Never guesses.
+ */
+export function refind(body: string, anchor: Anchor): RefindResult {
+ const { exact, prefix, suffix, start } = anchor;
+ const end = start + exact.length;
+
+ // (1) fast path
+ if (end <= body.length && body.slice(start, end) === exact) {
+ return { status: 'anchored', start, end };
+ }
+
+ // (2) quote search
+ const hits = allOccurrences(body, exact);
+ if (hits.length === 0) return refindBetweenBrackets(body, anchor);
+ if (hits.length === 1) {
+ return { status: 'anchored', start: hits[0], end: hits[0] + exact.length };
+ }
+
+ // disambiguate by how much of the stored context still surrounds each hit
+ const best = bestByContext(
+ body,
+ hits.map((h) => ({ start: h, end: h + exact.length })),
+ { prefix, suffix },
+ );
+ if (best.length === 1) {
+ return { status: 'anchored', start: best[0].start, end: best[0].end };
+ }
+
+ // final tie-break: nearest to the old position
+ let nearest: Span[] = [];
+ let nearestDist = Number.POSITIVE_INFINITY;
+ for (const h of best) {
+ const d = Math.abs(h.start - start);
+ if (d < nearestDist) {
+ nearestDist = d;
+ nearest = [h];
+ } else if (d === nearestDist) {
+ nearest.push(h);
+ }
+ }
+ if (nearest.length === 1) {
+ return { status: 'anchored', start: nearest[0].start, end: nearest[0].end };
+ }
+ // genuinely ambiguous — flag, never guess
+ return { status: 'orphaned' };
+}
+
+/**
+ * Recover a passage whose text was EDITED rather than removed.
+ *
+ * The stored prefix/suffix were widened at creation until the triple was
+ * unique, so when both still occur exactly once and in order, whatever sits
+ * between them is the passage — whatever it now says. The boundaries stay an
+ * exact match; only the middle is allowed to have changed, which is what makes
+ * this different from fuzzy matching: it cannot land on an unrelated passage,
+ * because the surroundings have to be literally where they were.
+ *
+ * Ambiguity orphans rather than guesses, per the same rule the quote search
+ * follows: more than one candidate bracket means we do not know which one the
+ * reviewer meant.
+ */
+function refindBetweenBrackets(body: string, anchor: Anchor): RefindResult {
+ const { prefix, suffix, exact } = anchor;
+ // An empty side means the anchor sat at that end of the document; that
+ // boundary is the document edge and needs no match.
+ const starts = prefix === '' ? [0] : allOccurrences(body, prefix).map((i) => i + prefix.length);
+ const ends = suffix === '' ? [body.length] : allOccurrences(body, suffix);
+ if (starts.length !== 1 || ends.length !== 1) return { status: 'orphaned' };
+
+ const start = starts[0];
+ const end = ends[0];
+ if (end < start) return { status: 'orphaned' };
+ // A passage edited down to nothing is a removal, not an edit.
+ if (end === start) return { status: 'orphaned' };
+ const ceiling = Math.max(exact.length * MAX_REWRITE_GROWTH, exact.length + REWRITE_GROWTH_FLOOR);
+ if (end - start > ceiling) return { status: 'orphaned' };
+ return { status: 'anchored', start, end, rewritten: true };
+}
+
+function countOccurrences(haystack: string, needle: string): number {
+ if (needle === '') return 0;
+ let count = 0;
+ let i = haystack.indexOf(needle);
+ while (i !== -1) {
+ count += 1;
+ i = haystack.indexOf(needle, i + 1);
+ }
+ return count;
+}
+
+function allOccurrences(haystack: string, needle: string): number[] {
+ const out: number[] = [];
+ if (needle === '') return out;
+ let i = haystack.indexOf(needle);
+ while (i !== -1) {
+ out.push(i);
+ i = haystack.indexOf(needle, i + 1);
+ }
+ return out;
+}
+
+function isUniqueTriple(body: string, prefix: string, exact: string, suffix: string): boolean {
+ return countOccurrences(body, prefix + exact + suffix) === 1;
+}
+
+/** Length of the longest common prefix of `a` and `b`. */
+function commonPrefixLen(a: string, b: string): number {
+ const n = Math.min(a.length, b.length);
+ let i = 0;
+ while (i < n && a[i] === b[i]) i += 1;
+ return i;
+}
+
+/** Length of the longest common suffix of `a` and `b`. */
+function commonSuffixLen(a: string, b: string): number {
+ const n = Math.min(a.length, b.length);
+ let i = 0;
+ while (i < n && a[a.length - 1 - i] === b[b.length - 1 - i]) i += 1;
+ return i;
+}
diff --git a/packages/server/src/comments/comment-api.test.ts b/packages/server/src/comments/comment-api.test.ts
new file mode 100644
index 000000000..420b09fa7
--- /dev/null
+++ b/packages/server/src/comments/comment-api.test.ts
@@ -0,0 +1,388 @@
+import { randomUUID } from 'node:crypto';
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import type { IncomingMessage, ServerResponse } from 'node:http';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { Readable } from 'node:stream';
+import type { Principal } from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { getLogger } from '../logger.ts';
+import { createCommentApi } from './comment-api.ts';
+import { CommentIndex } from './comment-index.ts';
+import { CommentService } from './comment-service.ts';
+import { CommentThreadStore } from './thread-store.ts';
+
+const log = getLogger('comment-api-test');
+const ORIGINAL = 'The rollout is scheduled for Q3. We expect minimal downtime.';
+const PRINCIPAL = { id: 'principal-1', display_name: 'Dev', display_email: '[email protected]' } as Principal;
+
+let dirs: string[] = [];
+afterEach(() => {
+ for (const d of dirs) rmSync(d, { recursive: true, force: true });
+ dirs = [];
+});
+
+class MockRes {
+ statusCode = 0;
+ body = '';
+ headers: Record<string, string> = {};
+ headersSent = false;
+ writableEnded = false;
+ destroyed = false;
+ writeHead(status: number, headers: Record<string, string>): this {
+ this.statusCode = status;
+ this.headers = headers;
+ this.headersSent = true;
+ return this;
+ }
+ end(chunk?: unknown): this {
+ if (chunk) this.body += String(chunk);
+ this.writableEnded = true;
+ return this;
+ }
+ setHeader(): void {}
+ get json(): Record<string, unknown> {
+ return JSON.parse(this.body) as Record<string, unknown>;
+ }
+}
+
+function getReq(url: string): IncomingMessage {
+ return { url, method: 'GET', headers: {} } as unknown as IncomingMessage;
+}
+function postReq(url: string, body: unknown): IncomingMessage {
+ const r = Readable.from([Buffer.from(JSON.stringify(body))]) as unknown as IncomingMessage;
+ (r as unknown as { url: string }).url = url;
+ (r as unknown as { method: string }).method = 'POST';
+ (r as unknown as { headers: unknown }).headers = {};
+ return r;
+}
+
+let api: ReturnType<typeof createCommentApi>;
+let bodies: Map<string, string>;
+let changed: number;
+/** The store's parent — `comments/` lives under it, and so does `threads/`. */
+let localDir: string;
+
+beforeEach(async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'comment-api-test-'));
+ dirs.push(dir);
+ localDir = dir;
+ const store = new CommentThreadStore(dir, log);
+ await store.init();
+ bodies = new Map([['notes/rollout', ORIGINAL]]);
+ const service = new CommentService({
+ store,
+ index: new CommentIndex(),
+ getDocBody: (doc) => bodies.get(doc) ?? null,
+ });
+ changed = 0;
+ api = createCommentApi({
+ service,
+ getPrincipal: () => PRINCIPAL,
+ onChanged: () => {
+ changed += 1;
+ },
+ });
+});
+
+async function createThread(): Promise<string> {
+ const res = new MockRes();
+ const start = ORIGINAL.indexOf('minimal downtime');
+ await api.create(
+ postReq('/api/comments', {
+ docName: 'notes/rollout',
+ start,
+ end: start + 'minimal downtime'.length,
+ body: 'still accurate?',
+ }),
+ res as unknown as ServerResponse,
+ );
+ expect(res.statusCode).toBe(201);
+ return res.json.threadId as string;
+}
+
+describe('comment-api routes', () => {
+ test('POST /api/comments creates a thread attributed to the principal', async () => {
+ const id = await createThread();
+ expect(id).toBeTruthy();
+ });
+
+ test('GET /api/comments?doc lists a doc threads', async () => {
+ await createThread();
+ const res = new MockRes();
+ await api.list(getReq('/api/comments?doc=notes/rollout'), res as unknown as ServerResponse);
+ expect(res.statusCode).toBe(200);
+ expect((res.json.threads as unknown[]).length).toBe(1);
+ });
+
+ test('GET /api/comments without doc lists project-wide', async () => {
+ await createThread();
+ const res = new MockRes();
+ await api.list(getReq('/api/comments'), res as unknown as ServerResponse);
+ expect(res.statusCode).toBe(200);
+ expect((res.json.threads as unknown[]).length).toBe(1);
+ });
+
+ test('POST /api/comments with queue lands the thread in the queue', async () => {
+ const res = new MockRes();
+ const start = ORIGINAL.indexOf('minimal downtime');
+ await api.create(
+ postReq('/api/comments', {
+ docName: 'notes/rollout',
+ start,
+ end: start + 'minimal downtime'.length,
+ body: 'batch this one',
+ queue: true,
+ }),
+ res as unknown as ServerResponse,
+ );
+ expect(res.statusCode).toBe(201);
+ expect(res.json.queued).toBe(true);
+ });
+
+ test('GET /api/comment?id reads one thread', async () => {
+ const id = await createThread();
+ const res = new MockRes();
+ await api.read(getReq(`/api/comment?id=${id}`), res as unknown as ServerResponse);
+ expect(res.statusCode).toBe(200);
+ expect(res.json.threadId).toBe(id);
+ expect(res.json.latestComment).toBe('still accurate?');
+ });
+
+ test('GET /api/comment?id for a missing thread is a 404', async () => {
+ const res = new MockRes();
+ await api.read(getReq(`/api/comment?id=${randomUUID()}`), res as unknown as ServerResponse);
+ expect(res.statusCode).toBe(404);
+ });
+
+ test('POST /api/comment edit / resolve mutate the thread', async () => {
+ const id = await createThread();
+ const editRes = new MockRes();
+ await api.mutate(
+ postReq('/api/comment', { action: 'edit', id, body: 'revised ask' }),
+ editRes as unknown as ServerResponse,
+ );
+ expect(editRes.statusCode).toBe(200);
+
+ const resolveRes = new MockRes();
+ await api.mutate(
+ postReq('/api/comment', { action: 'resolve', id }),
+ resolveRes as unknown as ServerResponse,
+ );
+ expect(resolveRes.statusCode).toBe(200);
+ expect(resolveRes.json.state).toBe('resolved');
+ });
+
+ test('POST /api/comment queue returns queued + orphaned status', async () => {
+ const id = await createThread();
+ bodies.set('notes/rollout', 'nothing to see here'); // anchor will be lost
+ const res = new MockRes();
+ await api.mutate(
+ postReq('/api/comment', { action: 'queue', id }),
+ res as unknown as ServerResponse,
+ );
+ expect(res.statusCode).toBe(200);
+ expect(res.json.orphaned).toBe(true);
+ expect((res.json.meta as { queued: boolean }).queued).toBe(true);
+ });
+
+ test('POST /api/comments on a missing doc is a 404', async () => {
+ const res = new MockRes();
+ await api.create(
+ postReq('/api/comments', { docName: 'gone', start: 0, end: 1, body: 'x' }),
+ res as unknown as ServerResponse,
+ );
+ expect(res.statusCode).toBe(404);
+ });
+
+ test('mutations signal clients to refetch; reads do not', async () => {
+ const id = await createThread();
+ expect(changed).toBe(1); // create signalled
+
+ const listRes = new MockRes();
+ await api.list(getReq('/api/comments?doc=notes/rollout'), listRes as unknown as ServerResponse);
+ expect(changed).toBe(1); // a read must not signal
+
+ await api.mutate(
+ postReq('/api/comment', { action: 'resolve', id }),
+ new MockRes() as unknown as ServerResponse,
+ );
+ expect(changed).toBe(2);
+ });
+
+ test('a failed mutation does not signal', async () => {
+ const res = new MockRes();
+ await api.mutate(
+ postReq('/api/comment', { action: 'resolve', id: randomUUID() }),
+ res as unknown as ServerResponse,
+ );
+ expect(res.statusCode).toBe(404);
+ expect(changed).toBe(0);
+ });
+
+ test('dispatch-prepare returns the payload the client composes with', async () => {
+ const id = await createThread();
+ const res = new MockRes();
+ await api.mutate(
+ postReq('/api/comment', { action: 'dispatch-prepare', id }),
+ res as unknown as ServerResponse,
+ );
+ expect(res.statusCode).toBe(200);
+ const payload = res.json.payload as {
+ docName: string;
+ instruction: string;
+ passage: unknown;
+ anchorLost: boolean;
+ };
+ expect(payload.docName).toBe('notes/rollout');
+ expect(payload.instruction).toBe('still accurate?');
+ expect(payload.passage).toMatchObject({ exact: 'minimal downtime' });
+ expect(payload.anchorLost).toBe(false);
+ expect((res.json.meta as { queued: boolean }).queued).toBe(true);
+ });
+
+ test('dispatch-prepare still returns a payload when the anchor is lost', async () => {
+ const id = await createThread();
+ bodies.set('notes/rollout', 'nothing to see here');
+ const res = new MockRes();
+ await api.mutate(
+ postReq('/api/comment', { action: 'dispatch-prepare', id }),
+ res as unknown as ServerResponse,
+ );
+ expect(res.statusCode).toBe(200);
+ expect((res.json.payload as { anchorLost: boolean }).anchorLost).toBe(true);
+ expect((res.json.meta as { state: string }).state).toBe('orphaned');
+ });
+
+ test('dispatch-complete resolves the thread', async () => {
+ const id = await createThread();
+ await api.mutate(
+ postReq('/api/comment', { action: 'dispatch-prepare', id }),
+ new MockRes() as unknown as ServerResponse,
+ );
+ const res = new MockRes();
+ await api.mutate(
+ postReq('/api/comment', { action: 'dispatch-complete', id }),
+ res as unknown as ServerResponse,
+ );
+ expect(res.statusCode).toBe(200);
+ expect(res.json.state).toBe('resolved');
+ expect(res.json.queued).toBe(false);
+ });
+
+ test('batch prepare + complete dispatches the selected ids in order', async () => {
+ const first = await createThread();
+ const second = await createThread();
+
+ const prepRes = new MockRes();
+ await api.mutate(
+ postReq('/api/comment', { action: 'dispatch-prepare-batch', ids: [second, first] }),
+ prepRes as unknown as ServerResponse,
+ );
+ expect(prepRes.statusCode).toBe(200);
+ const prepared = prepRes.json.results as { threadId: string; ok: boolean }[];
+ expect(prepared.map((r) => r.threadId)).toEqual([second, first]);
+
+ const doneRes = new MockRes();
+ await api.mutate(
+ postReq('/api/comment', { action: 'dispatch-complete-batch', ids: [second, first] }),
+ doneRes as unknown as ServerResponse,
+ );
+ expect(doneRes.statusCode).toBe(200);
+ const done = doneRes.json.results as { ok: boolean; meta?: { state: string } }[];
+ expect(done.every((r) => r.ok && r.meta?.state === 'resolved')).toBe(true);
+ });
+
+ test('batch prepare reports a missing id without failing the batch', async () => {
+ const id = await createThread();
+ const res = new MockRes();
+ await api.mutate(
+ postReq('/api/comment', { action: 'dispatch-prepare-batch', ids: [id, randomUUID()] }),
+ res as unknown as ServerResponse,
+ );
+ expect(res.statusCode).toBe(200);
+ const results = res.json.results as { ok: boolean; error?: string }[];
+ expect(results[0].ok).toBe(true);
+ expect(results[1]).toMatchObject({ ok: false, error: 'not-found' });
+ });
+
+ test('an empty batch is a 400', async () => {
+ const res = new MockRes();
+ await api.mutate(
+ postReq('/api/comment', { action: 'dispatch-prepare-batch', ids: [] }),
+ res as unknown as ServerResponse,
+ );
+ expect(res.statusCode).toBe(400);
+ });
+
+ test('DELETE /api/comment removes the thread outright', async () => {
+ const id = await createThread();
+ const res = new MockRes();
+ await api.remove(getReq(`/api/comment?id=${id}`), res as unknown as ServerResponse);
+ expect(res.statusCode).toBe(200);
+ expect(res.json.threadId).toBe(id);
+
+ // really gone — not merely unqueued or resolved
+ const readRes = new MockRes();
+ await api.read(getReq(`/api/comment?id=${id}`), readRes as unknown as ServerResponse);
+ expect(readRes.statusCode).toBe(404);
+
+ const listRes = new MockRes();
+ await api.list(getReq('/api/comments?doc=notes/rollout'), listRes as unknown as ServerResponse);
+ expect(listRes.json.threads).toEqual([]);
+ });
+
+ test('DELETE /api/comment refuses an id that walks out of the comments dir', async () => {
+ // The ACP thread store is `comments/`'s sibling and names its files with the
+ // same two extensions, so a traversing id lands on real agent transcripts.
+ const victimId = randomUUID();
+ mkdirSync(join(localDir, 'threads'), { recursive: true });
+ const transcript = join(localDir, 'threads', `${victimId}.ndjson`);
+ const meta = join(localDir, 'threads', `${victimId}.meta.json`);
+ writeFileSync(transcript, '{"kind":"user_message"}\n');
+ writeFileSync(meta, '{}');
+
+ const res = new MockRes();
+ await api.remove(
+ getReq(`/api/comment?id=${encodeURIComponent(`../threads/${victimId}`)}`),
+ res as unknown as ServerResponse,
+ );
+
+ expect(res.statusCode).toBe(400);
+ expect(existsSync(transcript)).toBe(true);
+ expect(existsSync(meta)).toBe(true);
+ });
+
+ test('GET /api/comment refuses an id that walks out of the comments dir', async () => {
+ const res = new MockRes();
+ await api.read(
+ getReq(`/api/comment?id=${encodeURIComponent('../threads/whatever')}`),
+ res as unknown as ServerResponse,
+ );
+ expect(res.statusCode).toBe(400);
+ });
+
+ test('POST /api/comment refuses a mutate id that is not a thread UUID', async () => {
+ const res = new MockRes();
+ await api.mutate(
+ postReq('/api/comment', { action: 'resolve', id: '../threads/whatever' }),
+ res as unknown as ServerResponse,
+ );
+ expect(res.statusCode).toBe(400);
+ });
+
+ test('DELETE /api/comment without an id is a 400', async () => {
+ const res = new MockRes();
+ await api.remove(getReq('/api/comment'), res as unknown as ServerResponse);
+ expect(res.statusCode).toBe(400);
+ });
+
+ test('POST /api/comment with an invalid action is a 400', async () => {
+ const res = new MockRes();
+ await api.mutate(
+ postReq('/api/comment', { action: 'explode', id: 'x' }),
+ res as unknown as ServerResponse,
+ );
+ expect(res.statusCode).toBe(400);
+ });
+});
diff --git a/packages/server/src/comments/comment-api.ts b/packages/server/src/comments/comment-api.ts
new file mode 100644
index 000000000..9b43e0c75
--- /dev/null
+++ b/packages/server/src/comments/comment-api.ts
@@ -0,0 +1,412 @@
+/**
+ * HTTP route module for comments — the app's door to the comment store
+ * (agents reach comments through the dispatch payload, not this API; there is
+ * no comments MCP surface in v1). Thin adapters over {@link CommentService}:
+ * parse + validate the request, thread identity for attribution, call the
+ * service, emit an RFC 9457 / schema-validated response.
+ *
+ * Wired into `api-extension.ts` as two `methodRouter` dispatchers:
+ * GET /api/comments[?doc=<docName>] list threads — one doc, or project-wide
+ * POST /api/comments create a thread { docName, start, end, body, queue? }
+ * GET /api/comment?id=<threadId> read one thread
+ * POST /api/comment mutate { action, ... }
+ * DELETE /api/comment?id=<threadId> delete a thread outright (destructive)
+ *
+ * Mutations multiplex on `action` so the route surface stays two paths:
+ * `edit` | `resolve` | `reopen` | `replace` | `queue` | `unqueue`, plus the
+ * dispatch pair `dispatch-prepare` / `dispatch-complete` and their batch forms
+ * `dispatch-prepare-batch` / `dispatch-complete-batch` (an ordered `ids` array
+ * — the reviewer's selection). Identity is threaded per mutation via
+ * `extractActorIdentity` (the mutating sub-handlers below), the same boundary
+ * rename/rollback use.
+ */
+
+import type { IncomingMessage, ServerResponse } from 'node:http';
+import type { Principal } from '@inkeep/open-knowledge-core';
+// The wire schemas live in core, shared with the app so neither side restates
+// the other's shape. Only `CommentThreadMetaSchema` doubles as the on-disk
+// shape; the envelopes below are wire-only.
+import {
+ CompleteBatchSuccessSchema,
+ DeleteSuccessSchema,
+ PrepareBatchSuccessSchema,
+ PrepareDispatchSuccessSchema,
+ QueueSuccessSchema,
+ ThreadListSuccessSchema,
+} from '@inkeep/open-knowledge-core';
+import { z } from 'zod';
+import { extractActorIdentity } from '../extract-actor-identity.ts';
+import { errorResponse } from '../http/error-response.ts';
+import { readBoundedJsonBody } from '../http/request-validation.ts';
+import { successResponse } from '../http/success-response.ts';
+import {
+ type CommentService,
+ DocNotFoundError,
+ PassageNotFoundError,
+ PropertyNotFoundError,
+ ThreadNotFoundError,
+} from './comment-service.ts';
+import { CommentThreadMetaSchema } from './types.ts';
+
+export interface CommentApiDeps {
+ service: CommentService;
+ getPrincipal: (() => Principal | null) | undefined;
+ /**
+ * Fired after any successful mutation so connected clients refetch (the CC1
+ * `comments` derived-view channel). Optional — omit in tests.
+ */
+ onChanged?: () => void;
+}
+
+export interface CommentApi {
+ list: (req: IncomingMessage, res: ServerResponse) => Promise<void>;
+ read: (req: IncomingMessage, res: ServerResponse) => Promise<void>;
+ create: (req: IncomingMessage, res: ServerResponse) => Promise<void>;
+ mutate: (req: IncomingMessage, res: ServerResponse) => Promise<void>;
+ remove: (req: IncomingMessage, res: ServerResponse) => Promise<void>;
+}
+
+const HANDLER = 'comments';
+/** Tight body budget — comment payloads are small; matches loopback-only handlers. */
+const BODY_LIMITS = { maxBytes: 64 * 1024, timeoutMs: 10_000 } as const;
+/** Cap on one dispatch batch. Well above any realistic review pass; bounds the work per request. */
+const BATCH_MAX = 200;
+
+/**
+ * Where the passage is: body offsets, or the quoted text for callers whose
+ * coordinate system isn't body offsets (the rich-text editor has ProseMirror
+ * positions, which markdown syntax + frontmatter make non-equivalent).
+ */
+const PassageRefSchema = {
+ start: z.number().int().nonnegative().optional(),
+ end: z.number().int().nonnegative().optional(),
+ quote: z.string().min(1).optional(),
+ /**
+ * Rendered text either side of the caller's selection — how a repeated quote
+ * says which occurrence it meant. Bounded: it only has to out-score the other
+ * candidates, not reproduce the document.
+ */
+ prefix: z.string().max(1000).optional(),
+ suffix: z.string().max(1000).optional(),
+} as const;
+
+const CreateRequestSchema = z.object({
+ docName: z.string().min(1),
+ ...PassageRefSchema,
+ /**
+ * Comment on a frontmatter key instead of a body passage. The passage fields
+ * above then apply to that VALUE rather than the body: send a `quote` to
+ * comment on a passage inside it, or omit one to comment on the whole thing.
+ */
+ propertyKey: z.string().min(1).optional(),
+ /** Steps into the key's value — `[2]` for the third tag, `["name"]` for a field. */
+ propertyPath: z.array(z.union([z.string(), z.number().int().nonnegative()])).optional(),
+ body: z.string(),
+ /** Post straight into the dispatch queue (queue-first compose flow). */
+ queue: z.boolean().optional(),
+ summary: z.string().optional(),
+});
+
+/**
+ * A thread id is a server-minted UUID, and the store joins it into a path. An
+ * id is therefore never caller data in the ordinary sense: `../threads/<id>`
+ * escapes the comments directory, and the ACP thread store one level over names
+ * its files with the very same `.meta.json` / `.ndjson` pair — so an unvalidated
+ * id on the delete route reaches real agent transcripts. Constraining the shape
+ * here is what keeps every id a leaf name; nothing downstream re-checks.
+ */
+const ThreadIdSchema = z.uuid();
+
+const MutateRequestSchema = z.discriminatedUnion('action', [
+ z.object({
+ action: z.literal('edit'),
+ id: ThreadIdSchema,
+ body: z.string(),
+ summary: z.string().optional(),
+ }),
+ z.object({ action: z.literal('resolve'), id: ThreadIdSchema, summary: z.string().optional() }),
+ z.object({ action: z.literal('reopen'), id: ThreadIdSchema, summary: z.string().optional() }),
+ z.object({
+ action: z.literal('replace'),
+ id: ThreadIdSchema,
+ ...PassageRefSchema,
+ summary: z.string().optional(),
+ }),
+ z.object({ action: z.literal('queue'), id: ThreadIdSchema, summary: z.string().optional() }),
+ z.object({ action: z.literal('unqueue'), id: ThreadIdSchema, summary: z.string().optional() }),
+ z.object({
+ action: z.literal('dispatch-prepare'),
+ id: ThreadIdSchema,
+ summary: z.string().optional(),
+ }),
+ z.object({
+ action: z.literal('dispatch-complete'),
+ id: ThreadIdSchema,
+ summary: z.string().optional(),
+ }),
+ // Batch forms. `ids` is the selected set in intended run order; the
+ // client drives select/deselect and sends only what stays checked.
+ z.object({
+ action: z.literal('dispatch-prepare-batch'),
+ ids: z.array(ThreadIdSchema).min(1).max(BATCH_MAX),
+ summary: z.string().optional(),
+ }),
+ z.object({
+ action: z.literal('dispatch-complete-batch'),
+ ids: z.array(ThreadIdSchema).min(1).max(BATCH_MAX),
+ summary: z.string().optional(),
+ }),
+]);
+
+export function createCommentApi(deps: CommentApiDeps): CommentApi {
+ const { service, getPrincipal, onChanged } = deps;
+
+ async function list(req: IncomingMessage, res: ServerResponse): Promise<void> {
+ // `doc` absent = the project-wide view (the queue panel spans docs you do
+ // not have open).
+ const docName = new URL(req.url ?? '', 'http://localhost').searchParams.get('doc') ?? undefined;
+ try {
+ const threads = await service.listThreads(docName);
+ successResponse(res, 200, ThreadListSuccessSchema, { threads }, { handler: HANDLER });
+ } catch (e) {
+ internalError(res, e, 'Failed to list comment threads.');
+ }
+ }
+
+ /**
+ * The `?id=` of a single-thread route, or null once a 400 has been sent.
+ * Shared by `read` and `remove` so the two can't drift — `remove` is the
+ * destructive one, and a validated id there is what keeps the store's
+ * `join` on a leaf name (see {@link ThreadIdSchema}).
+ */
+ function threadIdParam(req: IncomingMessage, res: ServerResponse): string | null {
+ const id = new URL(req.url ?? '', 'http://localhost').searchParams.get('id');
+ if (!id) {
+ badRequest(res, 'id query parameter is required.');
+ return null;
+ }
+ if (!ThreadIdSchema.safeParse(id).success) {
+ badRequest(res, 'id must be a comment thread UUID.');
+ return null;
+ }
+ return id;
+ }
+
+ async function read(req: IncomingMessage, res: ServerResponse): Promise<void> {
+ const id = threadIdParam(req, res);
+ if (id === null) return;
+ try {
+ const thread = await service.readThread(id);
+ successResponse(res, 200, CommentThreadMetaSchema, thread, { handler: HANDLER });
+ } catch (e) {
+ if (e instanceof ThreadNotFoundError) return notFound(res, 'Comment thread not found.');
+ internalError(res, e, 'Failed to read comment thread.');
+ }
+ }
+
+ async function create(req: IncomingMessage, res: ServerResponse): Promise<void> {
+ const parsed = await parseBody(req, res, CreateRequestSchema);
+ if (!parsed) return;
+ const actor = extractActorIdentity(parsed as unknown as Record<string, unknown>, getPrincipal);
+ if (actor.kind === 'invalid-summary') return badRequest(res, 'Summary must be a string.');
+ const author = authorFromActor(actor);
+ if (!author) return badRequest(res, 'A principal or agent identity is required to comment.');
+ try {
+ const meta = await service.createThread({
+ docName: parsed.docName,
+ start: parsed.start,
+ end: parsed.end,
+ quote: parsed.quote,
+ prefix: parsed.prefix,
+ suffix: parsed.suffix,
+ propertyKey: parsed.propertyKey,
+ propertyPath: parsed.propertyPath,
+ author,
+ body: parsed.body,
+ queue: parsed.queue,
+ });
+ onChanged?.();
+ successResponse(res, 201, CommentThreadMetaSchema, meta, { handler: HANDLER });
+ } catch (e) {
+ if (e instanceof DocNotFoundError) return notFound(res, 'Document not found.');
+ if (e instanceof PassageNotFoundError) {
+ return badRequest(res, 'The quoted passage is not in the document.');
+ }
+ if (e instanceof PropertyNotFoundError) {
+ return badRequest(res, `That property is not in the document: ${e.message}`);
+ }
+ if (
+ e instanceof RangeError ||
+ (e instanceof Error && /invalid selection|is required/.test(e.message))
+ ) {
+ return badRequest(res, 'Selection range is invalid for the document.');
+ }
+ internalError(res, e, 'Failed to create comment thread.');
+ }
+ }
+
+ async function mutate(req: IncomingMessage, res: ServerResponse): Promise<void> {
+ const parsed = await parseBody(req, res, MutateRequestSchema);
+ if (!parsed) return;
+ const actor = extractActorIdentity(parsed as unknown as Record<string, unknown>, getPrincipal);
+ if (actor.kind === 'invalid-summary') return badRequest(res, 'Summary must be a string.');
+ try {
+ switch (parsed.action) {
+ case 'edit': {
+ // Identity gate, not attribution: the service records no author for an
+ // edit (the event log that did was dropped). Kept because a mutation
+ // arriving from nobody is worth refusing on its own.
+ if (!authorFromActor(actor)) {
+ return badRequest(res, 'An identity is required to edit a comment.');
+ }
+ const meta = await service.editComment(parsed.id, parsed.body);
+ return ok(res, meta);
+ }
+ case 'resolve':
+ return ok(res, await service.resolve(parsed.id));
+ case 'reopen':
+ return ok(res, await service.reopen(parsed.id));
+ case 'replace':
+ return ok(
+ res,
+ await service.replaceAnchor(parsed.id, {
+ start: parsed.start,
+ end: parsed.end,
+ quote: parsed.quote,
+ prefix: parsed.prefix,
+ suffix: parsed.suffix,
+ }),
+ );
+ case 'queue': {
+ const result = await service.queueForDispatch(parsed.id);
+ onChanged?.();
+ return successResponse(res, 200, QueueSuccessSchema, result, { handler: HANDLER });
+ }
+ case 'unqueue':
+ return ok(res, await service.unqueue(parsed.id));
+ case 'dispatch-prepare': {
+ const result = await service.prepareDispatch(parsed.id);
+ onChanged?.();
+ return successResponse(res, 200, PrepareDispatchSuccessSchema, result, {
+ handler: HANDLER,
+ });
+ }
+ case 'dispatch-complete':
+ return ok(res, await service.completeDispatch(parsed.id));
+ case 'dispatch-prepare-batch': {
+ const results = await service.prepareDispatchBatch(parsed.ids);
+ onChanged?.();
+ return successResponse(
+ res,
+ 200,
+ PrepareBatchSuccessSchema,
+ { results },
+ {
+ handler: HANDLER,
+ },
+ );
+ }
+ case 'dispatch-complete-batch': {
+ const results = await service.completeDispatchBatch(parsed.ids);
+ onChanged?.();
+ return successResponse(
+ res,
+ 200,
+ CompleteBatchSuccessSchema,
+ { results },
+ {
+ handler: HANDLER,
+ },
+ );
+ }
+ }
+ } catch (e) {
+ if (e instanceof ThreadNotFoundError) return notFound(res, 'Comment thread not found.');
+ if (e instanceof DocNotFoundError) return notFound(res, 'Document not found.');
+ if (e instanceof PassageNotFoundError) {
+ return badRequest(res, 'The quoted passage is not in the document.');
+ }
+ if (e instanceof PropertyNotFoundError) {
+ return badRequest(res, `That property is not in the document: ${e.message}`);
+ }
+ if (e instanceof Error && /invalid selection|is required/.test(e.message)) {
+ return badRequest(res, 'Selection range is invalid for the document.');
+ }
+ internalError(res, e, 'Failed to update comment thread.');
+ }
+ }
+
+ /** Emit a mutation result + signal connected clients to refetch. */
+ /**
+ * DELETE a thread outright — the one destructive operation on this surface.
+ *
+ * Distinct from `unqueue` (drop from the batch, keep the comment) and from
+ * `resolve` (close it, keep the history). Deliberately a separate HTTP verb
+ * rather than another `action`, so it can never be reached by a body typo on
+ * a mutate call. Both files are removed; the conversation does not survive.
+ */
+ async function remove(req: IncomingMessage, res: ServerResponse): Promise<void> {
+ const id = threadIdParam(req, res);
+ if (id === null) return;
+ try {
+ await service.delete(id);
+ onChanged?.();
+ successResponse(res, 200, DeleteSuccessSchema, { threadId: id }, { handler: HANDLER });
+ } catch (e) {
+ internalError(res, e, 'Failed to delete comment thread.');
+ }
+ }
+
+ function ok(res: ServerResponse, meta: unknown): void {
+ onChanged?.();
+ successResponse(res, 200, CommentThreadMetaSchema, meta, { handler: HANDLER });
+ }
+
+ return { list, read, create, mutate, remove };
+}
+
+/** Read + Zod-validate a JSON body; emits a 400 and returns null on failure. */
+async function parseBody<T extends z.ZodType>(
+ req: IncomingMessage,
+ res: ServerResponse,
+ schema: T,
+): Promise<z.infer<T> | null> {
+ let raw: Buffer;
+ try {
+ raw = await readBoundedJsonBody(req, BODY_LIMITS);
+ } catch {
+ badRequest(res, 'Request body could not be read.');
+ return null;
+ }
+ let json: unknown;
+ try {
+ json = JSON.parse(raw.toString('utf8') || '{}');
+ } catch {
+ badRequest(res, 'Request body must be valid JSON.');
+ return null;
+ }
+ const result = schema.safeParse(json);
+ if (!result.success) {
+ badRequest(res, 'Request body is invalid.');
+ return null;
+ }
+ return result.data;
+}
+
+function authorFromActor(actor: ReturnType<typeof extractActorIdentity>): string | null {
+ if (actor.kind === 'agent' || actor.kind === 'principal') return actor.writerId;
+ return null;
+}
+
+function badRequest(res: ServerResponse, message: string): void {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', message, { handler: HANDLER });
+}
+function notFound(res: ServerResponse, message: string): void {
+ errorResponse(res, 404, 'urn:ok:error:not-found', message, { handler: HANDLER });
+}
+function internalError(res: ServerResponse, cause: unknown, message: string): void {
+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', message, {
+ handler: HANDLER,
+ cause,
+ });
+}
diff --git a/packages/server/src/comments/comment-index.test.ts b/packages/server/src/comments/comment-index.test.ts
new file mode 100644
index 000000000..086688e4c
--- /dev/null
+++ b/packages/server/src/comments/comment-index.test.ts
@@ -0,0 +1,212 @@
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
+import { getLogger } from '../logger.ts';
+import { createAnchor } from './anchor.ts';
+import { CommentIndex } from './comment-index.ts';
+import { CommentThreadStore } from './thread-store.ts';
+import type { CommentThreadMeta } from './types.ts';
+
+const log = getLogger('comments-index-test');
+
+let dirs: string[] = [];
+function tmp(): string {
+ const d = mkdtempSync(join(tmpdir(), 'comments-index-test-'));
+ dirs.push(d);
+ return d;
+}
+afterEach(() => {
+ for (const d of dirs) rmSync(d, { recursive: true, force: true });
+ dirs = [];
+});
+
+const BODY = 'one two three four five';
+const anchor = (q: string) => {
+ const s = BODY.indexOf(q);
+ return createAnchor(BODY, s, s + q.length);
+};
+
+/** A whole thread, since the index caches threads rather than doc pointers. */
+function thread(threadId: string, docName: string, quote = 'one'): CommentThreadMeta {
+ return {
+ threadId,
+ docName,
+ anchor: anchor(quote),
+ state: 'anchored',
+ queued: false,
+ latestComment: `note on ${threadId}`,
+ createdBy: 'principal-x',
+ createdAt: 1,
+ };
+}
+
+describe('CommentIndex', () => {
+ test('builds from disk at boot', async () => {
+ const store = new CommentThreadStore(tmp(), log);
+ await store.init();
+ for (const [id, doc, quote] of [
+ ['t1', 'a', 'one'],
+ ['t2', 'a', 'two'],
+ ['t3', 'b', 'three'],
+ ] as const) {
+ await store.createThread({
+ threadId: id,
+ docName: doc,
+ anchor: anchor(quote),
+ createdBy: 'principal-x',
+ createdAt: 1,
+ body: 'a note',
+ });
+ await store.whenIdle(id);
+ }
+
+ const index = new CommentIndex();
+ await index.build(store);
+
+ expect(index.size).toBe(3);
+ expect(index.threadsForDoc('a').sort()).toEqual(['t1', 't2']);
+ expect(index.threadsForDoc('b')).toEqual(['t3']);
+ expect(index.threadsForDoc('missing')).toEqual([]);
+ // The whole thread is cached, not just its doc — that's what lets listing
+ // serve reads without going back to disk.
+ expect(index.listForDoc('b')[0].latestComment).toBe('a note');
+ });
+
+ test('listAll returns every cached thread', () => {
+ const index = new CommentIndex();
+ index.upsert(thread('t1', 'a'));
+ index.upsert(thread('t2', 'b'));
+ expect(
+ index
+ .listAll()
+ .map((m) => m.threadId)
+ .sort(),
+ ).toEqual(['t1', 't2']);
+ });
+
+ test('upsert replaces the cached thread, not just its doc', () => {
+ // The index is read INSTEAD of the file, so an upsert that kept a stale
+ // copy would serve the pre-mutation state forever.
+ const index = new CommentIndex();
+ index.upsert(thread('t1', 'a'));
+ index.upsert({ ...thread('t1', 'a'), state: 'resolved', latestComment: 'revised' });
+
+ const [meta] = index.listForDoc('a');
+ expect(meta.state).toBe('resolved');
+ expect(meta.latestComment).toBe('revised');
+ });
+
+ test('upsert moves a thread to a new doc', () => {
+ const index = new CommentIndex();
+ index.upsert(thread('t1', 'a'));
+ index.upsert(thread('t1', 'b'));
+ expect(index.listForDoc('a')).toEqual([]);
+ expect(index.threadsForDoc('b')).toEqual(['t1']);
+ });
+
+ test('remove drops a thread and prunes an empty doc key', () => {
+ const index = new CommentIndex();
+ index.upsert(thread('t1', 'a'));
+ index.remove('t1');
+ expect(index.threadsForDoc('a')).toEqual([]);
+ expect(index.listAll()).toEqual([]);
+ expect(index.size).toBe(0);
+ });
+
+ test('renameDoc re-points every thread and rewrites its cached docName', () => {
+ // Both halves matter: the lookup key AND the cached copy. Leaving the copy
+ // behind would serve the old docName to the app after a rename.
+ const index = new CommentIndex();
+ index.upsert(thread('t1', 'old'));
+ index.upsert(thread('t2', 'old'));
+ index.renameDoc('old', 'new');
+
+ expect(index.threadsForDoc('old')).toEqual([]);
+ expect(index.threadsForDoc('new').sort()).toEqual(['t1', 't2']);
+ expect(index.listAll().every((m) => m.docName === 'new')).toBe(true);
+ });
+
+ test('renameDoc merges into an existing destination doc', () => {
+ const index = new CommentIndex();
+ index.upsert(thread('t1', 'old'));
+ index.upsert(thread('t2', 'new'));
+ index.renameDoc('old', 'new');
+ expect(index.threadsForDoc('new').sort()).toEqual(['t1', 't2']);
+ });
+});
+
+/**
+ * Counting is the read-side surface: it feeds the comment signal MCP `exec`
+ * folds into every file and folder it reports, so what it counts decides what
+ * an agent believes about a doc it is about to edit.
+ */
+describe('CommentIndex counting', () => {
+ test('counts every requested doc, zero included', () => {
+ // A requested doc with no threads must come back as 0 rather than absent —
+ // the caller has to tell "clean" from "not asked about".
+ const index = new CommentIndex();
+ index.upsert(thread('t1', 'a'));
+ index.upsert(thread('t2', 'a'));
+
+ expect([...index.countsForDocs(['a', 'b'])]).toEqual([
+ ['a', 2],
+ ['b', 0],
+ ]);
+ });
+
+ test('resolved threads do not count', () => {
+ // Settled work must not leave a doc looking permanently outstanding to
+ // every agent that reads it.
+ const index = new CommentIndex();
+ index.upsert(thread('t1', 'a'));
+ index.upsert({ ...thread('t2', 'a'), state: 'resolved' });
+
+ expect(index.countForDoc('a')).toBe(1);
+ expect(index.countsForDocs(['a']).get('a')).toBe(1);
+ });
+
+ test('orphaned threads still count', () => {
+ // The passage moved, but the request stands — an orphan is exactly the case
+ // a reader most needs to know about before editing.
+ const index = new CommentIndex();
+ index.upsert({ ...thread('t1', 'a'), state: 'orphaned' });
+ expect(index.countForDoc('a')).toBe(1);
+ });
+
+ test('prefix rollup is sparse and segment-bounded', () => {
+ // `docs` must not swallow `docsite/*`: the rollup annotates a FOLDER, and a
+ // sibling folder sharing a name prefix is a different folder.
+ const index = new CommentIndex();
+ index.upsert(thread('t1', 'docs/a'));
+ index.upsert(thread('t2', 'docs/nested/b'));
+ index.upsert(thread('t3', 'docsite/c'));
+ index.upsert({ ...thread('t4', 'docs/resolved-only'), state: 'resolved' });
+
+ const counts = index.countsUnderPrefix('docs');
+ expect([...counts].sort()).toEqual([
+ ['docs/a', 1],
+ ['docs/nested/b', 1],
+ ]);
+ // Sparse: a doc whose only thread is resolved is absent, not 0 — the folder
+ // line is drawn from the presence of entries.
+ expect(counts.has('docs/resolved-only')).toBe(false);
+ expect(counts.has('docsite/c')).toBe(false);
+ });
+
+ test('a trailing slash on the prefix means the same folder', () => {
+ const index = new CommentIndex();
+ index.upsert(thread('t1', 'docs/a'));
+ expect([...index.countsUnderPrefix('docs/')]).toEqual([['docs/a', 1]]);
+ });
+
+ test('an empty prefix rolls up the whole project', () => {
+ const index = new CommentIndex();
+ index.upsert(thread('t1', 'docs/a'));
+ index.upsert(thread('t2', 'top'));
+ expect([...index.countsUnderPrefix('')].sort()).toEqual([
+ ['docs/a', 1],
+ ['top', 1],
+ ]);
+ });
+});
diff --git a/packages/server/src/comments/comment-index.ts b/packages/server/src/comments/comment-index.ts
new file mode 100644
index 000000000..65317a8bd
--- /dev/null
+++ b/packages/server/src/comments/comment-index.ts
@@ -0,0 +1,154 @@
+/**
+ * In-memory thread index, the `backlink-index.ts` pattern: scan every thread
+ * once at boot, hold the result in memory, and update it incrementally on
+ * writes rather than re-reading per query.
+ *
+ * It holds the threads themselves, not just a doc pointer, so listing them
+ * touches no disk at all. The list is the hot path — the app refetches the
+ * whole project on every mutation and every push notification — and reading one
+ * small file per thread made a single click cost O(every comment ever written).
+ *
+ * Nothing persists between boots. Like the backlink index, it is rebuilt from
+ * the files every time, so there is no cache-invalidation problem: the files
+ * remain the source of truth, this is a copy of them, and a restart re-derives
+ * it. Staleness would need a writer that bypasses {@link upsert}, and the
+ * server lock guarantees a single writing process.
+ */
+
+import type { CommentThreadStore } from './thread-store.ts';
+import type { CommentThreadMeta } from './types.ts';
+
+export class CommentIndex {
+ private readonly threads = new Map<string, CommentThreadMeta>();
+ private readonly docToThreads = new Map<string, Set<string>>();
+
+ /** Build the index from the store. Call once at server boot. */
+ async build(store: CommentThreadStore): Promise<void> {
+ this.threads.clear();
+ this.docToThreads.clear();
+ for (const meta of await store.scanCoverSheets()) this.upsert(meta);
+ }
+
+ /**
+ * Record (or replace) a thread. Idempotent, and the ONLY way a change reaches
+ * the index — every write path calls this with what it just persisted, which
+ * is what keeps the copy honest.
+ */
+ upsert(meta: CommentThreadMeta): void {
+ const previous = this.threads.get(meta.threadId);
+ if (previous !== undefined && previous.docName !== meta.docName) {
+ this.detach(previous.docName, meta.threadId);
+ }
+ this.threads.set(meta.threadId, meta);
+ let set = this.docToThreads.get(meta.docName);
+ if (!set) {
+ set = new Set();
+ this.docToThreads.set(meta.docName, set);
+ }
+ set.add(meta.threadId);
+ }
+
+ /** Drop a deleted thread from the index. */
+ remove(threadId: string): void {
+ const meta = this.threads.get(threadId);
+ if (meta === undefined) return;
+ this.threads.delete(threadId);
+ this.detach(meta.docName, threadId);
+ }
+
+ /**
+ * Follow a doc rename: re-point every thread from `from` to `to`. Wired into
+ * the existing rename walk alongside the link/tag indexes. Rewrites each
+ * cached thread's `docName` too, or the copy would disagree with the files
+ * the rename walk just updated.
+ */
+ renameDoc(from: string, to: string): void {
+ const set = this.docToThreads.get(from);
+ if (!set) return;
+ this.docToThreads.delete(from);
+ const dest = this.docToThreads.get(to) ?? new Set<string>();
+ for (const threadId of set) {
+ dest.add(threadId);
+ const meta = this.threads.get(threadId);
+ if (meta) this.threads.set(threadId, { ...meta, docName: to });
+ }
+ this.docToThreads.set(to, dest);
+ }
+
+ /** Every thread on a doc. Order-agnostic — callers sort. */
+ listForDoc(docName: string): CommentThreadMeta[] {
+ const out: CommentThreadMeta[] = [];
+ for (const threadId of this.docToThreads.get(docName) ?? []) {
+ const meta = this.threads.get(threadId);
+ if (meta) out.push(meta);
+ }
+ return out;
+ }
+
+ /** Every thread, across every doc — the project-wide view the queue renders. */
+ listAll(): CommentThreadMeta[] {
+ return [...this.threads.values()];
+ }
+
+ /** Thread ids anchored to a doc (order-agnostic). */
+ threadsForDoc(docName: string): string[] {
+ return [...(this.docToThreads.get(docName) ?? [])];
+ }
+
+ /**
+ * Unresolved-thread counts for the named docs — what a reader needs to know
+ * before editing. Every requested name gets an entry (0 when it has none), so
+ * a caller can tell "no comments" from "not asked about".
+ *
+ * Resolved threads are excluded here and in {@link countsUnderPrefix}: they
+ * are settled work, and counting them would leave a doc looking permanently
+ * outstanding to every agent that reads it.
+ */
+ countsForDocs(docNames: readonly string[]): Map<string, number> {
+ const out = new Map<string, number>();
+ for (const docName of docNames) out.set(docName, this.countForDoc(docName));
+ return out;
+ }
+
+ /**
+ * Unresolved-thread counts for every doc under a folder prefix — the folder
+ * rollup an `ls` entry reports. Sparse: only docs that actually carry threads
+ * appear, so a caller sums the values for a subtree total and can also name
+ * which docs the total came from.
+ *
+ * `prefix` is a docName prefix, not a path glob. An empty prefix means the
+ * whole project.
+ */
+ countsUnderPrefix(prefix: string): Map<string, number> {
+ // A bare `docs` must not match `docsite/page` — segment-boundary the
+ // prefix, and treat the empty prefix as project-wide.
+ const scope = prefix === '' ? '' : prefix.endsWith('/') ? prefix : `${prefix}/`;
+ const out = new Map<string, number>();
+ for (const docName of this.docToThreads.keys()) {
+ if (!docName.startsWith(scope)) continue;
+ const count = this.countForDoc(docName);
+ if (count > 0) out.set(docName, count);
+ }
+ return out;
+ }
+
+ /** Unresolved threads on one doc. */
+ countForDoc(docName: string): number {
+ let count = 0;
+ for (const threadId of this.docToThreads.get(docName) ?? []) {
+ if (this.threads.get(threadId)?.state !== 'resolved') count++;
+ }
+ return count;
+ }
+
+ get size(): number {
+ return this.threads.size;
+ }
+
+ private detach(docName: string, threadId: string): void {
+ const set = this.docToThreads.get(docName);
+ if (!set) return;
+ set.delete(threadId);
+ if (set.size === 0) this.docToThreads.delete(docName);
+ }
+}
diff --git a/packages/server/src/comments/comment-service.test.ts b/packages/server/src/comments/comment-service.test.ts
new file mode 100644
index 000000000..20071582e
--- /dev/null
+++ b/packages/server/src/comments/comment-service.test.ts
@@ -0,0 +1,942 @@
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { getLogger } from '../logger.ts';
+import { CommentIndex } from './comment-index.ts';
+import {
+ CommentService,
+ DocNotFoundError,
+ PassageNotFoundError,
+ PropertyNotFoundError,
+ ThreadNotFoundError,
+} from './comment-service.ts';
+import { CommentThreadStore } from './thread-store.ts';
+
+const log = getLogger('comment-service-test');
+
+let dirs: string[] = [];
+function tmp(): string {
+ const d = mkdtempSync(join(tmpdir(), 'comment-service-test-'));
+ dirs.push(d);
+ return d;
+}
+afterEach(() => {
+ for (const d of dirs) rmSync(d, { recursive: true, force: true });
+ dirs = [];
+});
+
+const ORIGINAL = 'The rollout is scheduled for Q3. We expect minimal downtime.';
+
+let store: CommentThreadStore;
+let index: CommentIndex;
+let bodies: Map<string, string>;
+/** Frontmatter records per doc — what a property thread re-finds against. */
+let frontmatter: Map<string, Record<string, unknown>>;
+let clock: number;
+let ids: number;
+let svc: CommentService;
+/** Document reads, counted so the dispatch path can assert it does not double-read. */
+let docBodyReads: number;
+
+beforeEach(async () => {
+ store = new CommentThreadStore(tmp(), log);
+ await store.init();
+ index = new CommentIndex();
+ bodies = new Map([['notes/rollout', ORIGINAL]]);
+ frontmatter = new Map<string, Record<string, unknown>>([
+ [
+ 'notes/rollout',
+ {
+ title: 'Rollout notes',
+ tags: ['infra', 'q3'],
+ summary: 'Ships in Q3. Downtime should be minimal.',
+ author: { name: 'Ada' },
+ },
+ ],
+ ]);
+ clock = 1000;
+ ids = 0;
+ docBodyReads = 0;
+ svc = new CommentService({
+ store,
+ index,
+ getDocBody: (doc) => {
+ docBodyReads += 1;
+ return bodies.get(doc) ?? null;
+ },
+ getDocFrontmatter: (doc) => frontmatter.get(doc) ?? null,
+ now: () => ++clock,
+ newId: () => `t${++ids}`,
+ });
+});
+
+async function makeThread(quote = 'minimal downtime') {
+ const start = ORIGINAL.indexOf(quote);
+ return svc.createThread({
+ docName: 'notes/rollout',
+ start,
+ end: start + quote.length,
+ author: 'principal-abc',
+ body: 'still accurate?',
+ });
+}
+
+describe('CommentService — create / read / list', () => {
+ test('creates an anchored thread and indexes it', async () => {
+ const meta = await makeThread();
+ expect(meta.state).toBe('anchored');
+ expect(meta.anchor.exact).toBe('minimal downtime');
+ expect(index.threadsForDoc('notes/rollout')).toEqual([meta.threadId]);
+
+ expect((await svc.readThread(meta.threadId)).latestComment).toBe('still accurate?');
+ });
+
+ test('listThreads returns cover sheets for a doc', async () => {
+ await makeThread('minimal downtime');
+ await makeThread('Q3');
+ const list = await svc.listThreads('notes/rollout');
+ expect(list.map((m) => m.anchor.exact).sort()).toEqual(['Q3', 'minimal downtime']);
+ });
+
+ test('listThreads without a doc spans the whole project', async () => {
+ bodies.set('other/doc', ORIGINAL);
+ await makeThread('minimal downtime');
+ await svc.createThread({
+ docName: 'other/doc',
+ start: ORIGINAL.indexOf('Q3'),
+ end: ORIGINAL.indexOf('Q3') + 2,
+ author: 'principal-abc',
+ body: 'elsewhere',
+ });
+
+ const all = await svc.listThreads();
+ expect(all.map((m) => m.docName).sort()).toEqual(['notes/rollout', 'other/doc']);
+ // still scopes correctly when asked for one doc
+ expect(await svc.listThreads('other/doc')).toHaveLength(1);
+ });
+
+ test('createThread with queue posts straight into the queue', async () => {
+ const start = ORIGINAL.indexOf('minimal downtime');
+ const meta = await svc.createThread({
+ docName: 'notes/rollout',
+ start,
+ end: start + 'minimal downtime'.length,
+ author: 'principal-abc',
+ body: 'batch this',
+ queue: true,
+ });
+ expect(meta.queued).toBe(true);
+ expect(meta.state).toBe('anchored');
+ });
+
+ test('anchors by quote when the caller has no body offsets', async () => {
+ // The rich-text editor only has ProseMirror positions, so it sends words.
+ const meta = await svc.createThread({
+ docName: 'notes/rollout',
+ quote: 'minimal downtime',
+ author: 'principal-abc',
+ body: 'still true?',
+ });
+ expect(meta.anchor.exact).toBe('minimal downtime');
+ expect(ORIGINAL.slice(meta.anchor.start, meta.anchor.end)).toBe('minimal downtime');
+ });
+
+ test('matches a passage the editor rendered without its markdown syntax', async () => {
+ // A selection spanning a heading and a list item arrives as the editor
+ // renders it — no "##", no "1.", blocks joined by a newline — while the body
+ // still carries all of it. Only syntax and whitespace may differ; the words
+ // must still match exactly.
+ bodies.set('notes/steps', '## Steps\n\n1. Heat oven to 425F.\n2. Toss the sweet potato.');
+ const meta = await svc.createThread({
+ docName: 'notes/steps',
+ quote: 'Steps\nHeat oven to 425F.',
+ author: 'principal-abc',
+ body: 'how hot?',
+ });
+ expect(meta.state).toBe('anchored');
+ // the resolved range covers the real source text, markers and all
+ const body = bodies.get('notes/steps') ?? '';
+ expect(body.slice(meta.anchor.start, meta.anchor.end)).toBe('Steps\n\n1. Heat oven to 425F.');
+ });
+
+ test('anchors a passage that starts after a bold run inside a list item', async () => {
+ // The reported 400: the source line is "- **Peanut sauce:** 3 tbsp ...", so
+ // the selected words are not a literal substring of the body — the bold
+ // markers sit inside the passage.
+ bodies.set(
+ 'recipes/stir-fry',
+ '## Ingredients\n\n- 2 tbsp neutral oil\n- **Peanut sauce:** 3 tbsp peanut butter, water to loosen\n',
+ );
+ const meta = await svc.createThread({
+ docName: 'recipes/stir-fry',
+ quote: 'Peanut sauce: 3 tbsp peanut butter',
+ author: 'principal-abc',
+ body: 'how much water?',
+ });
+ expect(meta.state).toBe('anchored');
+ const body = bodies.get('recipes/stir-fry') ?? '';
+ expect(body.slice(meta.anchor.start, meta.anchor.end)).toBe(
+ 'Peanut sauce:** 3 tbsp peanut butter',
+ );
+ });
+
+ test('relaxed matching still refuses different words', async () => {
+ bodies.set('notes/steps', '## Steps\n\n1. Heat oven to 425F.');
+ await expect(
+ svc.createThread({
+ docName: 'notes/steps',
+ quote: 'Steps Heat oven to 500F.',
+ author: 'principal-abc',
+ body: 'x',
+ }),
+ ).rejects.toBeInstanceOf(PassageNotFoundError);
+ });
+
+ test('rejects a quote that is not in the document', async () => {
+ await expect(
+ svc.createThread({
+ docName: 'notes/rollout',
+ quote: 'text that was never here',
+ author: 'principal-abc',
+ body: 'x',
+ }),
+ ).rejects.toBeInstanceOf(PassageNotFoundError);
+ });
+
+ test('replaceAnchor accepts a quote too', async () => {
+ const { threadId } = await makeThread();
+ const meta = await svc.replaceAnchor(threadId, { quote: 'Q3' });
+ expect(meta.anchor.exact).toBe('Q3');
+ expect(meta.state).toBe('anchored');
+ });
+
+ test('createThread on a missing doc throws', async () => {
+ await expect(
+ svc.createThread({ docName: 'gone', start: 0, end: 1, author: 'principal-x', body: 'x' }),
+ ).rejects.toBeInstanceOf(DocNotFoundError);
+ });
+
+ test('listing threads reads no files at all', async () => {
+ // The app refetches the whole project on every mutation and every push
+ // notification, so a per-thread file read here made one click cost O(every
+ // comment ever made). The index holds the threads; this pins that it is
+ // actually what answers.
+ await makeThread('minimal downtime');
+ await makeThread('Q3');
+ const reads = vi.spyOn(store, 'readMeta');
+
+ const all = await svc.listThreads();
+ const scoped = await svc.listThreads('notes/rollout');
+
+ expect(all).toHaveLength(2);
+ expect(scoped).toHaveLength(2);
+ expect(reads).not.toHaveBeenCalled();
+ });
+
+ test('a mutation is visible to the very next list', async () => {
+ // The other half of the trade: reads never hit disk, so a write that failed
+ // to refresh the index would serve the pre-mutation state indefinitely.
+ const { threadId } = await makeThread();
+ await svc.editComment(threadId, 'revised ask');
+ await svc.resolve(threadId);
+
+ const [meta] = await svc.listThreads('notes/rollout');
+ expect(meta.latestComment).toBe('revised ask');
+ expect(meta.state).toBe('resolved');
+ });
+
+ test('a rename is visible to the very next list', async () => {
+ const { threadId } = await makeThread();
+ bodies.set('notes/rollout-2026', ORIGINAL);
+ await svc.renameDoc('notes/rollout', 'notes/rollout-2026');
+
+ expect(await svc.listThreads('notes/rollout')).toEqual([]);
+ const moved = await svc.listThreads('notes/rollout-2026');
+ expect(moved.map((m) => m.threadId)).toEqual([threadId]);
+ expect(moved[0].docName).toBe('notes/rollout-2026');
+ });
+
+ test('a deleted thread leaves the list immediately', async () => {
+ const { threadId } = await makeThread();
+ await svc.delete(threadId);
+ expect(await svc.listThreads()).toEqual([]);
+ });
+
+ test('prepareDispatch reads the document once, not once per use', async () => {
+ // The re-find and the repeated-quote check both want the same body. Reading
+ // it twice is invisible in behaviour and doubles the cost of a batch, which
+ // runs this sequentially per thread.
+ const { threadId } = await makeThread();
+ docBodyReads = 0;
+ await svc.prepareDispatch(threadId);
+ expect(docBodyReads).toBe(1);
+ });
+
+ test('a batch reads each thread its document exactly once', async () => {
+ const a = await makeThread('minimal downtime');
+ const b = await makeThread('Q3');
+ docBodyReads = 0;
+ await svc.prepareDispatchBatch([a.threadId, b.threadId]);
+ expect(docBodyReads).toBe(2);
+ });
+
+ describe('a repeated quote resolves to the occurrence the caller selected', () => {
+ // Two identical sentences under different headings — the case where taking
+ // the first match anchors the comment to a passage nobody picked, and the
+ // create-time context widening then cements it with nothing flagged.
+ const REPEATED = [
+ '## Rollout',
+ 'We will ship with minimal downtime.',
+ '',
+ '## Rollback',
+ 'We will ship with minimal downtime.',
+ ].join('\n');
+ const SECOND = REPEATED.lastIndexOf('minimal downtime');
+
+ beforeEach(() => {
+ bodies.set('notes/repeat', REPEATED);
+ });
+
+ async function commentOnRepeat(context: { prefix?: string; suffix?: string }) {
+ return svc.createThread({
+ docName: 'notes/repeat',
+ quote: 'minimal downtime',
+ ...context,
+ author: 'principal-abc',
+ body: 'not true for rollback',
+ });
+ }
+
+ test('the context around the selection picks the second one', async () => {
+ // Rendered text, as the editor would capture it — no `##`, which is
+ // exactly why the scoring has to tolerate a partial match.
+ const meta = await commentOnRepeat({ prefix: 'Rollback\nWe will ship with ' });
+ expect(meta.anchor.start).toBe(SECOND);
+ });
+
+ test('the suffix side works on its own', async () => {
+ const first = REPEATED.indexOf('minimal downtime');
+ const meta = await commentOnRepeat({ suffix: '.\n\n## Rollback' });
+ expect(meta.anchor.start).toBe(first);
+ });
+
+ test('no context still lands on the first occurrence', async () => {
+ // Nothing better to go on — the previous behavior, now the fallback
+ // rather than the rule.
+ const meta = await commentOnRepeat({});
+ expect(meta.anchor.start).toBe(REPEATED.indexOf('minimal downtime'));
+ });
+
+ test('the widened context describes the passage that was actually chosen', async () => {
+ // The failure this guards is silent: a wrong pick produces a perfectly
+ // valid, unique anchor, so only the stored context reveals which passage
+ // the thread really points at.
+ const meta = await commentOnRepeat({ prefix: 'Rollback\nWe will ship with ' });
+ expect(meta.anchor.prefix).toContain('Rollback');
+ expect(meta.anchor.prefix).not.toContain('Rollout');
+ });
+ });
+});
+
+describe('CommentService — edit / resolve / reopen', () => {
+ test('an edit replaces the comment and the lifecycle moves through it', async () => {
+ const { threadId } = await makeThread();
+ await svc.editComment(threadId, 'still right?');
+ expect((await svc.readThread(threadId)).latestComment).toBe('still right?');
+
+ let meta = await svc.resolve(threadId);
+ expect(meta.state).toBe('resolved');
+ meta = await svc.reopen(threadId);
+ expect(meta.state).toBe('anchored');
+ // The comment survives the round trip; only state moved.
+ expect(meta.latestComment).toBe('still right?');
+ });
+
+ test('reopening re-checks the anchor rather than assuming it is still there', async () => {
+ // `resolved` does not preserve what the anchor state was underneath it, so
+ // reopening has to re-establish it — otherwise a thread closed while
+ // orphaned would reopen claiming to be anchored.
+ const { threadId } = await makeThread();
+ await svc.resolve(threadId);
+ bodies.set('notes/rollout', 'The rollout is scheduled for Q3. All clear now.');
+
+ expect((await svc.reopen(threadId)).state).toBe('orphaned');
+ });
+
+ test('unknown thread throws', async () => {
+ await expect(svc.editComment('nope', 'b')).rejects.toBeInstanceOf(ThreadNotFoundError);
+ });
+});
+
+describe('CommentService — deleteDoc (document deleted)', () => {
+ test('deletes every thread on the doc and reports how many', async () => {
+ await makeThread('minimal downtime');
+ await makeThread('Q3');
+
+ expect(await svc.deleteDoc('notes/rollout')).toBe(2);
+ expect(await svc.listThreads('notes/rollout')).toEqual([]);
+ expect(await svc.listThreads()).toEqual([]);
+ });
+
+ test('leaves other documents alone', async () => {
+ bodies.set('other/doc', ORIGINAL);
+ const keep = await svc.createThread({
+ docName: 'other/doc',
+ quote: 'Q3',
+ author: 'principal-abc',
+ body: 'elsewhere',
+ });
+ await makeThread();
+
+ expect(await svc.deleteDoc('notes/rollout')).toBe(1);
+ expect((await svc.listThreads()).map((m) => m.threadId)).toEqual([keep.threadId]);
+ });
+
+ test('a doc with no threads is a no-op', async () => {
+ await makeThread();
+ expect(await svc.deleteDoc('notes/never-commented')).toBe(0);
+ expect(await svc.listThreads()).toHaveLength(1);
+ });
+
+ test('the threads are gone from disk, not just the index', async () => {
+ // The index is a cache rebuilt from disk at boot, so dropping only the
+ // cached entry would resurrect every deleted thread on the next restart.
+ const { threadId } = await makeThread();
+ await svc.deleteDoc('notes/rollout');
+
+ expect(await store.readMeta(threadId)).toBeNull();
+ expect(await store.scanCoverSheets()).toEqual([]);
+ });
+
+ test('a deleted doc takes its queued comments out of the batch with it', async () => {
+ // The reason this matters: a thread on a missing document reads as a
+ // HEALTHY anchor — the re-find bails out when the body cannot be read — so
+ // left in the queue it would be dispatched with `anchorLost: false`,
+ // telling an agent to edit a document that no longer exists.
+ const start = ORIGINAL.indexOf('minimal downtime');
+ await svc.createThread({
+ docName: 'notes/rollout',
+ start,
+ end: start + 'minimal downtime'.length,
+ author: 'principal-abc',
+ body: 'batch this',
+ queue: true,
+ });
+ expect((await svc.listThreads()).filter((m) => m.queued)).toHaveLength(1);
+
+ await svc.deleteDoc('notes/rollout');
+ expect(await svc.listThreads()).toEqual([]);
+ });
+});
+
+describe('CommentService — refindDoc (document settled)', () => {
+ test('deleting a commented passage orphans the thread without anyone asking', async () => {
+ // The gap this closes: state used to refresh only when a comment was queued
+ // or sent, so a deleted passage left the comment looking healthy — highlight
+ // silently gone, card unchanged — until you tried to send it.
+ const { threadId } = await makeThread();
+ bodies.set('notes/rollout', 'The rollout is scheduled for Q3. All clear now.');
+
+ expect(await svc.refindDoc('notes/rollout')).toBe(true);
+ expect((await svc.readThread(threadId)).state).toBe('orphaned');
+ });
+
+ test('restoring the passage recovers the thread', async () => {
+ const { threadId } = await makeThread();
+ bodies.set('notes/rollout', 'gone');
+ await svc.refindDoc('notes/rollout');
+ bodies.set('notes/rollout', ORIGINAL);
+
+ expect(await svc.refindDoc('notes/rollout')).toBe(true);
+ expect((await svc.readThread(threadId)).state).toBe('anchored');
+ });
+
+ test('an unchanged document reports no change and writes nothing', async () => {
+ // This runs on every settle of every document, so the steady state has to
+ // be free. A write here would mean one per thread per keystroke burst.
+ await makeThread();
+ const writes = vi.spyOn(store, 'update');
+
+ expect(await svc.refindDoc('notes/rollout')).toBe(false);
+ expect(writes).not.toHaveBeenCalled();
+ });
+
+ test('a passage that merely moved is left alone', async () => {
+ // Position is a hint, not authority. Re-capturing it on every settle would
+ // be a write per thread for text that is still exactly where the words say.
+ await makeThread();
+ bodies.set('notes/rollout', `Heads up: dates may slip. ${ORIGINAL}`);
+ const writes = vi.spyOn(store, 'update');
+
+ expect(await svc.refindDoc('notes/rollout')).toBe(false);
+ expect(writes).not.toHaveBeenCalled();
+ });
+
+ test('a doc with no threads never touches the document', async () => {
+ // Every settle of every document reaches this, including the vast majority
+ // that carry no comments at all.
+ await makeThread();
+ docBodyReads = 0;
+
+ expect(await svc.refindDoc('notes/untouched')).toBe(false);
+ expect(docBodyReads).toBe(0);
+ });
+
+ test('resolved threads are skipped', async () => {
+ const { threadId } = await makeThread();
+ await svc.resolve(threadId);
+ bodies.set('notes/rollout', 'nothing left');
+
+ expect(await svc.refindDoc('notes/rollout')).toBe(false);
+ expect((await svc.readThread(threadId)).state).toBe('resolved');
+ });
+});
+
+describe('CommentService — refindOnLoad', () => {
+ test('follows the anchor silently when text is inserted above it', async () => {
+ const { threadId, anchor } = await makeThread();
+ bodies.set('notes/rollout', `Heads up: dates may slip. ${ORIGINAL}`);
+
+ const meta = await svc.refindOnLoad(threadId);
+
+ expect(meta.state).toBe('anchored');
+ expect(meta.anchor.start).not.toBe(anchor.start); // hint moved
+ expect(meta.anchor.exact).toBe('minimal downtime'); // and still the same words
+ });
+
+ test('orphans explicitly when the quoted text is gone', async () => {
+ const { threadId } = await makeThread();
+ bodies.set('notes/rollout', 'The rollout is scheduled for Q3. All clear now.');
+
+ const meta = await svc.refindOnLoad(threadId);
+ expect(meta.state).toBe('orphaned');
+
+ // idempotent: a second load while still gone reports the same thing
+ expect((await svc.refindOnLoad(threadId)).state).toBe('orphaned');
+ });
+
+ test('recovers when the text returns', async () => {
+ const { threadId } = await makeThread();
+ bodies.set('notes/rollout', 'gone');
+ expect((await svc.refindOnLoad(threadId)).state).toBe('orphaned');
+ bodies.set('notes/rollout', ORIGINAL);
+
+ expect((await svc.refindOnLoad(threadId)).state).toBe('anchored');
+ });
+
+ test('skips resolved threads', async () => {
+ const { threadId } = await makeThread();
+ await svc.resolve(threadId);
+ bodies.set('notes/rollout', 'gone'); // would orphan if it ran
+ const meta = await svc.refindOnLoad(threadId);
+ expect(meta.state).toBe('resolved');
+ });
+});
+
+describe('CommentService — re-placement and dispatch queue', () => {
+ test('replaceAnchor re-anchors an orphaned thread', async () => {
+ const { threadId } = await makeThread();
+ bodies.set('notes/rollout', 'Rollout moved to Q4. We expect minimal downtime still.');
+ await svc.refindOnLoad(threadId); // still finds "minimal downtime"; force orphan instead:
+ bodies.set('notes/rollout', 'Totally different text about nothing.');
+ let meta = await svc.refindOnLoad(threadId);
+ expect(meta.state).toBe('orphaned');
+
+ const next = 'Totally different text about nothing.';
+ const start = next.indexOf('different');
+ meta = await svc.replaceAnchor(threadId, { start, end: start + 'different'.length });
+ expect(meta.state).toBe('anchored');
+ expect(meta.anchor.exact).toBe('different');
+ });
+
+ test('queueForDispatch: anchored thread queues and is not orphaned', async () => {
+ const { threadId } = await makeThread();
+ const res = await svc.queueForDispatch(threadId);
+ expect(res.orphaned).toBe(false);
+ expect(res.meta.queued).toBe(true);
+ expect(res.meta.state).toBe('anchored');
+ });
+
+ test('queueForDispatch: lost anchor stays queued but is held (orphaned)', async () => {
+ const { threadId } = await makeThread();
+ bodies.set('notes/rollout', 'nothing to see here');
+ const res = await svc.queueForDispatch(threadId);
+ expect(res.orphaned).toBe(true);
+ expect(res.meta.queued).toBe(true); // stays IN the queue
+ expect(res.meta.state).toBe('orphaned'); // but blocked
+ // and the same is true when read back, not just in the return value
+ const stored = await svc.readThread(threadId);
+ expect(stored.queued).toBe(true);
+ expect(stored.state).toBe('orphaned');
+ });
+
+ test('unqueue clears the queue flag', async () => {
+ const { threadId } = await makeThread();
+ await svc.queueForDispatch(threadId);
+ const meta = await svc.unqueue(threadId);
+ expect(meta.queued).toBe(false);
+ });
+});
+
+describe('CommentService — dispatch (client-delivered, resolve-on-send)', () => {
+ test('prepare hands back the ingredients the client composes with', async () => {
+ const { threadId } = await makeThread();
+ const res = await svc.prepareDispatch(threadId);
+
+ expect(res.payload.docName).toBe('notes/rollout');
+ expect(res.payload.instruction).toBe('still accurate?');
+ expect(res.payload.passage.exact).toBe('minimal downtime');
+ expect(res.payload.anchorLost).toBe(false);
+ // queued while it is out for delivery, not yet resolved
+ expect(res.meta.queued).toBe(true);
+ expect(res.meta.state).toBe('anchored');
+ });
+
+ test('prepare sends the revised comment, not the text it replaced', async () => {
+ // Dispatch must carry the revision, not the text it replaced — handing an
+ // agent the opening ask would have it act on words the reviewer deliberately
+ // rewrote.
+ const { threadId } = await makeThread(); // opens with "still accurate?"
+ await svc.editComment(threadId, 'actually: cite the SLA');
+
+ const instruction = (await svc.prepareDispatch(threadId)).payload.instruction;
+
+ expect(instruction).toBe('actually: cite the SLA');
+ expect(instruction).not.toContain('still accurate?');
+ });
+
+ test('a single-comment thread sends the bare body, unlabelled', async () => {
+ const { threadId } = await makeThread();
+ const instruction = (await svc.prepareDispatch(threadId)).payload.instruction;
+ expect(instruction).toBe('still accurate?');
+ });
+
+ test('complete closes the thread', async () => {
+ const { threadId } = await makeThread();
+ await svc.prepareDispatch(threadId);
+ const meta = await svc.completeDispatch(threadId);
+
+ expect(meta.state).toBe('resolved');
+ expect(meta.queued).toBe(false);
+ // closing clears the queue in the same write, so a crash between the two
+ // cannot leave a resolved thread still sitting in the batch
+ expect(await svc.readThread(threadId)).toMatchObject({
+ state: 'resolved',
+ queued: false,
+ });
+ });
+
+ test('an orphaned thread is still sent, flagged so the agent is told', async () => {
+ const { threadId } = await makeThread();
+ bodies.set('notes/rollout', 'nothing to see here');
+ const res = await svc.prepareDispatch(threadId);
+
+ // sent by default — the payload carries the quoted words, not a stale offset
+ expect(res.payload.anchorLost).toBe(true);
+ expect(res.payload.passage.exact).toBe('minimal downtime');
+ expect(res.payload.instruction).toBe('still accurate?');
+ // the loss is still recorded on the thread, so re-placement stays offerable
+ expect(res.meta.state).toBe('orphaned');
+ expect((await svc.readThread(threadId)).state).toBe('orphaned');
+ });
+
+ test('a delivery the client could not complete leaves the thread open', async () => {
+ const { threadId } = await makeThread();
+ await svc.prepareDispatch(threadId);
+ // client failed to launch the agent → releases the queue instead of completing
+ const meta = await svc.unqueue(threadId);
+
+ expect(meta.state).toBe('anchored'); // NOT resolved
+ expect(meta.queued).toBe(false);
+ });
+
+ test('batch prepare returns results in the requested order', async () => {
+ const a = await makeThread('minimal downtime');
+ const b = await makeThread('Q3');
+ const c = await makeThread('rollout');
+
+ const results = await svc.prepareDispatchBatch([c.threadId, a.threadId, b.threadId]);
+ expect(results.map((r) => r.threadId)).toEqual([c.threadId, a.threadId, b.threadId]);
+ expect(results.every((r) => r.ok)).toBe(true);
+ for (const r of results) if (r.ok) expect(r.payload.docName).toBe('notes/rollout');
+ });
+
+ test('one missing id does not fail the rest of the batch', async () => {
+ const a = await makeThread('minimal downtime');
+ const b = await makeThread('Q3');
+
+ const results = await svc.prepareDispatchBatch([a.threadId, 'gone', b.threadId]);
+ expect(results.map((r) => r.ok)).toEqual([true, false, true]);
+ const missing = results[1];
+ expect(missing.ok).toBe(false);
+ if (!missing.ok) expect(missing.error).toBe('not-found');
+ // the surviving items really were queued
+ expect((await store.readMeta(a.threadId))?.queued).toBe(true);
+ expect((await store.readMeta(b.threadId))?.queued).toBe(true);
+ });
+
+ test('batch complete resolves every selected thread', async () => {
+ const a = await makeThread('minimal downtime');
+ const b = await makeThread('Q3');
+ await svc.prepareDispatchBatch([a.threadId, b.threadId]);
+
+ const results = await svc.completeDispatchBatch([a.threadId, b.threadId]);
+ expect(results.every((r) => r.ok)).toBe(true);
+ for (const id of [a.threadId, b.threadId]) {
+ const meta = await store.readMeta(id);
+ expect(meta?.state).toBe('resolved');
+ expect(meta?.queued).toBe(false);
+ }
+ });
+
+ test('deselected threads stay queued when the batch goes out', async () => {
+ const selected = await makeThread('minimal downtime');
+ const deselected = await makeThread('Q3');
+ await svc.queueForDispatch(deselected.threadId); // queued, but not in the batch
+
+ await svc.prepareDispatchBatch([selected.threadId]);
+ await svc.completeDispatchBatch([selected.threadId]);
+
+ expect((await store.readMeta(selected.threadId))?.state).toBe('resolved');
+ const left = await store.readMeta(deselected.threadId);
+ expect(left?.queued).toBe(true); // still waiting for a later batch
+ expect(left?.state).toBe('anchored');
+ });
+
+ test('a dispatched thread can be reopened', async () => {
+ const { threadId } = await makeThread();
+ await svc.prepareDispatch(threadId);
+ await svc.completeDispatch(threadId);
+ const meta = await svc.reopen(threadId);
+ expect(meta.state).toBe('anchored');
+ });
+});
+
+describe('CommentService — renameDoc (US-12)', () => {
+ test('threads follow a renamed doc in both the index and the cover sheets', async () => {
+ const a = await makeThread('minimal downtime');
+ const b = await makeThread('Q3');
+ expect(index.threadsForDoc('notes/rollout').sort()).toEqual([a.threadId, b.threadId].sort());
+
+ await svc.renameDoc('notes/rollout', 'notes/rollout-2026');
+
+ expect(index.threadsForDoc('notes/rollout')).toEqual([]);
+ expect(index.threadsForDoc('notes/rollout-2026').sort()).toEqual(
+ [a.threadId, b.threadId].sort(),
+ );
+ expect((await store.readMeta(a.threadId))?.docName).toBe('notes/rollout-2026');
+ expect((await store.readMeta(b.threadId))?.docName).toBe('notes/rollout-2026');
+ });
+
+ test('is a no-op when the doc has no threads', async () => {
+ await expect(svc.renameDoc('empty', 'empty-2')).resolves.toBeUndefined();
+ });
+});
+
+describe('CommentService — delete', () => {
+ test('removes the thread from store and index', async () => {
+ const { threadId } = await makeThread();
+ await svc.delete(threadId);
+ expect(index.threadsForDoc('notes/rollout')).toEqual([]);
+ await expect(svc.readThread(threadId)).rejects.toBeInstanceOf(ThreadNotFoundError);
+ });
+});
+
+describe('CommentService — property threads', () => {
+ async function makePropertyThread(key = 'tags') {
+ return svc.createThread({
+ docName: 'notes/rollout',
+ propertyKey: key,
+ author: 'principal-abc',
+ body: 'these tags are stale',
+ });
+ }
+
+ test('a property thread stores its key and carries NO anchor', async () => {
+ const meta = await makePropertyThread();
+ expect(meta.target).toEqual({ kind: 'property', key: 'tags', path: [] });
+ // The absence is the point: a filler anchor would let a re-find path that
+ // forgot to branch go looking for "tags" in the prose and match it.
+ expect(meta.anchor).toBeNull();
+ expect(meta.state).toBe('anchored');
+ });
+
+ test('a body thread still records a body target, so old threads keep working', async () => {
+ const meta = await makeThread();
+ expect(meta.target).toEqual({ kind: 'body' });
+ expect(meta.anchor).not.toBeNull();
+ });
+
+ test('refuses a key the document does not declare', async () => {
+ await expect(makePropertyThread('nonexistent')).rejects.toBeInstanceOf(PropertyNotFoundError);
+ });
+
+ test('editing the body never orphans a property thread', async () => {
+ const { threadId } = await makePropertyThread();
+ // The passage a body comment would have pointed at is gone; the key is not.
+ bodies.set('notes/rollout', 'Entirely different prose.');
+ await svc.refindDoc('notes/rollout');
+ expect((await svc.readThread(threadId)).state).toBe('anchored');
+ });
+
+ test('removing the key orphans it, and restoring the key recovers it', async () => {
+ const { threadId } = await makePropertyThread();
+ frontmatter.set('notes/rollout', { title: 'Rollout notes' });
+ await svc.refindDoc('notes/rollout');
+ expect((await svc.readThread(threadId)).state).toBe('orphaned');
+
+ frontmatter.set('notes/rollout', { title: 'Rollout notes', tags: ['infra', 'q3'] });
+ await svc.refindDoc('notes/rollout');
+ expect((await svc.readThread(threadId)).state).toBe('anchored');
+ });
+
+ test('unreadable frontmatter leaves the state alone rather than orphaning', async () => {
+ const { threadId } = await makePropertyThread();
+ frontmatter.delete('notes/rollout');
+ await svc.refindDoc('notes/rollout');
+ // A doc that could not be read is not evidence the key is gone — the same
+ // contract the body path applies to an unreadable body.
+ expect((await svc.readThread(threadId)).state).toBe('anchored');
+ });
+
+ test('dispatch names the key and sends no passage', async () => {
+ const { threadId } = await makePropertyThread();
+ const { payload } = await svc.prepareDispatch(threadId);
+ expect(payload.property).toBe('tags');
+ expect(payload.passage).toBeNull();
+ expect(payload.anchorLost).toBe(false);
+ // A key is unique in its frontmatter, so the which-occurrence question the
+ // body path answers cannot arise.
+ expect(payload.passageRepeats).toBe(false);
+ });
+
+ test('dispatch reports a removed key as lost rather than withholding it', async () => {
+ const { threadId } = await makePropertyThread();
+ frontmatter.set('notes/rollout', { title: 'Rollout notes' });
+ const { payload } = await svc.prepareDispatch(threadId);
+ expect(payload.property).toBe('tags');
+ expect(payload.anchorLost).toBe(true);
+ });
+
+ test('re-placement onto a passage is refused', async () => {
+ const { threadId } = await makePropertyThread();
+ // Re-placement moves a comment onto fresh prose, which would silently change
+ // what a property comment is about.
+ await expect(svc.replaceAnchor(threadId, { quote: 'minimal downtime' })).rejects.toBeInstanceOf(
+ PropertyNotFoundError,
+ );
+ });
+});
+
+describe('CommentService — property paths and value passages', () => {
+ async function makeThreadAt(
+ propertyKey: string,
+ propertyPath: (string | number)[],
+ quote?: string,
+ ) {
+ return svc.createThread({
+ docName: 'notes/rollout',
+ propertyKey,
+ propertyPath,
+ quote,
+ author: 'principal-abc',
+ body: 'note',
+ });
+ }
+
+ test('a path addresses one list item', async () => {
+ const meta = await makeThreadAt('tags', [1]);
+ expect(meta.target).toEqual({ kind: 'property', key: 'tags', path: [1] });
+ expect(meta.anchor).toBeNull();
+ });
+
+ test('a path addresses a nested field', async () => {
+ const meta = await makeThreadAt('author', ['name']);
+ expect(meta.target).toEqual({ kind: 'property', key: 'author', path: ['name'] });
+ });
+
+ test('an index past the end of the list is refused', async () => {
+ await expect(makeThreadAt('tags', [9])).rejects.toBeInstanceOf(PropertyNotFoundError);
+ });
+
+ test('a list shrinking past the index orphans the thread', async () => {
+ const { threadId } = await makeThreadAt('tags', [1]);
+ frontmatter.set('notes/rollout', { tags: ['infra'] });
+ await svc.refindDoc('notes/rollout');
+ expect((await svc.readThread(threadId)).state).toBe('orphaned');
+ });
+
+ test('a quote inside a value anchors against THAT value, not the body', async () => {
+ const meta = await makeThreadAt('summary', [], 'Ships in Q3');
+ expect(meta.anchor?.exact).toBe('Ships in Q3');
+ // Offsets index the value: 'Ships in Q3' starts at 0 of the summary, and
+ // nowhere near that in the document body.
+ expect(meta.anchor?.start).toBe(0);
+ });
+
+ test('editing the value elsewhere keeps the passage anchored', async () => {
+ const { threadId } = await makeThreadAt('summary', [], 'Ships in Q3');
+ frontmatter.set('notes/rollout', {
+ summary: 'Update: Ships in Q3. Downtime should be minimal.',
+ });
+ await svc.refindDoc('notes/rollout');
+ // The settle sweep reports state only. It deliberately does NOT re-capture
+ // the position — same policy the body path documents, and for the same
+ // reason: the offsets are a hint, and refreshing them on every settle would
+ // mean a write per thread per keystroke burst.
+ expect((await svc.readThread(threadId)).state).toBe('anchored');
+ });
+
+ test('the per-thread re-find refreshes the moved offsets', async () => {
+ const { threadId } = await makeThreadAt('summary', [], 'Ships in Q3');
+ frontmatter.set('notes/rollout', {
+ summary: 'Update: Ships in Q3. Downtime should be minimal.',
+ });
+ // Where the hint IS refreshed — the path a load or a dispatch takes, so what
+ // reaches an agent is never measured against stale text.
+ const meta = await svc.refindOnLoad(threadId);
+ expect(meta.anchor?.start).toBe('Update: '.length);
+ expect(meta.anchor?.exact).toBe('Ships in Q3');
+ });
+
+ test('removing the quoted words orphans it, while the key survives', async () => {
+ const { threadId } = await makeThreadAt('summary', [], 'Ships in Q3');
+ frontmatter.set('notes/rollout', { summary: 'Timing to be confirmed.' });
+ await svc.refindDoc('notes/rollout');
+ expect((await svc.readThread(threadId)).state).toBe('orphaned');
+ });
+
+ test('a value that stops being text orphans a passage anchored in it', async () => {
+ const { threadId } = await makeThreadAt('summary', [], 'Ships in Q3');
+ // The field became a list. The words cannot be there, and serializing the
+ // list to search it would anchor into punctuation nobody ever saw.
+ frontmatter.set('notes/rollout', { summary: ['Ships in Q3'] });
+ await svc.refindDoc('notes/rollout');
+ expect((await svc.readThread(threadId)).state).toBe('orphaned');
+ });
+
+ test('quoting into a container is refused at create time', async () => {
+ await expect(makeThreadAt('tags', [], 'infra')).rejects.toBeInstanceOf(PropertyNotFoundError);
+ });
+
+ test('dispatch names the path and carries the value passage', async () => {
+ const { threadId } = await makeThreadAt('summary', [], 'Ships in Q3');
+ const { payload } = await svc.prepareDispatch(threadId);
+ expect(payload.property).toBe('summary');
+ expect(payload.passage?.exact).toBe('Ships in Q3');
+ });
+
+ test('dispatch renders a nested path the way a human reads it', async () => {
+ const { threadId } = await makeThreadAt('author', ['name']);
+ const { payload } = await svc.prepareDispatch(threadId);
+ expect(payload.property).toBe('author.name');
+ expect(payload.passage).toBeNull();
+ });
+
+ test('dispatch renders a list index the way a human reads it', async () => {
+ const { threadId } = await makeThreadAt('tags', [1]);
+ const { payload } = await svc.prepareDispatch(threadId);
+ expect(payload.property).toBe('tags[1]');
+ });
+});
diff --git a/packages/server/src/comments/comment-service.ts b/packages/server/src/comments/comment-service.ts
new file mode 100644
index 000000000..e6274dfee
--- /dev/null
+++ b/packages/server/src/comments/comment-service.ts
@@ -0,0 +1,851 @@
+/**
+ * Comment orchestration — ties the store, the boot index, and the anchor
+ * engine together and owns the anchor lifecycle (create, re-find on load,
+ * explicit orphaning, re-placement) and the dispatch-queue storage side.
+ *
+ * Transport-agnostic: the HTTP routes (`comment-api.ts`) are thin adapters
+ * over this. It reaches document text through an injected `getDocBody` so it
+ * stays testable without a live CRDT. All state changes go through the store,
+ * so the per-thread meta file stays the single source of truth.
+ */
+
+import { randomUUID } from 'node:crypto';
+import { findAllPassages } from '@inkeep/open-knowledge-core';
+import { bestByContext, createAnchor, literalSpans, refind } from './anchor.ts';
+import type { CommentIndex } from './comment-index.ts';
+import type { CommentThreadStore } from './thread-store.ts';
+import type {
+ Anchor,
+ CommentTarget,
+ CommentThreadMeta,
+ CommentThreadPatch,
+ PropertyPath,
+} from './types.ts';
+
+/** Body text of a doc (everything after frontmatter), or null if the doc is gone. */
+export type GetDocBody = (docName: string) => Promise<string | null> | string | null;
+
+/**
+ * The doc's current frontmatter as a raw record, or null if the doc is gone.
+ *
+ * Values, not just keys: a property thread can point into a value (one tag, a
+ * nested field) or at a passage inside one, so re-find has to walk the same
+ * structure the comment addressed. Returning the record keeps that walk in the
+ * service, next to the re-find it feeds, rather than splitting it across the
+ * transport that supplies the document.
+ */
+export type GetDocFrontmatter = (
+ docName: string,
+) => Promise<Record<string, unknown> | null> | Record<string, unknown> | null;
+
+/**
+ * Walk a frontmatter record to the value a property target addresses.
+ *
+ * `undefined` for a path that no longer resolves — a renamed key, a list that
+ * shrank past the index, a field that changed shape. Distinct from a value that
+ * IS null, which resolves fine and is simply empty.
+ */
+function resolvePropertyPath(
+ record: Record<string, unknown>,
+ key: string,
+ path: PropertyPath,
+): unknown {
+ if (!Object.hasOwn(record, key)) return undefined;
+ let current: unknown = record[key];
+ for (const step of path) {
+ if (current === null || current === undefined) return undefined;
+ if (typeof step === 'number') {
+ if (!Array.isArray(current) || step >= current.length) return undefined;
+ current = current[step];
+ continue;
+ }
+ if (typeof current !== 'object' || Array.isArray(current)) return undefined;
+ const asRecord = current as Record<string, unknown>;
+ if (!Object.hasOwn(asRecord, step)) return undefined;
+ current = asRecord[step];
+ }
+ return current;
+}
+
+/**
+ * The addressed value as anchorable TEXT, or null when there is none.
+ *
+ * Only scalars have text. A list or a map is structure — you comment on it as a
+ * whole, or you address one of its members with a longer path — so returning a
+ * serialization of it would invite anchoring into punctuation that no editor
+ * ever showed the reader.
+ */
+function propertyValueText(value: unknown): string | null {
+ if (typeof value === 'string') return value;
+ if (typeof value === 'number' || typeof value === 'boolean') return String(value);
+ return null;
+}
+
+export interface CommentServiceDeps {
+ store: CommentThreadStore;
+ index: CommentIndex;
+ getDocBody: GetDocBody;
+ getDocFrontmatter: GetDocFrontmatter;
+ /** Injectable for deterministic tests; defaults to `Date.now`. */
+ now?: () => number;
+ /** Injectable for deterministic tests; defaults to `crypto.randomUUID`. */
+ newId?: () => string;
+}
+
+export interface QueueResult {
+ meta: CommentThreadMeta;
+ /** True when the pre-dispatch re-find lost the anchor: the thread stays queued but is held (Q3). */
+ orphaned: boolean;
+}
+
+/**
+ * What the client needs to hand a comment to an agent.
+ *
+ * Ingredients, not a finished prompt: delivery targets differ (an in-app agent
+ * thread, the docked terminal, a deep link into an external app) and the app's
+ * existing Ask-AI composer already fits a passage to each target's transport and
+ * budget — a deep link has a URL length limit a server-composed string would
+ * blow past. So the server supplies the request and the passage; the client
+ * builds the prompt with the machinery it already uses for Ask AI.
+ */
+interface DispatchPayload {
+ docName: string;
+ /** What the thread is asking for: its newest comment (edits supersede). */
+ instruction: string;
+ /**
+ * The frontmatter key the comment is on, or null for a passage comment.
+ *
+ * A key is sent by NAME and nothing else. The passage machinery below exists
+ * because prose has to be re-identified after it moves; a key is already the
+ * identifier, so quoting its value would only give an agent a second, staler
+ * copy of something it is about to read anyway.
+ */
+ property: string | null;
+ /**
+ * The anchored passage plus its stored context.
+ *
+ * Null when the comment is on a whole thing — a property with no quoted
+ * passage. Present alongside `property` when the reviewer selected inside a
+ * value, in which case these words are a passage in THAT value, not the body.
+ */
+ passage: { exact: string; prefix: string; suffix: string } | null;
+ /**
+ * The quoted text occurs more than once in the document.
+ *
+ * The agent gets the words, not an offset — offsets shift the moment it makes
+ * its first edit in a batch — so a repeated quote is the one case where the
+ * words alone cannot say which passage was meant. When this is set the client
+ * spells out the surrounding context; when it is not, the extra prose would
+ * only pad the prompt.
+ */
+ passageRepeats: boolean;
+ /**
+ * The passage could not be found in the document's current text.
+ *
+ * A lost anchor no longer blocks dispatch — the payload carries the quoted
+ * words themselves, so the agent is not being pointed at a stale offset, and
+ * it can see for itself what is and is not there. The flag exists so the
+ * composer can say so explicitly: without it, an agent that cannot find the
+ * passage may "fix" a different occurrence, or re-add text a rewrite
+ * deliberately removed. That silent-wrong-target case is the one the
+ * anchoring design exists to prevent, and naming it costs a line of prompt.
+ */
+ anchorLost: boolean;
+}
+
+export interface PrepareDispatchResult {
+ meta: CommentThreadMeta;
+ /** Always present — a lost anchor is sent with `payload.anchorLost` set, not withheld. */
+ payload: DispatchPayload;
+}
+
+/**
+ * One entry of a batch result. Per-item rather than all-or-nothing: a batch
+ * carries ids the user selected earlier, and one that has since been deleted
+ * must not take the rest of the batch down with it: a failure on one item
+ * leaves the others intact and surfaces the failure in that item.
+ */
+export type BatchItem<T> =
+ | ({ threadId: string; ok: true } & T)
+ | { threadId: string; ok: false; error: 'not-found' };
+
+/** Cheap "is this quote ambiguous" test — stops at the second hit. */
+function occursMoreThanOnce(body: string, quote: string): boolean {
+ if (quote === '') return false;
+ const first = body.indexOf(quote);
+ return first !== -1 && body.indexOf(quote, first + 1) !== -1;
+}
+
+export class DocNotFoundError extends Error {}
+export class ThreadNotFoundError extends Error {}
+/** The frontmatter key a property comment names is not in the document. */
+export class PropertyNotFoundError extends Error {}
+/** The quoted passage isn't in the document's body — the caller's selection is stale. */
+export class PassageNotFoundError extends Error {}
+
+export class CommentService {
+ private readonly store: CommentThreadStore;
+ private readonly index: CommentIndex;
+ private readonly getDocBody: GetDocBody;
+ private readonly getDocFrontmatter: GetDocFrontmatter;
+ private readonly now: () => number;
+ private readonly newId: () => string;
+ /** Memoized lazy index build — the first index-touching call scans the cover sheets once. */
+ private indexReady: Promise<void> | null = null;
+
+ constructor(deps: CommentServiceDeps) {
+ this.store = deps.store;
+ this.index = deps.index;
+ this.getDocBody = deps.getDocBody;
+ this.getDocFrontmatter = deps.getDocFrontmatter;
+ this.now = deps.now ?? Date.now;
+ this.newId = deps.newId ?? randomUUID;
+ }
+
+ /**
+ * Build the doc -> threads index from the store's cover sheets, once. Every
+ * index-touching method awaits this first, so the index is correct without a
+ * separate boot step; the scan is memoized so it runs at most once per
+ * process.
+ */
+ buildIndex(): Promise<void> {
+ this.indexReady ??= this.index.build(this.store);
+ return this.indexReady;
+ }
+
+ /**
+ * Create an anchored thread on `[start, end)` of the doc's current body. The
+ * anchor is measured against the live body so the write-time invariant holds
+ * by construction. `body` is the opening comment.
+ */
+ async createThread(input: {
+ docName: string;
+ /**
+ * Where the passage is. Either body offsets (a caller that already measured
+ * against the markdown source, e.g. source mode) or the quoted text itself.
+ *
+ * The rich-text editor only has ProseMirror positions, which are NOT body
+ * offsets — markdown syntax characters and the frontmatter region make the
+ * two coordinate systems disagree. Rather than have every client attempt a
+ * lossy conversion, it sends the words and the server locates them.
+ */
+ start?: number;
+ end?: number;
+ quote?: string;
+ /**
+ * Rendered text around the caller's selection. The one thing that says WHICH
+ * occurrence was meant when the quoted words repeat.
+ */
+ prefix?: string;
+ suffix?: string;
+ /**
+ * The frontmatter key to comment on, instead of a body passage.
+ *
+ * With no `quote`, the comment is on the addressed value as a whole. With
+ * one, it is on that passage INSIDE the value — which is how a
+ * paragraph-length field gets commented a sentence at a time, using the same
+ * anchoring the body uses over a much smaller haystack.
+ */
+ propertyKey?: string;
+ /** Steps into the key's value: `[2]` for the third tag, `['name']` for a field. */
+ propertyPath?: PropertyPath;
+ author: string;
+ body: string;
+ /**
+ * Post straight into the dispatch queue (the queue-first compose flow):
+ * posting a comment adds it to the batch you later send, rather than
+ * dispatching it on its own.
+ */
+ queue?: boolean;
+ }): Promise<CommentThreadMeta> {
+ await this.buildIndex();
+ const propertyKey = input.propertyKey;
+ let target: CommentTarget;
+ let anchor: Anchor | null;
+ if (propertyKey === undefined) {
+ const docBody = await this.requireDocBody(input.docName);
+ const { start, end } = this.resolveRange(docBody, input);
+ target = { kind: 'body' };
+ anchor = createAnchor(docBody, start, end);
+ } else {
+ // An address that isn't there is refused rather than stored orphaned: the
+ // only caller offers this on a row it is currently rendering, so a missing
+ // key means the request and the document disagree — and a thread born
+ // orphaned points at nothing a human ever chose.
+ const path = input.propertyPath ?? [];
+ target = { kind: 'property', key: propertyKey, path };
+ const quote = input.quote?.trim();
+ if (quote === undefined || quote.length === 0) {
+ await this.requirePropertyTarget(input.docName, propertyKey, path);
+ anchor = null;
+ } else {
+ // Anchored inside the value: same `createAnchor` the body uses, with the
+ // value as the haystack, so the offsets it stores index that value and
+ // never the document.
+ const text = await this.requirePropertyText(input.docName, propertyKey, path);
+ const { start, end } = this.resolveRange(text, input);
+ anchor = createAnchor(text, start, end);
+ }
+ }
+ const threadId = this.newId();
+ const ts = this.now();
+ const meta = await this.store.createThread({
+ threadId,
+ docName: input.docName,
+ target,
+ anchor,
+ createdBy: input.author,
+ createdAt: ts,
+ body: input.body,
+ });
+ this.index.upsert(meta);
+ if (input.queue !== true) return meta;
+ // Queue-first compose: the comment joins the batch immediately. No
+ // pre-dispatch re-find here — the anchor was just measured against the live
+ // body, and the re-find that matters runs at `prepareDispatch`.
+ return this.mutate(threadId, { queued: true });
+ }
+
+ /**
+ * Cover sheets for threads. Pass a `docName` for one doc's threads; omit it
+ * for the project-wide view the queue panel renders (comments queued on docs
+ * you don't currently have open).
+ *
+ * Served entirely from the in-memory index — no disk reads. The app refetches
+ * the whole project on every mutation and every push notification, so a
+ * per-thread file read here made one click cost O(every comment ever made).
+ */
+ async listThreads(docName?: string): Promise<CommentThreadMeta[]> {
+ await this.buildIndex();
+ return docName === undefined ? this.index.listAll() : this.index.listForDoc(docName);
+ }
+
+ /**
+ * Unresolved-thread counts, keyed by docName — the read-side signal agents
+ * get through MCP enrichment. Pass `docNames` for an exact set (every name
+ * gets an entry, 0 included) or `prefix` for a folder subtree (sparse — only
+ * docs that carry threads).
+ *
+ * Counts rather than threads because the listing callers are per-file rows,
+ * and shipping every comment body for a 200-file `ls` would dwarf the listing
+ * it annotates. A reader that wants the text asks for the one doc.
+ */
+ async countThreads(
+ scope: { docNames: readonly string[] } | { prefix: string },
+ ): Promise<Map<string, number>> {
+ await this.buildIndex();
+ return 'prefix' in scope
+ ? this.index.countsUnderPrefix(scope.prefix)
+ : this.index.countsForDocs(scope.docNames);
+ }
+
+ /** One thread. */
+ async readThread(threadId: string): Promise<CommentThreadMeta> {
+ return this.requireMeta(threadId);
+ }
+
+ /**
+ * Revise a thread's comment — it replaces the previous text. A thread holds
+ * one comment that can be rewritten, not a discussion: the reader is an
+ * agent, so refining the ask is the move that comes up, not replying.
+ */
+ /**
+ * Revise a thread's comment. Replaces the text — a thread holds one comment
+ * that can be rewritten, not a discussion.
+ *
+ * Takes no author. It used to, back when an append-only event log recorded who
+ * wrote each revision; that log was dropped deliberately (see `types.ts`) and
+ * the parameter outlived it, so callers were handing over attribution this
+ * discarded. The ROUTE still requires a known actor before allowing the edit —
+ * that is an identity gate, not attribution, and nothing here can record it.
+ */
+ async editComment(threadId: string, body: string): Promise<CommentThreadMeta> {
+ return this.mutate(threadId, { latestComment: body });
+ }
+
+ async resolve(threadId: string): Promise<CommentThreadMeta> {
+ return this.mutate(threadId, { state: 'resolved' });
+ }
+
+ /**
+ * Reopen a closed thread. Its anchor state was not preserved under `resolved`
+ * — deliberately, since a closed thread's anchor is moot — so the re-find
+ * immediately re-establishes whether the passage is still there.
+ */
+ async reopen(threadId: string): Promise<CommentThreadMeta> {
+ await this.mutate(threadId, { state: 'anchored' });
+ return this.refindOnLoad(threadId);
+ }
+
+ /**
+ * Human re-placement: re-anchor onto a fresh selection of the current
+ * body and append `anchored` — the thread returns from orphaned.
+ */
+ async replaceAnchor(
+ threadId: string,
+ input: { start?: number; end?: number; quote?: string; prefix?: string; suffix?: string },
+ ): Promise<CommentThreadMeta> {
+ const meta = await this.requireMeta(threadId);
+ // Re-placement moves a comment onto a fresh PASSAGE. A property thread that
+ // lost its key is fixed by restoring the key or deleting the thread, not by
+ // pointing it at prose — which would silently change what it is a comment on.
+ if (meta.target.kind === 'property') {
+ throw new PropertyNotFoundError(meta.target.key);
+ }
+ const docBody = await this.requireDocBody(meta.docName);
+ const { start, end } = this.resolveRange(docBody, input);
+ const anchor = createAnchor(docBody, start, end);
+ return this.mutate(threadId, { anchor, state: 'anchored' });
+ }
+
+ /**
+ * Ask-AI storage side (spec §Dispatch loop step 1): append `queued`, then
+ * re-run re-find. If the anchor is lost the thread stays queued but held —
+ * an `orphaned` event is appended and the caller must NOT start an agent turn
+ * until a human re-places it. The actual agent turn (session correlation +
+ * edit-landing stamp) is the ACP wiring, layered on top of this.
+ */
+ async queueForDispatch(threadId: string, docBody?: string | null): Promise<QueueResult> {
+ await this.mutate(threadId, { queued: true });
+ const state = await this.refindOnLoad(threadId, docBody);
+ return { meta: state, orphaned: state.state === 'orphaned' };
+ }
+
+ /**
+ * "Ask AI", step 1: queue the thread, verify the anchor still resolves, and
+ * hand back what the client needs to deliver it.
+ *
+ * Delivery is the client's job because the target set is the app's, not the
+ * server's — an in-app agent thread, the docked terminal, or a deep link into
+ * an external app. Only the client can reach the latter two, and its Ask-AI
+ * composer already fits a passage to each target's transport and budget.
+ *
+ * A lost anchor does not block the send; it is reported on the payload
+ * (`anchorLost`) so the agent is told the passage is gone rather than left to
+ * guess. The thread's own state still records the loss via the `orphaned`
+ * event, so the UI can still offer re-placement.
+ */
+ async prepareDispatch(threadId: string): Promise<PrepareDispatchResult> {
+ // One document read for the whole call. The pre-dispatch re-find and the
+ // repeated-quote check both want the same body, and a batch runs this
+ // sequentially per thread — two reads apiece is the batch's dominant cost
+ // for information that hasn't changed between them.
+ const docBody = await this.getDocBody((await this.requireMeta(threadId)).docName);
+ const queued = await this.queueForDispatch(threadId, docBody);
+ const { anchor, docName, target } = queued.meta;
+ const instruction = await this.latestComment(threadId);
+ if (target.kind === 'property') {
+ return {
+ meta: queued.meta,
+ payload: {
+ docName,
+ instruction,
+ property: describeTarget(target.key, target.path),
+ passage:
+ anchor === null
+ ? null
+ : { exact: anchor.exact, prefix: anchor.prefix, suffix: anchor.suffix },
+ anchorLost: queued.orphaned,
+ // An address is unique within its frontmatter by construction, and a
+ // quote inside one value has only that value to be confused with — the
+ // client's locating note exists for a document-wide ambiguity that
+ // cannot arise here.
+ passageRepeats: false,
+ },
+ };
+ }
+ return {
+ meta: queued.meta,
+ payload: {
+ docName,
+ instruction,
+ property: null,
+ passage:
+ anchor === null
+ ? null
+ : { exact: anchor.exact, prefix: anchor.prefix, suffix: anchor.suffix },
+ anchorLost: queued.orphaned,
+ passageRepeats:
+ anchor !== null && docBody !== null && occursMoreThanOnce(docBody, anchor.exact),
+ },
+ };
+ }
+
+ /**
+ * "Ask AI", step 2: the client delivered it — close the thread.
+ *
+ * Closing on send (rather than when the agent's edit lands) is a deliberate
+ * product call: the server has no reliable way to recognize *that agent's*
+ * write — an ACP thread and its agent's MCP identity share no join key, and
+ * agents commonly edit through their own file tools, which land with no agent
+ * identity at all. Delivery to a terminal or an external app is one-way in any
+ * case. The accepted tradeoff is that a thread closes even if the agent errors,
+ * declines, or edits nothing; reopening is one click.
+ *
+ * If delivery failed, the client calls `unqueue` instead and the thread stays
+ * open for a retry.
+ */
+ async completeDispatch(threadId: string): Promise<CommentThreadMeta> {
+ return this.mutate(threadId, { queued: false, state: 'resolved' });
+ }
+
+ /**
+ * Batch form of {@link prepareDispatch}: the reviewer selects which
+ * queued comments to send, and the whole selection goes out in one action.
+ *
+ * `ids` order IS the intended run order — nothing stored carries a batch
+ * ordering, so the caller's array is what supplies it and results come back
+ * in the same order. Processed sequentially rather than concurrently so that
+ * order is real.
+ */
+ async prepareDispatchBatch(ids: readonly string[]): Promise<BatchItem<PrepareDispatchResult>[]> {
+ const out: BatchItem<PrepareDispatchResult>[] = [];
+ for (const threadId of ids) {
+ try {
+ const result = await this.prepareDispatch(threadId);
+ out.push({ threadId, ok: true, ...result });
+ } catch (e) {
+ if (e instanceof ThreadNotFoundError) {
+ out.push({ threadId, ok: false, error: 'not-found' });
+ continue;
+ }
+ throw e;
+ }
+ }
+ return out;
+ }
+
+ /** Batch form of {@link completeDispatch}. Same per-item tolerance and ordering. */
+ async completeDispatchBatch(
+ ids: readonly string[],
+ ): Promise<BatchItem<{ meta: CommentThreadMeta }>[]> {
+ const out: BatchItem<{ meta: CommentThreadMeta }>[] = [];
+ for (const threadId of ids) {
+ try {
+ out.push({ threadId, ok: true, meta: await this.completeDispatch(threadId) });
+ } catch (e) {
+ if (e instanceof ThreadNotFoundError) {
+ out.push({ threadId, ok: false, error: 'not-found' });
+ continue;
+ }
+ throw e;
+ }
+ }
+ return out;
+ }
+
+ /**
+ * What the thread is asking for — the live comment, which a reviewer may have
+ * revised since opening it. Threads hold one comment that can be rewritten,
+ * not a discussion, so an edit replaces the text outright and there are no
+ * superseded drafts to pick between.
+ */
+ private async latestComment(threadId: string): Promise<string> {
+ return (await this.requireMeta(threadId)).latestComment.trim();
+ }
+
+ /** Leave the queue without sending (human un-queue, or a concluded dispatch). */
+ async unqueue(threadId: string): Promise<CommentThreadMeta> {
+ return this.mutate(threadId, { queued: false });
+ }
+
+ async delete(threadId: string): Promise<void> {
+ await this.buildIndex();
+ await this.store.delete(threadId);
+ this.index.remove(threadId);
+ }
+
+ /**
+ * Follow a doc rename: re-point every thread on `from` to `to` in the
+ * index and rewrite each affected cover sheet's `docName`. Wired into the
+ * existing rename walk alongside the link/tag index renames. No stable doc id
+ * in v1 — the rename is driven deliberately, name to name.
+ */
+ async renameDoc(from: string, to: string): Promise<void> {
+ if (from === to) return;
+ await this.buildIndex();
+ const threadIds = this.index.threadsForDoc(from);
+ if (threadIds.length === 0) return;
+ this.index.renameDoc(from, to);
+ await Promise.all(threadIds.map((id) => this.store.update(id, { docName: to })));
+ }
+
+ /**
+ * Delete every thread on a doc, because the doc itself is gone. Returns how
+ * many went.
+ *
+ * This is the one place the store destroys a comment the user did not ask it
+ * to — and it is not the system inferring anything. Losing a *passage* is an
+ * inference (the words moved, or we can't find them) and always orphans
+ * rather than deletes. Losing the whole document is a fact.
+ *
+ * Keeping them would preserve nothing reachable: the panel needs the document
+ * open and the queue only lists what is waiting to send, so a thread on a
+ * deleted doc is invisible from every surface while still being sendable —
+ * and a missing document reads as a healthy anchor, so it would go to an agent
+ * claiming nothing was wrong.
+ */
+ async deleteDoc(docName: string): Promise<number> {
+ await this.buildIndex();
+ const threadIds = this.index.threadsForDoc(docName);
+ for (const threadId of threadIds) {
+ await this.store.delete(threadId);
+ this.index.remove(threadId);
+ }
+ return threadIds.length;
+ }
+
+ /**
+ * Re-anchor every open thread on a doc against its settled content, and
+ * report whether any of them changed state.
+ *
+ * Comments are a derived view of document text, like backlinks and tags: a
+ * passage that gets deleted has to read as orphaned, and one that comes back
+ * has to recover. Without this the state only refreshed when a comment was
+ * queued or dispatched, so deleting a commented passage left the comment
+ * looking healthy — its highlight silently gone, the card unchanged — right
+ * up until the moment you tried to send it.
+ *
+ * Cheap by construction on the path that runs constantly: it returns before
+ * touching the document when the doc has no threads, and it writes only when
+ * a thread actually crosses between anchored and orphaned. A passage that
+ * merely moved is left alone — the position is a hint, and re-capturing it
+ * on every settle would mean a write per thread per keystroke burst.
+ */
+ async refindDoc(docName: string): Promise<boolean> {
+ await this.buildIndex();
+ const threads = this.index.listForDoc(docName).filter((m) => m.state !== 'resolved');
+ if (threads.length === 0) return false;
+ const docBody = await this.getDocBody(docName);
+ if (docBody === null) return false;
+ // One read for the whole pass, and only when a property thread is actually
+ // present — this runs on every settle, so the common all-body doc must not
+ // pay for a frontmatter parse it has no use for.
+ const frontmatter = threads.some((m) => m.target.kind === 'property')
+ ? await this.getDocFrontmatter(docName)
+ : null;
+
+ let changed = false;
+ for (const meta of threads) {
+ let state: 'anchored' | 'orphaned';
+ if (meta.target.kind === 'property') {
+ // Unreadable frontmatter is not evidence the address is gone; skip,
+ // exactly as an unreadable body leaves every body thread alone above.
+ const result = await this.refindProperty(docName, meta.target, meta.anchor, frontmatter);
+ if (result === null) continue;
+ state = result.state;
+ } else {
+ // A body thread without an anchor is malformed rather than orphaned —
+ // leave it as it is instead of reporting a loss the document didn't cause.
+ if (meta.anchor === null) continue;
+ state = refind(docBody, meta.anchor).status === 'anchored' ? 'anchored' : 'orphaned';
+ }
+ if (state === meta.state) continue;
+ await this.mutate(meta.threadId, { state });
+ changed = true;
+ }
+ return changed;
+ }
+
+ /**
+ * Re-find a thread's anchor against the current body and reconcile state
+ * (spec §5.2). A routine re-find that only moved the position updates the
+ * cover-sheet hint SILENTLY (no event). Losing the spot appends `orphaned`;
+ * recovering it appends `anchored`. Resolved threads are skipped — their
+ * anchor is moot until reopened. Returns the (possibly updated) cover sheet.
+ */
+ async refindOnLoad(threadId: string, body?: string | null): Promise<CommentThreadMeta> {
+ const meta = await this.requireMeta(threadId);
+ if (meta.state === 'resolved') return meta;
+
+ if (meta.target.kind === 'property') {
+ const result = await this.refindProperty(meta.docName, meta.target, meta.anchor);
+ if (result === null) return meta;
+ // A moved passage inside a value updates its hint silently, exactly as the
+ // body path does — only a crossing between anchored and orphaned is news.
+ if (result.anchor === undefined && result.state === meta.state) return meta;
+ return this.mutate(threadId, {
+ ...(result.anchor ? { anchor: result.anchor } : {}),
+ state: result.state,
+ });
+ }
+
+ // `body` is a document already read by the caller, passed in so a dispatch
+ // doesn't read the same document twice. Tri-state on purpose: `undefined`
+ // means nobody has read it yet, `null` means it was read and is gone.
+ const docBody = body !== undefined ? body : await this.getDocBody(meta.docName);
+ if (docBody === null) return meta; // doc temporarily unavailable — leave state untouched
+
+ // A body thread always carries an anchor; this narrows the nullable field
+ // rather than asserting past it, so a malformed thread is left alone instead
+ // of crashing the settle pass that re-finds every thread in the document.
+ const bodyAnchor = meta.anchor;
+ if (bodyAnchor === null) return meta;
+
+ const result = refind(docBody, bodyAnchor);
+
+ if (result.status === 'orphaned') {
+ return meta.state === 'orphaned' ? meta : this.mutate(threadId, { state: 'orphaned' });
+ }
+
+ // Recovered from its brackets: the passage was EDITED, so the stored quote no
+ // longer matches the document. Re-capture the whole anchor rather than only
+ // the offsets — a stale `exact` would be handed to an agent as the passage
+ // to act on, naming text that is not there any more.
+ const anchor: Anchor | undefined = result.rewritten
+ ? createAnchor(docBody, result.start, result.end)
+ : result.start !== bodyAnchor.start || result.end !== bodyAnchor.end
+ ? // Same words, new position: the cheap hint update.
+ { ...bodyAnchor, start: result.start, end: result.end }
+ : undefined;
+
+ // A routine re-find that only moved the position is silent — the caller
+ // sees a fresh hint, not a state change.
+ if (anchor === undefined && meta.state === 'anchored') return meta;
+ return this.mutate(threadId, { ...(anchor ? { anchor } : {}), state: 'anchored' });
+ }
+
+ /**
+ * Apply a patch and return the updated thread, treating a vanished thread as
+ * the error every caller here already handles.
+ */
+ private async mutate(threadId: string, patch: CommentThreadPatch): Promise<CommentThreadMeta> {
+ const updated = await this.store.update(threadId, patch);
+ if (!updated) throw new ThreadNotFoundError(threadId);
+ // Every write funnels through here, which is what lets the index serve
+ // reads without going back to disk.
+ this.index.upsert(updated);
+ return updated;
+ }
+
+ /**
+ * Resolve a caller's passage reference to body offsets. Explicit offsets win;
+ * otherwise the quote is located in the body — literally first, then treating
+ * the body's markdown syntax as elastic, since the editor's callers only have
+ * the passage as it RENDERS (`bold`, not `**bold**`; a bullet's text without
+ * its `- `).
+ *
+ * A quote occurring more than once is decided by the context the caller
+ * captured around its selection, scored the same way re-find scores its own
+ * stored context. Taking the first occurrence instead would anchor the comment
+ * to a passage nobody selected — and `createAnchor` would then widen the
+ * context around THAT one until it was unambiguous, cementing the wrong
+ * target with no signal that anything went wrong. A caller that sends no
+ * context still lands on the first occurrence; there is nothing better to go on.
+ */
+ private resolveRange(
+ docBody: string,
+ input: { start?: number; end?: number; quote?: string; prefix?: string; suffix?: string },
+ ): { start: number; end: number } {
+ if (input.start !== undefined && input.end !== undefined) {
+ return { start: input.start, end: input.end };
+ }
+ const quote = input.quote?.trim();
+ if (quote === undefined || quote.length === 0) {
+ throw new Error('either start/end offsets or a non-empty quote is required');
+ }
+ const literal = literalSpans(docBody, quote);
+ // The caller's quote is the passage as the editor RENDERS it, so the body's
+ // markdown syntax has to be treated as elastic — see `findAllPassages`.
+ const hits =
+ literal.length > 0 ? literal : findAllPassages(docBody, quote, { syntaxIn: 'haystack' });
+ if (hits.length === 0) throw new PassageNotFoundError(quote);
+ if (hits.length === 1) return hits[0];
+ return bestByContext(docBody, hits, { prefix: input.prefix, suffix: input.suffix })[0];
+ }
+
+ private async requireMeta(threadId: string): Promise<CommentThreadMeta> {
+ const meta = await this.store.readMeta(threadId);
+ if (!meta) throw new ThreadNotFoundError(threadId);
+ return meta;
+ }
+
+ private async requireDocBody(docName: string): Promise<string> {
+ const body = await this.getDocBody(docName);
+ if (body === null) throw new DocNotFoundError(docName);
+ return body;
+ }
+
+ /**
+ * The text a property target's anchor is measured against, for creating one.
+ *
+ * Throws rather than returning null so the create path reports WHICH thing was
+ * missing: an unreadable doc, an address that no longer resolves, or a
+ * container the caller tried to quote into.
+ */
+ private async requirePropertyText(
+ docName: string,
+ key: string,
+ path: PropertyPath,
+ ): Promise<string> {
+ const record = await this.getDocFrontmatter(docName);
+ if (record === null) throw new DocNotFoundError(docName);
+ const value = resolvePropertyPath(record, key, path);
+ if (value === undefined) throw new PropertyNotFoundError(describeTarget(key, path));
+ const text = propertyValueText(value);
+ if (text === null) throw new PropertyNotFoundError(describeTarget(key, path));
+ return text;
+ }
+
+ /** Assert the address resolves, without requiring it to be quotable text. */
+ private async requirePropertyTarget(
+ docName: string,
+ key: string,
+ path: PropertyPath,
+ ): Promise<void> {
+ const record = await this.getDocFrontmatter(docName);
+ if (record === null) throw new DocNotFoundError(docName);
+ if (resolvePropertyPath(record, key, path) === undefined) {
+ throw new PropertyNotFoundError(describeTarget(key, path));
+ }
+ }
+
+ /**
+ * Property re-find: does the address still resolve, and — when the thread
+ * quoted a passage inside it — are those words still in that value?
+ *
+ * Two steps, cheapest first, mirroring the body path's ladder at a much
+ * smaller scale. The address is exact, so step one cannot mis-target; step two
+ * runs the ordinary anchor search over ONE value, where a repeated quote has
+ * far less to be confused with than in a whole document.
+ *
+ * `null` when the document could not be read, which every caller treats as
+ * "leave the state alone" — the same tri-state the body path uses, and for the
+ * same reason: a doc that is momentarily unavailable must not orphan threads.
+ */
+ private async refindProperty(
+ docName: string,
+ target: Extract<CommentTarget, { kind: 'property' }>,
+ anchor: Anchor | null,
+ record?: Record<string, unknown> | null,
+ ): Promise<{ state: 'anchored' | 'orphaned'; anchor?: Anchor } | null> {
+ const fm = record !== undefined ? record : await this.getDocFrontmatter(docName);
+ if (fm === null) return null;
+ const value = resolvePropertyPath(fm, target.key, target.path);
+ if (value === undefined) return { state: 'orphaned' };
+ if (anchor === null) return { state: 'anchored' };
+
+ const text = propertyValueText(value);
+ // The address still resolves but no longer holds text — the field became a
+ // list or a map. The quoted words are not there to be found, and inventing a
+ // serialization to search would anchor into punctuation nobody ever saw.
+ if (text === null) return { state: 'orphaned' };
+
+ const result = refind(text, anchor);
+ if (result.status === 'orphaned') return { state: 'orphaned' };
+ if (result.rewritten) {
+ return { state: 'anchored', anchor: createAnchor(text, result.start, result.end) };
+ }
+ if (result.start !== anchor.start || result.end !== anchor.end) {
+ return { state: 'anchored', anchor: { ...anchor, start: result.start, end: result.end } };
+ }
+ return { state: 'anchored' };
+ }
+}
+
+/** `tags`, `tags[2]`, `author.name` — how a property address reads to a human and an agent. */
+function describeTarget(key: string, path: PropertyPath): string {
+ let out = key;
+ for (const step of path) out += typeof step === 'number' ? `[${step}]` : `.${step}`;
+ return out;
+}
diff --git a/packages/server/src/comments/thread-store.test.ts b/packages/server/src/comments/thread-store.test.ts
new file mode 100644
index 000000000..377249f66
--- /dev/null
+++ b/packages/server/src/comments/thread-store.test.ts
@@ -0,0 +1,163 @@
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
+import { getLogger } from '../logger.ts';
+import { createAnchor } from './anchor.ts';
+import { CommentThreadStore } from './thread-store.ts';
+import { CommentThreadMetaSchema } from './types.ts';
+
+const log = getLogger('comments-store-test');
+
+let dirs: string[] = [];
+function tmp(): string {
+ const d = mkdtempSync(join(tmpdir(), 'comments-store-test-'));
+ dirs.push(d);
+ return d;
+}
+afterEach(() => {
+ for (const d of dirs) rmSync(d, { recursive: true, force: true });
+ dirs = [];
+});
+
+async function makeStore(): Promise<CommentThreadStore> {
+ const store = new CommentThreadStore(tmp(), log);
+ await store.init();
+ return store;
+}
+
+const BODY = 'The rollout is scheduled for Q3. We expect minimal downtime.';
+function anchorFor(quote: string) {
+ const start = BODY.indexOf(quote);
+ return createAnchor(BODY, start, start + quote.length);
+}
+
+async function newThread(store: CommentThreadStore, id = 'thread-1') {
+ return store.createThread({
+ threadId: id,
+ docName: 'notes/rollout',
+ anchor: anchorFor('minimal downtime'),
+ createdBy: 'principal-abc',
+ createdAt: 1000,
+ body: 'is this still true?',
+ });
+}
+
+describe('CommentThreadStore', () => {
+ test('creates a thread carrying its comment, open and unqueued', async () => {
+ const store = await makeStore();
+ const meta = await newThread(store);
+ await store.whenIdle('thread-1');
+
+ expect(() => CommentThreadMetaSchema.parse(meta)).not.toThrow();
+ expect(meta.state).toBe('anchored');
+ expect(meta.queued).toBe(false);
+ expect(meta.docName).toBe('notes/rollout');
+ expect(meta.latestComment).toBe('is this still true?');
+ });
+
+ test('update patches only the named fields and persists the result', async () => {
+ const store = await makeStore();
+ const created = await newThread(store);
+
+ const updated = await store.update('thread-1', { queued: true, state: 'orphaned' });
+ await store.whenIdle('thread-1');
+
+ expect(updated?.queued).toBe(true);
+ expect(updated?.state).toBe('orphaned');
+ // Untouched fields survive the patch.
+ expect(updated?.latestComment).toBe(created.latestComment);
+ expect(updated?.anchor).toEqual(created.anchor);
+ expect(await store.readMeta('thread-1')).toEqual(updated);
+ });
+
+ test('identity fields are not patchable', async () => {
+ // `threadId`, `createdBy` and `createdAt` are the thread's provenance and
+ // exist nowhere else — a patch type that admitted them would let a caller
+ // quietly rewrite who wrote a comment.
+ const store = await makeStore();
+ await newThread(store);
+ // @ts-expect-error createdBy is deliberately outside CommentThreadPatch
+ const updated = await store.update('thread-1', { createdBy: 'principal-someone-else' });
+ expect(updated?.createdBy).toBe('principal-abc');
+ });
+
+ test('update on a missing thread returns null rather than creating one', async () => {
+ const store = await makeStore();
+ expect(await store.update('never-existed', { queued: true })).toBeNull();
+ expect(await store.readMeta('never-existed')).toBeNull();
+ });
+
+ test('concurrent updates to different fields do not lose each other', async () => {
+ // Each update is a read-modify-write. Without the per-thread queue both
+ // would read the same starting thread and the second would clobber the
+ // first's field — the classic lost update.
+ const store = await makeStore();
+ await newThread(store);
+
+ await Promise.all([
+ store.update('thread-1', { queued: true }),
+ store.update('thread-1', { latestComment: 'reworded' }),
+ store.update('thread-1', { state: 'orphaned' }),
+ ]);
+ await store.whenIdle('thread-1');
+
+ const meta = await store.readMeta('thread-1');
+ expect(meta?.queued).toBe(true);
+ expect(meta?.latestComment).toBe('reworded');
+ expect(meta?.state).toBe('orphaned');
+ });
+
+ test('a thread on disk always parses — there is no partial state to read', async () => {
+ // The write is atomic (tmp + rename), so a reader never sees a blend of the
+ // old thread and the new one. This asserts the observable consequence.
+ const store = await makeStore();
+ await newThread(store);
+ for (const patch of [{ queued: true }, { state: 'resolved' as const }, { queued: false }]) {
+ await store.update('thread-1', patch);
+ const raw = readFileSync(store.metaPath('thread-1'), 'utf8');
+ expect(() => CommentThreadMetaSchema.parse(JSON.parse(raw))).not.toThrow();
+ }
+ });
+
+ test('an unreadable thread file is skipped, not crashed on', async () => {
+ const store = await makeStore();
+ await newThread(store, 'thread-1');
+ await newThread(store, 'thread-2');
+ await store.whenIdle('thread-1');
+ await store.whenIdle('thread-2');
+
+ writeFileSync(store.metaPath('broken'), 'not json');
+
+ expect((await store.scanCoverSheets()).map((m) => m.threadId).sort()).toEqual([
+ 'thread-1',
+ 'thread-2',
+ ]);
+ expect(await store.readMeta('broken')).toBeNull();
+ });
+
+ test('a thread whose shape no longer validates is skipped', async () => {
+ const store = await makeStore();
+ await newThread(store);
+ writeFileSync(store.metaPath('thread-1'), JSON.stringify({ threadId: 'thread-1' }));
+ expect(await store.readMeta('thread-1')).toBeNull();
+ });
+
+ test('delete removes the thread', async () => {
+ const store = await makeStore();
+ await newThread(store);
+ await store.whenIdle('thread-1');
+ await store.delete('thread-1');
+ expect(await store.readMeta('thread-1')).toBeNull();
+ expect(await store.scanCoverSheets()).toEqual([]);
+ });
+
+ test('is written as pretty JSON that parses back', async () => {
+ const store = await makeStore();
+ await newThread(store);
+ await store.whenIdle('thread-1');
+ const raw = readFileSync(store.metaPath('thread-1'), 'utf8');
+ expect(raw).toContain('\n');
+ expect(() => CommentThreadMetaSchema.parse(JSON.parse(raw))).not.toThrow();
+ });
+});
diff --git a/packages/server/src/comments/thread-store.ts b/packages/server/src/comments/thread-store.ts
new file mode 100644
index 000000000..887bd37e1
--- /dev/null
+++ b/packages/server/src/comments/thread-store.ts
@@ -0,0 +1,223 @@
+/**
+ * Durable comment-thread storage — `<localDir>/comments/`, machine-local and
+ * never committed (thread text can quote document content; same trust envelope
+ * as the ACP thread store).
+ *
+ * <threadId>.meta.json the whole thread
+ *
+ * Writes are serialized per thread through a promise chain, so a read-modify-
+ * write can't interleave with another one, and each write lands atomically
+ * (tmp + rename). Together that means a thread on disk is always a complete
+ * thread: the previous one or the next one, never a blend of the two.
+ *
+ * A crash therefore costs at most the transition being written — a resolve that
+ * didn't stick — and never the thread itself. That matters because a thread's
+ * identity (`docName`, `anchor`, `createdBy`, `createdAt`) exists only here and
+ * cannot be reconstructed from anything else.
+ */
+
+import { readdir, readFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { atomicWriteFile } from '@inkeep/open-knowledge-core/server';
+import { tracedAtomicFs, tracedMkdir, tracedRm } from '../fs-traced.ts';
+import type { PinoLogger } from '../logger.ts';
+import {
+ type Anchor,
+ type CommentTarget,
+ type CommentThreadMeta,
+ CommentThreadMetaSchema,
+ type CommentThreadPatch,
+} from './types.ts';
+
+const COMMENTS_SUBDIR = 'comments';
+
+export interface CreateThreadInput {
+ threadId: string;
+ docName: string;
+ target: CommentTarget;
+ /** Null for a property target, which is located by key name rather than words. */
+ anchor: Anchor | null;
+ createdBy: string;
+ createdAt: number;
+ /** The opening comment. */
+ body: string;
+}
+
+export class CommentThreadStore {
+ private readonly dir: string;
+ private readonly log: PinoLogger;
+ /** Per-thread write chains, so a read-modify-write can't interleave. */
+ private readonly writeQueues = new Map<string, Promise<void>>();
+ /** Memoized directory creation — every write path awaits this, so boot order can't race. */
+ private dirReady: Promise<void> | null = null;
+
+ constructor(localDir: string, log: PinoLogger) {
+ this.dir = join(localDir, COMMENTS_SUBDIR);
+ this.log = log;
+ }
+
+ init(): Promise<void> {
+ return this.ensureDir();
+ }
+
+ private ensureDir(): Promise<void> {
+ this.dirReady ??= tracedMkdir(this.dir, { recursive: true }).then(() => undefined);
+ return this.dirReady;
+ }
+
+ metaPath(threadId: string): string {
+ return join(this.dir, `${threadId}.meta.json`);
+ }
+
+ /**
+ * Serialize a write task behind the thread's pending writes and resolve with
+ * its result. Callers enter this queue SYNCHRONOUSLY (no await before the
+ * call) so queue order is call order — see {@link update}.
+ */
+ private enqueueResult<T>(threadId: string, task: () => Promise<T>): Promise<T> {
+ const prev = this.writeQueues.get(threadId) ?? Promise.resolve();
+ const run = prev.then(() => task());
+ this.writeQueues.set(
+ threadId,
+ run.then(
+ () => undefined,
+ () => undefined,
+ ),
+ );
+ return run;
+ }
+
+ /** Resolve once every queued write for the thread has hit disk. */
+ async whenIdle(threadId: string): Promise<void> {
+ await (this.writeQueues.get(threadId) ?? Promise.resolve());
+ }
+
+ /** Create a thread: open, anchored, not queued, carrying its opening comment. */
+ createThread(input: CreateThreadInput): Promise<CommentThreadMeta> {
+ const meta: CommentThreadMeta = CommentThreadMetaSchema.parse({
+ threadId: input.threadId,
+ docName: input.docName,
+ target: input.target,
+ anchor: input.anchor,
+ state: 'anchored',
+ queued: false,
+ latestComment: input.body,
+ createdBy: input.createdBy,
+ createdAt: input.createdAt,
+ });
+ return this.enqueueResult(input.threadId, async () => {
+ await this.ensureDir();
+ await this.write(meta);
+ return meta;
+ });
+ }
+
+ /**
+ * Apply a patch to a thread and persist it. Returns the updated thread, or
+ * null if it is gone.
+ *
+ * Enters the per-thread write queue SYNCHRONOUSLY: the read, the merge, and
+ * the write all happen inside the queued task, so two concurrent updates
+ * cannot both read the same starting state and have the second overwrite the
+ * first's field.
+ */
+ update(threadId: string, patch: CommentThreadPatch): Promise<CommentThreadMeta | null> {
+ return this.enqueueResult(threadId, async () => {
+ await this.ensureDir();
+ const meta = await this.readMeta(threadId);
+ if (!meta) return null;
+ const updated = CommentThreadMetaSchema.parse({ ...meta, ...patchable(patch) });
+ await this.write(updated);
+ return updated;
+ });
+ }
+
+ private write(meta: CommentThreadMeta): Promise<void> {
+ return atomicWriteFile(this.metaPath(meta.threadId), serialize(meta), { fs: tracedAtomicFs });
+ }
+
+ /** Read one thread, or null if absent/unreadable/invalid. */
+ async readMeta(threadId: string): Promise<CommentThreadMeta | null> {
+ let raw: string;
+ try {
+ raw = await readFile(this.metaPath(threadId), 'utf8');
+ } catch {
+ return null;
+ }
+ const result = CommentThreadMetaSchema.safeParse(safeJson(raw));
+ if (!result.success) {
+ this.log.warn({ threadId }, '[comments] skipping unreadable thread meta');
+ return null;
+ }
+ return result.data;
+ }
+
+ /**
+ * Every thread on disk. This is what the boot index consumes; the cost is
+ * O(#threads) small-file reads and nothing more.
+ */
+ async scanCoverSheets(): Promise<CommentThreadMeta[]> {
+ let names: string[];
+ try {
+ names = await readdir(this.dir);
+ } catch {
+ return [];
+ }
+ const metas: CommentThreadMeta[] = [];
+ for (const name of names) {
+ if (!name.endsWith('.meta.json')) continue;
+ const meta = await this.readMeta(name.slice(0, -'.meta.json'.length));
+ if (meta) metas.push(meta);
+ }
+ return metas;
+ }
+
+ async delete(threadId: string): Promise<void> {
+ // ENQUEUED, not jumped ahead of. Dropping the queue entry and unlinking
+ // immediately let a write that was already in flight finish afterwards and
+ // recreate the thread that had just been deleted — serializing behind the
+ // pending writes is the entire point of the per-thread chain.
+ //
+ // The map entry is deliberately left behind (holding a settled promise):
+ // removing it here would let the NEXT enqueue for this id start a second,
+ // parallel chain while an earlier one was still running.
+ await this.enqueueResult(threadId, async () => {
+ await tracedRm(this.metaPath(threadId), { force: true });
+ // Threads written before the event log was dropped still have one sitting
+ // beside them. Nothing reads it, but leaving it behind on delete would
+ // keep a deleted thread's text on disk indefinitely.
+ await tracedRm(join(this.dir, `${threadId}.ndjson`), { force: true });
+ });
+ }
+}
+
+/**
+ * Keep only the fields a patch is allowed to touch, by naming them.
+ *
+ * The patch TYPE already excludes identity, but a type is a compile-time
+ * promise and this data is the one place a thread's provenance exists. Picking
+ * explicitly means a caller cannot rewrite who wrote a comment or when, whether
+ * by mistake or through an `as` cast.
+ */
+function patchable(patch: CommentThreadPatch): CommentThreadPatch {
+ const { docName, anchor, state, queued, latestComment } = patch;
+ return {
+ ...(docName !== undefined && { docName }),
+ ...(anchor !== undefined && { anchor }),
+ ...(state !== undefined && { state }),
+ ...(queued !== undefined && { queued }),
+ ...(latestComment !== undefined && { latestComment }),
+ };
+}
+
+function serialize(value: unknown): string {
+ return `${JSON.stringify(value, null, 1)}\n`;
+}
+
+function safeJson(text: string): unknown {
+ try {
+ return JSON.parse(text);
+ } catch {
+ return undefined;
+ }
+}
diff --git a/packages/server/src/comments/types.ts b/packages/server/src/comments/types.ts
new file mode 100644
index 000000000..57a233424
--- /dev/null
+++ b/packages/server/src/comments/types.ts
@@ -0,0 +1,47 @@
+/**
+ * Comment-thread data model — one file per thread under `<localDir>/comments/`:
+ *
+ * <threadId>.meta.json the whole thread — id, doc, anchor, current state,
+ * and the comment text.
+ *
+ * One file, written atomically, so a thread is always either its previous
+ * complete state or its next one. There is no second file to disagree with it
+ * and therefore nothing to reconcile: a crash mid-write loses the transition
+ * being written, never the thread.
+ *
+ * This deliberately drops the append-only event log the first cut carried. The
+ * log recorded every transition and every superseded draft, and nothing read
+ * any of it — the UI shows a thread's current request, never its history. What
+ * it bought was the option to add replies or agent-authored comments as new
+ * line forms rather than a schema change. That option is cheaper to buy later
+ * (this data is machine-local, gitignored, and disposable) than to carry in
+ * every write now.
+ *
+ * There is deliberately no schema-version field. A shape change already fails
+ * validation, and an unreadable thread is skipped rather than migrated, so a
+ * version literal added no detection — only the risk that a build reading a
+ * newer build's files (beta and stable share `<localDir>` on one machine) would
+ * treat every thread as garbage. Zod strips unknown keys, so the `version: 1`
+ * that older threads carry parses fine and disappears on the next write.
+ */
+
+/**
+ * The thread shape itself lives in `@inkeep/open-knowledge-core`, because the
+ * app consumes these same objects over `/api/comments` and used to keep a
+ * hand-written copy in step by hand. Re-exported here so this module stays the
+ * one import site for everything thread-shaped on the server.
+ */
+import type { CommentThreadMeta } from '@inkeep/open-knowledge-core';
+
+export {
+ type Anchor,
+ type CommentTarget,
+ type CommentThreadMeta,
+ CommentThreadMetaSchema,
+ type PropertyPath,
+} from '@inkeep/open-knowledge-core';
+
+/** The fields a caller may change. Identity and provenance are not among them. */
+export type CommentThreadPatch = Partial<
+ Pick<CommentThreadMeta, 'docName' | 'anchor' | 'state' | 'queued' | 'latestComment'>
+>;
diff --git a/packages/server/src/content/enrichment.test.ts b/packages/server/src/content/enrichment.test.ts
index 9aabd11ba..facf82d3d 100644
--- a/packages/server/src/content/enrichment.test.ts
+++ b/packages/server/src/content/enrichment.test.ts
@@ -5,7 +5,12 @@ import { resolve } from 'node:path';
import { commitWip, initShadowRepo, type WriterIdentity } from '@inkeep/open-knowledge-server';
import simpleGit from 'simple-git';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
-import { computeGraphRole, enrichDirectory, enrichPath } from './enrichment.ts';
+import {
+ computeGraphRole,
+ enrichDirectory,
+ enrichPath,
+ parseCommentThreads,
+} from './enrichment.ts';
let tmpDir: string;
@@ -367,3 +372,76 @@ describe('schemas_applicable — read-time schema advertisement', () => {
expect(meta.schemas_applicable).toEqual(['.ok/schemas/doc.schema.json']);
});
});
+
+/**
+ * The comment parser is the boundary between the comment store's wire shape and
+ * what an agent reads. The fixtures are `CommentThreadMeta` rows exactly as
+ * `GET /api/comments` serves them, so the field names this depends on
+ * (`latestComment`, `anchor.exact`, `state`, `queued`) are pinned against the
+ * real contract rather than assumed — rename one in `comments/types.ts` and
+ * these fail, instead of every read quietly reporting docs as comment-free.
+ */
+describe('parseCommentThreads', () => {
+ /** One row as the comment API serves it. */
+ const wireThread = (overrides: Record<string, unknown> = {}): Record<string, unknown> => ({
+ threadId: 't1',
+ docName: 'notes/rollout',
+ anchor: { exact: 'minimal downtime', prefix: 'with ', suffix: '.', start: 10, end: 26 },
+ state: 'anchored',
+ queued: false,
+ latestComment: 'still accurate?',
+ createdBy: 'principal-x',
+ createdAt: 1,
+ ...overrides,
+ });
+
+ test('lifts the ask and the anchored passage', () => {
+ expect(parseCommentThreads([wireThread()])).toEqual([
+ {
+ threadId: 't1',
+ body: 'still accurate?',
+ quote: 'minimal downtime',
+ state: 'anchored',
+ queued: false,
+ },
+ ]);
+ });
+
+ test('keeps orphaned threads, drops resolved ones', () => {
+ // An orphan is the case a reader most needs — the request stands, the quote
+ // can no longer be trusted. A resolved thread is settled work.
+ expect(parseCommentThreads([wireThread({ state: 'orphaned' })])[0]?.state).toBe('orphaned');
+ expect(parseCommentThreads([wireThread({ state: 'resolved' })])).toEqual([]);
+ });
+
+ test('carries the queued flag — staged to send, still outstanding', () => {
+ // Sending auto-resolves a thread, so `queued` only ever means "a human
+ // staged this and has not sent it". It must survive the parse, or a reader
+ // loses the fact that a request is already on its way.
+ expect(parseCommentThreads([wireThread({ queued: true })])[0]?.queued).toBe(true);
+ });
+
+ test('skips malformed rows without blanking the rest', () => {
+ // One bad row must not cost a doc its whole comment signal; the failure
+ // mode is an agent editing over a request it was never shown.
+ const parsed = parseCommentThreads([
+ null,
+ 'nonsense',
+ wireThread({ threadId: '' }),
+ wireThread({ state: 'unheard-of' }),
+ wireThread({ threadId: 'good' }),
+ ]);
+ expect(parsed.map((c) => c.threadId)).toEqual(['good']);
+ });
+
+ test('tolerates a missing anchor or non-string body', () => {
+ expect(parseCommentThreads([wireThread({ anchor: undefined, latestComment: 7 })])).toEqual([
+ { threadId: 't1', body: '', quote: '', state: 'anchored', queued: false },
+ ]);
+ });
+
+ test('a non-array payload is no comments, not a crash', () => {
+ expect(parseCommentThreads(undefined)).toEqual([]);
+ expect(parseCommentThreads({ threads: [] })).toEqual([]);
+ });
+});
diff --git a/packages/server/src/content/enrichment.ts b/packages/server/src/content/enrichment.ts
index 083ffb4b7..f8789dbdc 100644
--- a/packages/server/src/content/enrichment.ts
+++ b/packages/server/src/content/enrichment.ts
@@ -55,6 +55,26 @@ interface BacklinkEntry {
snippet?: string | null;
}
+/**
+ * One unresolved comment thread on a doc, as rich enrichment surfaces it.
+ *
+ * `orphaned` says the quoted passage is gone, so the reader re-locates rather
+ * than trusting the quote. `queued` says the human staged this to send but has
+ * not sent it — sending auto-resolves a thread (`completeDispatch` writes
+ * `{ queued: false, state: 'resolved' }`) and resolved threads never reach this
+ * shape, so a queued comment is one nobody has been handed yet.
+ */
+interface CommentSummary {
+ threadId: string;
+ /** What the reviewer asked for. */
+ body: string;
+ /** The anchored passage — content-addressed, never an offset. */
+ quote: string;
+ state: 'anchored' | 'orphaned';
+ /** Staged in the dispatch queue, not yet sent to anyone. */
+ queued: boolean;
+}
+
interface DocumentForwardLinkEntry {
kind: 'doc';
docName: string;
@@ -120,6 +140,24 @@ export interface DirectoryMeta {
};
/** `true` when the recursive scan hit `DIRECTORY_SCAN_CAP`. */
truncated: boolean;
+ /**
+ * Unresolved comment threads anywhere under this folder — recursive, like
+ * `recursiveMdCount`, so a folder row answers "is there review waiting in
+ * here" without opening anything.
+ *
+ * Absent (not `0`) when there is no server to ask or the folder is clean:
+ * `DirectoryMeta` omits keys it has nothing to say about, matching `title` /
+ * `description` / `tags`. Unbounded by `DIRECTORY_SCAN_CAP` — it comes from
+ * the comment index, not the directory walk, so a truncated scan still
+ * reports the true count.
+ */
+ commentCount?: number;
+ /**
+ * Which docs the count came from, most-commented first, capped — enough to
+ * navigate straight to the file that needs attention instead of re-listing
+ * the folder. Absent whenever `commentCount` is.
+ */
+ commentedDocs?: { docName: string; count: number }[];
/**
* Templates available when creating a new doc inside this folder. Aggregated
* leaf → root walk-up (closest-wins on filename collision). Empty array
@@ -226,6 +264,22 @@ export interface EnrichedMeta {
* multi-path output, where the counts are not fully resolved.
*/
graphRole: GraphRole | null;
+ /**
+ * Unresolved comment threads on this doc — review requests a human left that
+ * nobody has acted on. Null when Hocuspocus is unreachable (unknown), `0`
+ * when the doc is genuinely clean.
+ *
+ * Populated on both slim and rich enrichment: knowing a file you are about to
+ * edit carries an outstanding request matters as much in a listing as in a
+ * read, and the count comes from one batched call for the whole listing.
+ */
+ commentCount: number | null;
+ /**
+ * The threads themselves. Null on multi-path output (a 200-file listing must
+ * not carry 200 comment bodies) or when Hocuspocus is unreachable; populated
+ * on single-path rich enrichment, where the agent is about to act on the doc.
+ */
+ comments: CommentSummary[] | null;
/**
* Frontmatter schema files governing this doc, resolved server-side via the
* enabled frontmatter plugin's `appliesTo` mappings. Absent when the plugin
@@ -413,6 +467,55 @@ async function fetchBacklinks(
return entries;
}
+/**
+ * Unresolved comment threads on one doc (rich enrichment). Null when there is
+ * no server to ask or the request fails — `[]` is the positive "nobody has an
+ * outstanding request on this doc" answer, so the two must stay distinct.
+ *
+ * Resolved threads are filtered server-side; the `state` filter here is the
+ * belt-and-braces half, since a stale build could serve them.
+ */
+async function fetchComments(
+ serverUrl: string | undefined,
+ docName: string,
+): Promise<CommentSummary[] | null> {
+ if (!serverUrl) return null;
+ const result = await httpGet(serverUrl, `/api/comments?doc=${encodeURIComponent(docName)}`);
+ if (!result.ok) return null;
+ return parseCommentThreads(result.threads);
+}
+
+/**
+ * `CommentThreadMeta` wire rows → the summary shape enrichment surfaces.
+ * Tolerant per element like the link parsers: one malformed thread must not
+ * blank a doc's whole comment signal.
+ *
+ * Resolved threads drop out here as well as server-side — this parser is the
+ * boundary the read surfaces trust, and a stale peer serving them must not put
+ * settled work back in front of an agent.
+ */
+export function parseCommentThreads(raw: unknown): CommentSummary[] {
+ if (!Array.isArray(raw)) return [];
+ const entries: CommentSummary[] = [];
+ for (const item of raw) {
+ if (typeof item !== 'object' || item === null) continue;
+ const rec = item as Record<string, unknown>;
+ const state = rec.state;
+ if (state !== 'anchored' && state !== 'orphaned') continue;
+ if (typeof rec.threadId !== 'string' || rec.threadId === '') continue;
+ const anchor = typeof rec.anchor === 'object' && rec.anchor !== null ? rec.anchor : {};
+ const quote = (anchor as Record<string, unknown>).exact;
+ entries.push({
+ threadId: rec.threadId,
+ body: typeof rec.latestComment === 'string' ? rec.latestComment : '',
+ quote: typeof quote === 'string' ? quote : '',
+ state,
+ queued: rec.queued === true,
+ });
+ }
+ return entries;
+}
+
/**
* Chunk size for bulk backlink-count fetches. Keeps each URL comfortably
* under typical 8KB HTTP URL limits even with long docNames (e.g. 100 x
@@ -461,6 +564,68 @@ export async function fetchBacklinkCountsBatch(
return anySuccess ? out : null;
}
+/**
+ * Bulk unresolved-comment-count fetch — the listing counterpart to
+ * {@link fetchComments}' single-doc read. Shares
+ * `fetchBacklinkCountsBatch`'s chunking and partial-merge contract; see there
+ * for the URL-length rationale.
+ *
+ * Unlike backlink counts this is also used for the slim path of a MULTI-file
+ * `cat`, so a two-file read still reports outstanding requests on both.
+ */
+export async function fetchCommentCountsBatch(
+ serverUrl: string | undefined,
+ docNames: string[],
+): Promise<Map<string, number> | null> {
+ if (!serverUrl || docNames.length === 0) return null;
+ const unique = [...new Set(docNames)];
+ const chunks: string[][] = [];
+ for (let i = 0; i < unique.length; i += BACKLINK_COUNT_CHUNK) {
+ chunks.push(unique.slice(i, i + BACKLINK_COUNT_CHUNK));
+ }
+ const results = await Promise.all(
+ chunks.map(async (chunk) => {
+ const param = encodeURIComponent(chunk.join(','));
+ const result = await httpGet(serverUrl, `/api/comment-counts?docNames=${param}`);
+ if (!result.ok) return null;
+ return (result.counts ?? {}) as Record<string, unknown>;
+ }),
+ );
+ return mergeCountChunks(results);
+}
+
+/**
+ * Unresolved-comment counts for every doc under a folder, in one request — the
+ * `ls` rollup. Returns the per-doc map rather than a total so the caller can
+ * both sum it and name the docs; empty map means a clean subtree.
+ */
+async function fetchCommentCountsUnderPrefix(
+ serverUrl: string | undefined,
+ prefix: string,
+): Promise<Map<string, number> | null> {
+ if (!serverUrl) return null;
+ const result = await httpGet(
+ serverUrl,
+ `/api/comment-counts?prefix=${encodeURIComponent(prefix)}`,
+ );
+ if (!result.ok) return null;
+ return mergeCountChunks([(result.counts ?? {}) as Record<string, unknown>]);
+}
+
+/** Merge count chunks, dropping non-numeric values. Null when every chunk failed. */
+function mergeCountChunks(chunks: (Record<string, unknown> | null)[]): Map<string, number> | null {
+ const out = new Map<string, number>();
+ let anySuccess = false;
+ for (const chunk of chunks) {
+ if (!chunk) continue;
+ anySuccess = true;
+ for (const [name, val] of Object.entries(chunk)) {
+ if (typeof val === 'number' && Number.isFinite(val)) out.set(name, val);
+ }
+ }
+ return anySuccess ? out : null;
+}
+
async function fetchForwardLinks(
serverUrl: string | undefined,
docName: string,
@@ -569,12 +734,17 @@ export async function enrichPath(
projectHistory: null,
projectHistorySource: null,
graphRole: null,
+ // Slim callers backfill this from one batched request for the whole
+ // listing (see `fetchCommentCountsBatch`) — per-path here would be the
+ // N-amplification the slim mode exists to avoid.
+ commentCount: null,
+ comments: null,
...schemasField,
};
}
- // Rich mode — fan out all five data sources in parallel.
- const [fm, backlinks, forwardLinks, shadow, project] = await Promise.all([
+ // Rich mode — fan out all six data sources in parallel.
+ const [fm, backlinks, forwardLinks, shadow, project, comments] = await Promise.all([
fmPromise,
fetchBacklinks(deps.serverUrl, pathToDocName(relPath)).catch(() => null),
fetchForwardLinks(deps.serverUrl, pathToDocName(relPath)).catch(() => null),
@@ -586,6 +756,7 @@ export async function enrichPath(
commits: [] as GitCommit[],
source: 'git' as ProjectHistorySource,
})),
+ fetchComments(deps.serverUrl, pathToDocName(relPath)).catch(() => null),
]);
const lifted = liftOwnFrontmatter(fm);
@@ -604,6 +775,8 @@ export async function enrichPath(
projectHistory: project.commits,
projectHistorySource: project.source,
graphRole: computeGraphRole(backlinks?.length ?? null, forwardLinks?.length ?? null),
+ commentCount: comments?.length ?? null,
+ comments,
...schemasField,
};
}
@@ -686,7 +859,7 @@ async function scanDirectory(absDir: string, projectDir: string): Promise<DirSca
*/
export async function enrichDirectory(
relPathInput: string,
- deps: Pick<EnrichPathDeps, 'projectDir' | 'contentDir' | 'frontmatterSchemas'>,
+ deps: Pick<EnrichPathDeps, 'projectDir' | 'contentDir' | 'frontmatterSchemas' | 'serverUrl'>,
): Promise<DirectoryMeta> {
// See `enrichPath` for the rationale — same `..`/absolute-path escape
// class via `node:fs`-direct readdir / stat.
@@ -739,9 +912,31 @@ export async function enrichDirectory(
const folderSchemas = schemasApplicableToFolder(deps, relPath);
if (folderSchemas.length > 0) result.schemas_applicable = folderSchemas;
+ // One prefix query for the whole subtree, not one per file — the count is
+ // read off the in-memory comment index, so depth costs nothing here.
+ const commentCounts = await fetchCommentCountsUnderPrefix(deps.serverUrl, relPath).catch(
+ () => null,
+ );
+ if (commentCounts && commentCounts.size > 0) {
+ let total = 0;
+ for (const count of commentCounts.values()) total += count;
+ result.commentCount = total;
+ result.commentedDocs = [...commentCounts]
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
+ .slice(0, FOLDER_COMMENTED_DOCS_CAP)
+ .map(([docName, count]) => ({ docName, count }));
+ }
+
return result;
}
+/**
+ * Cap on `commentedDocs`. The field is a pointer to where to look, not a
+ * report — `commentCount` already carries the true total, and an `ls` row that
+ * lists forty filenames stops being a row.
+ */
+const FOLDER_COMMENTED_DOCS_CAP = 5;
+
/**
* Recursively enrich a directory + its subfolders up to `depth` levels.
*
@@ -755,7 +950,7 @@ export async function enrichDirectory(
export async function enrichDirectoryRecursive(
relPathInput: string,
depth: number,
- deps: Pick<EnrichPathDeps, 'projectDir' | 'contentDir' | 'frontmatterSchemas'>,
+ deps: Pick<EnrichPathDeps, 'projectDir' | 'contentDir' | 'frontmatterSchemas' | 'serverUrl'>,
): Promise<DirectoryMeta> {
const top = await enrichDirectory(relPathInput, deps);
if (depth <= 1) return top;
diff --git a/packages/server/src/live-derived-index.ts b/packages/server/src/live-derived-index.ts
index 501c2c6ba..4962582c5 100644
--- a/packages/server/src/live-derived-index.ts
+++ b/packages/server/src/live-derived-index.ts
@@ -7,6 +7,17 @@ export const LIVE_DERIVED_INDEX_DEBOUNCE_MS = 100;
export interface LiveDerivedIndexOptions {
derivedDocumentIndex: DerivedDocumentIndexLivePort;
+ /**
+ * Optional. Re-anchors the doc's comment threads against its settled text, so
+ * a deleted passage reads as orphaned instead of staying healthy-looking
+ * until someone tries to send it.
+ *
+ * A callback rather than a direct dependency because the comment service is
+ * built inside the API extension, which is constructed after this one. It
+ * owns its own signalling — a state change is what warrants telling clients,
+ * and only it knows whether one happened.
+ */
+ onDocumentSettled?: (docName: string) => void;
debounceMs?: number;
}
@@ -32,7 +43,11 @@ function serializeLiveDocument(document: Document): string {
}
export function createLiveDerivedIndexExtension(options: LiveDerivedIndexOptions): Extension {
- const { derivedDocumentIndex, debounceMs = LIVE_DERIVED_INDEX_DEBOUNCE_MS } = options;
+ const {
+ derivedDocumentIndex,
+ onDocumentSettled,
+ debounceMs = LIVE_DERIVED_INDEX_DEBOUNCE_MS,
+ } = options;
const pendingByDoc = new Map<string, ReturnType<typeof setTimeout>>();
function clearPending(docName: string): void {
@@ -57,6 +72,10 @@ export function createLiveDerivedIndexExtension(options: LiveDerivedIndexOptions
`Failed to update derived views for ${docName}`,
);
});
+ // Anchors are measured against the doc BODY, not the source bytes
+ // above — so this re-reads rather than reusing `markdown`, which
+ // still carries the frontmatter region.
+ onDocumentSettled?.(docName);
} catch (err) {
getLogger('live-derived-index').error(
{ docName, err },
diff --git a/packages/server/src/mcp/tools/exec.test.ts b/packages/server/src/mcp/tools/exec.test.ts
index 5a8f1aa4a..02ad81dea 100644
--- a/packages/server/src/mcp/tools/exec.test.ts
+++ b/packages/server/src/mcp/tools/exec.test.ts
@@ -6,11 +6,12 @@ import { commitWip, initShadowRepo, type WriterIdentity } from '@inkeep/open-kno
import simpleGit from 'simple-git';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { type Config, ConfigSchema } from '../../config/schema.ts';
-import type { EnrichedMeta } from '../../content/enrichment.ts';
+import type { DirectoryMeta, EnrichedMeta } from '../../content/enrichment.ts';
import {
buildExecResult,
DESCRIPTION,
type ExecStructuredResult,
+ formatDirectoryEntry,
formatFileEntry,
RESULT_BODY_BUDGET_BYTES,
WIRE_BODY_COPIES,
@@ -932,6 +933,8 @@ describe('formatFileEntry rendering', () => {
projectHistory: null,
projectHistorySource: null,
graphRole: 'hub',
+ commentCount: null,
+ comments: null,
});
expect(line).toContain('graph: hub');
expect(line).toContain('status: canonical');
@@ -956,6 +959,8 @@ describe('formatFileEntry rendering', () => {
projectHistory: null,
projectHistorySource: null,
graphRole: null,
+ commentCount: null,
+ comments: null,
});
expect(line).toContain('backlinks: 2 (login.md, sessions.md)');
expect(line).toContain('forward links: 1 (tokens.md)');
@@ -976,6 +981,8 @@ describe('formatFileEntry rendering', () => {
projectHistory: null,
projectHistorySource: null,
graphRole: null,
+ commentCount: null,
+ comments: null,
});
expect(line).not.toContain('graph:');
});
@@ -999,6 +1006,8 @@ describe('formatFileEntry rendering', () => {
projectHistory: null,
projectHistorySource: null,
graphRole: null,
+ commentCount: null,
+ comments: null,
});
expect(line).toContain('backlinks: 7 (src1.md, src2.md, src3.md, src4.md, src5.md, …)');
expect(line).toContain('forward links: 7 (dst1.md, dst2.md, dst3.md, dst4.md, dst5.md, …)');
@@ -1019,11 +1028,153 @@ describe('formatFileEntry rendering', () => {
projectHistory: null,
projectHistorySource: null,
graphRole: null,
+ commentCount: null,
+ comments: null,
});
expect(line).toContain('forward links: 1 (https://example.com)');
});
});
+/**
+ * Unresolved comments on the text channel.
+ *
+ * The structured field alone is not enough — several MCP hosts surface only
+ * `content[].text`, so a comment an agent never sees is a comment that gets
+ * silently edited over. These pin what that line says and, as importantly,
+ * when it says nothing.
+ */
+describe('formatFileEntry — unresolved comments', () => {
+ const base: EnrichedMeta = {
+ path: 'architecture/auth.md',
+ title: 'Authentication',
+ tags: [],
+ frontmatter: {},
+ backlinkCount: null,
+ backlinks: null,
+ forwardLinkCount: null,
+ forwardLinks: null,
+ history: null,
+ historySource: null,
+ projectHistory: null,
+ projectHistorySource: null,
+ graphRole: null,
+ commentCount: null,
+ comments: null,
+ };
+
+ test('a listing entry reports the count alone', () => {
+ // Slim enrichment has the count and not the bodies — a 200-file `ls` must
+ // not carry 200 comment texts.
+ const line = formatFileEntry({ ...base, commentCount: 2 });
+ expect(line).toContain('2 unresolved comments');
+ expect(line).toContain('⚠');
+ });
+
+ test('a single-file read inlines the ask and the passage', () => {
+ const line = formatFileEntry({
+ ...base,
+ commentCount: 1,
+ comments: [
+ {
+ threadId: 'c1',
+ body: 'tighten this claim',
+ quote: 'always converges',
+ state: 'anchored',
+ queued: false,
+ },
+ ],
+ });
+ expect(line).toContain('1 unresolved comment:');
+ expect(line).toContain('"tighten this claim"');
+ expect(line).toContain('always converges');
+ });
+
+ test('marks queued and orphaned threads', () => {
+ // `queued` = staged to send, not yet sent (a sent comment resolves and
+ // never reaches a read); `passage gone` says do not trust the quote.
+ const line = formatFileEntry({
+ ...base,
+ commentCount: 2,
+ comments: [
+ { threadId: 'c1', body: 'a', quote: 'x', state: 'anchored', queued: true },
+ { threadId: 'c2', body: 'b', quote: 'y', state: 'orphaned', queued: false },
+ ],
+ });
+ expect(line).toContain('[queued]');
+ expect(line).toContain('[passage gone]');
+ });
+
+ test('caps inlined bodies and elides the rest', () => {
+ const line = formatFileEntry({
+ ...base,
+ commentCount: 5,
+ comments: [1, 2, 3, 4, 5].map((n) => ({
+ threadId: `c${n}`,
+ body: `note ${n}`,
+ quote: `q${n}`,
+ state: 'anchored' as const,
+ queued: false,
+ })),
+ });
+ expect(line).toContain('5 unresolved comments:');
+ expect(line).toContain('note 3');
+ expect(line).not.toContain('note 4');
+ expect(line).toContain('…');
+ });
+
+ test('says nothing when there are none, and nothing when unknown', () => {
+ // The overwhelmingly common case is a doc with no comments. A
+ // `comments: 0` on every entry would be pure noise, unlike `backlinks: 0`
+ // which is a real fact about a doc's place in the graph. `null` (no server
+ // to ask) is likewise silent rather than reported as zero.
+ expect(formatFileEntry({ ...base, commentCount: 0 })).not.toContain('unresolved');
+ expect(formatFileEntry(base)).not.toContain('unresolved');
+ });
+});
+
+describe('formatDirectoryEntry — folder comment rollup', () => {
+ const base: DirectoryMeta = {
+ path: 'specs',
+ type: 'directory',
+ directMdCount: 3,
+ recursiveMdCount: 9,
+ childDirCount: 2,
+ truncated: false,
+ };
+
+ test('reports the subtree total and where to look', () => {
+ const line = formatDirectoryEntry({
+ ...base,
+ commentCount: 4,
+ commentedDocs: [
+ { docName: 'specs/auth', count: 3 },
+ { docName: 'specs/nested/tokens', count: 1 },
+ ],
+ });
+ expect(line).toContain('4 unresolved comments in tree');
+ expect(line).toContain('specs/auth (3)');
+ expect(line).toContain('specs/nested/tokens (1)');
+ expect(line).not.toContain(', …');
+ });
+
+ test('elides when the named docs do not account for the total', () => {
+ // `commentedDocs` is capped in enrichment, so the renderer infers the tail
+ // from the arithmetic rather than re-deriving the cap.
+ const line = formatDirectoryEntry({
+ ...base,
+ commentCount: 10,
+ commentedDocs: [{ docName: 'specs/auth', count: 3 }],
+ });
+ expect(line).toContain('10 unresolved comments in tree');
+ expect(line).toContain(', …');
+ });
+
+ test('a clean or unknown folder says nothing', () => {
+ expect(formatDirectoryEntry(base)).not.toContain('unresolved');
+ expect(formatDirectoryEntry({ ...base, commentCount: 0 })).not.toContain('unresolved');
+ });
+});
+
describe('exec — frontmatter schemas_applicable read-time advertisement', () => {
// The composition this pins: config.contentRules.frontmatter → exec.ts's
// enrichSchemaDeps wiring → enrichment's appliesTo resolver → the schema
diff --git a/packages/server/src/mcp/tools/exec.ts b/packages/server/src/mcp/tools/exec.ts
index 8150f7932..d55d7f075 100644
--- a/packages/server/src/mcp/tools/exec.ts
+++ b/packages/server/src/mcp/tools/exec.ts
@@ -44,6 +44,7 @@ import {
enrichDirectoryRecursive,
enrichPath,
fetchBacklinkCountsBatch,
+ fetchCommentCountsBatch,
pathToDocName,
} from '../../content/enrichment.ts';
import { resolveWithinRoot } from './path-safety.ts';
@@ -92,10 +93,14 @@ const SOFT_CAP_BYTES =
const BINARY_EXT_RE = /\.(png|jpe?g|gif|webp|svg|pdf|zip|tar|gz|tgz|mp4|mov|mp3|wav|ico|bmp)$/i;
export const DESCRIPTION = [
- '**STOP — when the project has `.ok/`, do NOT use native `Read`/`Grep`/`Glob` on in-scope `.md`/`.mdx`; use `exec` (this tool).** Native tools skip the frontmatter, backlinks, shadow-repo activity, and git history `exec` returns per wiki file. Reserve native tools for source code, non-markdown, and projects without `.ok/`. (Full rule + escape hatch: the `open-knowledge` skill.)',
+ '**STOP — when the project has `.ok/`, do NOT use native `Read`/`Grep`/`Glob` on in-scope `.md`/`.mdx`; use `exec` (this tool).** Native tools skip the frontmatter, backlinks, unresolved comments, shadow-repo activity, and git history `exec` returns per wiki file. Reserve native tools for source code, non-markdown, and projects without `.ok/`. (Full rule + escape hatch: the `open-knowledge` skill.)',
'',
'Run a read-only bash-like command against the project content directory. Returns raw stdout plus enriched metadata for every wiki file referenced (frontmatter, backlink/forward-link counts, shadow-repo activity with agent/human attribution).',
'',
+ // Deliberately stops at "report": there is no MCP surface for resolving a
+ // thread, so an agent told to "address" one has no way to close the loop.
+ '`⚠ N unresolved comment(s)` = open human review requests — factor in before editing, and report them.',
+ '',
'Allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut. One command or a pipe (|) per call — NOT a shell: `&&`, `;`, redirections, subshells, and writes are rejected. To do several things, make separate exec calls or pass multiple paths to one command (e.g. `ls -A a b c`, `cat a b c`).',
'',
"cwd: the command runs in the explicit absolute `cwd` you pass, or in the MCP client's only advertised root when there is exactly one. If the client has zero or multiple roots, pass `cwd` explicitly. Paths inside the command resolve relative to that cwd; traversal above it is rejected.",
@@ -278,7 +283,7 @@ function isDirectoryMeta(e: EnrichedEntry): e is DirectoryMeta {
return (e as DirectoryMeta).type === 'directory';
}
-function formatDirectoryEntry(d: DirectoryMeta): string {
+export function formatDirectoryEntry(d: DirectoryMeta): string {
// When the folder's own `.ok/frontmatter.yml` supplied a title, lead with it
// like file entries do; otherwise fall back to the path label. Either way show
// the path in parens so agents can always resolve the on-disk location.
@@ -314,10 +319,47 @@ function formatDirectoryEntry(d: DirectoryMeta): string {
`most recent: ${d.mostRecentMd.title ?? d.mostRecentMd.path} (${d.mostRecentMd.path}${when})`,
);
}
+ // After the counts, before the recency hint: it is a property of the subtree
+ // like the file counts are, not a property of any one file in it.
+ if (d.commentCount !== undefined && d.commentCount > 0) {
+ let line = `⚠ ${d.commentCount} unresolved comment${d.commentCount === 1 ? '' : 's'} in tree`;
+ if (d.commentedDocs && d.commentedDocs.length > 0) {
+ const where = d.commentedDocs.map((c) => `${c.docName} (${c.count})`).join(', ');
+ // The cap lives in `enrichDirectory`, so infer the elision from the
+ // totals rather than re-deriving it: listed docs summing below the total
+ // means the tail was dropped.
+ const listed = d.commentedDocs.reduce((sum, c) => sum + c.count, 0);
+ line += `: ${where}${listed < d.commentCount ? ', …' : ''}`;
+ }
+ parts.push(line);
+ }
if (d.truncated) parts.push('scan truncated');
return `- ${parts.join(' — ')}`;
}
+/**
+ * How many comment bodies a single-file read inlines. Past a handful the entry
+ * stops being metadata about the file and becomes the review itself; the count
+ * still names the true total.
+ */
+const COMMENT_PREVIEW_CAP = 3;
+
+/**
+ * One comment, as the text channel renders it: the ask, the passage it sits on,
+ * and the two states that change what the reader should do about it.
+ *
+ * `queued` means staged to send and not yet sent — a comment that WAS sent is
+ * resolved and never reaches here. It is context for the reader ("a human is
+ * about to ask for this"), not a duplicate marker.
+ */
+function formatCommentPreview(c: NonNullable<EnrichedMeta['comments']>[number]): string {
+ const flags = [c.state === 'orphaned' ? 'passage gone' : null, c.queued ? 'queued' : null].filter(
+ (f) => f !== null,
+ );
+ const suffix = flags.length > 0 ? ` [${flags.join(', ')}]` : '';
+ return c.quote === '' ? `"${c.body}"${suffix}` : `"${c.body}" on “${c.quote}”${suffix}`;
+}
+
export function formatFileEntry(m: EnrichedMeta): string {
const title = m.title ?? m.path;
const parts: string[] = [`**${title}** (${m.path})`];
@@ -331,6 +373,17 @@ export function formatFileEntry(m: EnrichedMeta): string {
if (m.schemas_applicable && m.schemas_applicable.length > 0) {
parts.push(`schemas: ${m.schemas_applicable.join(', ')}`);
}
+ // Leads the connective metadata, and prints only when there IS something
+ // outstanding — unlike `backlinks: 0`, which is a useful fact about a doc, a
+ // `comments: 0` on every read is noise on the overwhelmingly common case.
+ if (m.commentCount !== null && m.commentCount > 0) {
+ let line = `⚠ ${m.commentCount} unresolved comment${m.commentCount === 1 ? '' : 's'}`;
+ if (m.comments && m.comments.length > 0) {
+ const notes = m.comments.slice(0, COMMENT_PREVIEW_CAP).map(formatCommentPreview);
+ line += `: ${notes.join('; ')}${m.comments.length > COMMENT_PREVIEW_CAP ? '; …' : ''}`;
+ }
+ parts.push(line);
+ }
if (m.backlinkCount !== null) {
// Source paths are populated on single-cat rich only (null on multi-path); render
// them so the agent can follow a backlink without a second links() call.
@@ -654,6 +707,8 @@ export async function buildExecResult(
projectHistory: null,
projectHistorySource: null,
graphRole: null,
+ commentCount: null,
+ comments: null,
}),
),
),
@@ -666,7 +721,11 @@ export async function buildExecResult(
// change away.
const dirEnriched: DirectoryMeta[] = await Promise.all(
dirs.map((p) =>
- enrichDirectoryRecursive(p, 1, { projectDir: cwd, ...enrichSchemaDeps }).catch(
+ enrichDirectoryRecursive(p, 1, {
+ projectDir: cwd,
+ serverUrl: resolvedServerUrl,
+ ...enrichSchemaDeps,
+ }).catch(
(): DirectoryMeta => ({
path: p,
type: 'directory',
@@ -683,12 +742,21 @@ export async function buildExecResult(
// without N-amplifying /api/backlinks. Single-path rich cat already has it.
if (!isSinglePathCat && resolvedServerUrl && fileEnriched.length > 0) {
const docNames = fileEnriched.map((f) => pathToDocName(f.path));
- const counts = await fetchBacklinkCountsBatch(resolvedServerUrl, docNames).catch(() => null);
- if (counts) {
- for (const f of fileEnriched) {
- const c = counts.get(pathToDocName(f.path));
- if (typeof c === 'number') f.backlinkCount = c;
- }
+ // Both batches fire together — they are independent reads of two indexes,
+ // so serializing them would double the listing's added latency for nothing.
+ const [counts, commentCounts] = await Promise.all([
+ fetchBacklinkCountsBatch(resolvedServerUrl, docNames).catch(() => null),
+ fetchCommentCountsBatch(resolvedServerUrl, docNames).catch(() => null),
+ ]);
+ for (const f of fileEnriched) {
+ const docName = pathToDocName(f.path);
+ const c = counts?.get(docName);
+ if (typeof c === 'number') f.backlinkCount = c;
+ // Unlike backlinks, a slim entry carries the comment COUNT but never the
+ // bodies — the signal a listing needs is "something is waiting here", and
+ // the doc's own read has the text.
+ const comments = commentCounts?.get(docName);
+ if (typeof comments === 'number') f.commentCount = comments;
}
}
// Preserve stdout order: walk `paths` and pick up the matching entry.
@@ -776,7 +844,7 @@ export function register(server: ServerInstance, deps: ExecDeps): void {
},
outputSchema: outputSchemaWithText({
enrichedPaths: looseObjectArray.describe(
- 'Per-referenced-file metadata: frontmatter, backlink/forward-link counts, recent shadow-repo activity, and a route-only previewUrl.',
+ 'Per-referenced-file metadata: frontmatter, backlink/forward-link counts, unresolved comment threads (`commentCount`, plus `comments` on a single-file read), recent shadow-repo activity, and a route-only previewUrl. Directory entries carry a recursive `commentCount` + `commentedDocs`.',
),
stdoutTruncated: z
.boolean()
diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.ts
index 90a386601..5858d6ae9 100644
--- a/packages/server/src/server-factory.ts
+++ b/packages/server/src/server-factory.ts
@@ -55,7 +55,7 @@ import { AcpRegistry, loadCustomAgents } from './acp/registry.ts';
import { AgentFocusBroadcaster } from './agent-focus.ts';
import { AgentPresenceBroadcaster } from './agent-presence.ts';
import { AgentSessionManager } from './agent-sessions.ts';
-import { createApiExtension, isSafeDocName } from './api-extension.ts';
+import { type CommentDocHooks, createApiExtension, isSafeDocName } from './api-extension.ts';
import { assetReferencesChanged } from './asset-references.ts';
import { seedBasenameIndex, seedSingleDirBasenameIndex } from './asset-walk.ts';
import { HocuspocusAuthRejection, parseHocuspocusAuthToken } from './auth-token-schema.ts';
@@ -1042,7 +1042,9 @@ export function createServer(options: ServerOptions): ServerInstance {
rejectReady = rej;
});
- function signalChannel(channel: 'files' | 'backlinks' | 'graph' | 'tags' | 'lint-config'): void {
+ function signalChannel(
+ channel: 'files' | 'backlinks' | 'graph' | 'tags' | 'comments' | 'lint-config',
+ ): void {
cc1Broadcaster?.signal(channel);
}
@@ -1113,6 +1115,12 @@ export function createServer(options: ServerOptions): ServerInstance {
// Lambda-callback shape mirrors `onDiskFlush` (`persistenceOpts`) — keeps
// the watcher reconcile cases free of direct cache references and avoids
// extending `signalChannel`'s union for a per-event side effect.
+ // Comments follow their document's lifecycle. The comment service is built
+ // inside the API extension, further down, so the watcher and the settle
+ // extension reach it through this ref at call time rather than construction
+ // time.
+ const commentDocHooksRef: { current: CommentDocHooks | null } = { current: null };
+
const onUpstreamRename = (oldDocName: string, newDocName: string): void => {
if (isReservedForUserTree(oldDocName)) return;
recentlyRemovedDocs.setRenamed(oldDocName, newDocName);
@@ -1144,6 +1152,11 @@ export function createServer(options: ServerOptions): ServerInstance {
return;
}
recentlyRemovedDocs.setDeleted(docName);
+ // A comment's whole reason to exist is a passage in this document. Hooked
+ // here rather than in the delete routes because every delete path reaches
+ // disk, so the watcher sees them all — an in-app delete, the desktop trash
+ // flow, and a file removed outside the app alike.
+ commentDocHooksRef.current?.deleted(docName);
};
const onUpstreamAdd = (docName: string): void => {
if (isReservedForUserTree(docName)) return;
@@ -1497,6 +1510,7 @@ export function createServer(options: ServerOptions): ServerInstance {
);
const liveDerivedIndexExtension = createLiveDerivedIndexExtension({
derivedDocumentIndex,
+ onDocumentSettled: (docName) => commentDocHooksRef.current?.changed(docName),
});
hocuspocus.configuration.extensions.push(liveDerivedIndexExtension);
@@ -1787,6 +1801,7 @@ export function createServer(options: ServerOptions): ServerInstance {
durabilityState,
remotePublicHost: options.remotePublicHost,
sessionManager,
+ commentDocHooksRef,
contentDir,
contentFilter,
serverInstanceId,