Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Comment opens on the right rather than inline (#3476)
shagun-singh-inkeep42250dfa9885
diff --git a/.changeset/comments-open-in-panel.md b/.changeset/comments-open-in-panel.mdnew file mode 100644index 000000000..ba586a740--- /dev/null+++ b/.changeset/comments-open-in-panel.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Clicking a commented passage, its margin icon, or a commented property value now shows that comment in the Comments panel on the right instead of floating a card over the document. The card used to be pinned to the text it was about, so it covered the paragraphs around the passage — the ones you need in order to judge the comment — and printed the comment twice, since the panel was showing it as well. The Comments tab now opens, scrolls to the comment, and highlights it, with the passage still marked in the document. Comments are also reachable in single-file (`ok <file>`) sessions, which previously offered no Comments tab at all.diff --git a/packages/app/package.json b/packages/app/package.jsonindex b3e6e7ba3..a8e4a032d 100644--- a/packages/app/package.json+++ b/packages/app/package.json@@ -27,7 +27,7 @@"measure:stress": "bash scripts/measure-stress.sh","measure:sweep": "bash scripts/measure-sweep.sh","perf:compare": "bash scripts/perf-compare.sh",- "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-collapse-spaced-folder.e2e.ts tests/stress/sidebar-file-list-fills.e2e.ts tests/stress/file-tree-sticky-collapse.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/frontmatter-schema-badge.e2e.ts tests/stress/frontmatter-glob-picker.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/image-invalid-placeholder.e2e.ts tests/stress/local-target-audit.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts tests/stress/qa-miles-edge-blanks.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/editor-split-view.e2e.ts tests/stress/language-load-failure.e2e.ts tests/stress/language-first-paint.e2e.ts tests/stress/user-text-direction.e2e.ts tests/stress/pseudolocale.e2e.ts tests/stress/language-picker.e2e.ts tests/stress/zh-hans-coverage-sweep.e2e.ts tests/stress/preview-tab-promotion.e2e.ts tests/stress/cv-paint-lock-click.e2e.ts tests/stress/history-traversal-preview-tab.e2e.ts",+ "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-collapse-spaced-folder.e2e.ts tests/stress/sidebar-file-list-fills.e2e.ts tests/stress/file-tree-sticky-collapse.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/frontmatter-schema-badge.e2e.ts tests/stress/frontmatter-glob-picker.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/image-invalid-placeholder.e2e.ts tests/stress/local-target-audit.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts tests/stress/comment-opens-in-panel.e2e.ts tests/stress/qa-miles-edge-blanks.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/editor-split-view.e2e.ts tests/stress/language-load-failure.e2e.ts tests/stress/language-first-paint.e2e.ts tests/stress/user-text-direction.e2e.ts tests/stress/pseudolocale.e2e.ts tests/stress/language-picker.e2e.ts tests/stress/zh-hans-coverage-sweep.e2e.ts tests/stress/preview-tab-promotion.e2e.ts tests/stress/cv-paint-lock-click.e2e.ts tests/stress/history-traversal-preview-tab.e2e.ts","test:e2e:install-browsers": "playwright install chromium webkit firefox","test:visual": "playwright test --config playwright.visual.config.ts","test:visual:update": "playwright test --config playwright.visual.config.ts --update-snapshots",diff --git a/packages/app/src/comments/CommentListPanel.tsx b/packages/app/src/comments/CommentListPanel.tsxindex 3e447a216..5050210c5 100644--- a/packages/app/src/comments/CommentListPanel.tsx+++ b/packages/app/src/comments/CommentListPanel.tsx@@ -37,10 +37,72 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltipimport { CommentSendFooter } from './CommentSendFooter';import { docBasename } from './comment-chips';import { groupByDoc } from './queue-grouping';-import { setSendingAll, subscribeFocusThread, usePinnedThread, useQueueSelection } from './store';+import {+ getOpenThread,+ setSendingAll,+ subscribeFocusThread,+ subscribeOpenThread,+ useOpenThread,+ useQueueSelection,+} from './store';import { ThreadCard } from './ThreadCard';import type { CommentThread } from './types';+/** ~a third of a second of frames — long enough for a cold panel, short enough to stop. */+const SCROLL_FRAME_BUDGET = 20;++/** How long the ring stays on the card it was put on. */+const RING_MS = 1_600;++interface FocusHandles {+ cards: ReadonlyMap<string, HTMLElement>;+ /** The pending scroll chase, so a second open calls off the first one's. */+ frame: { current: number | null };+ /** The ring's own timer, held so it can be cancelled rather than left to fire after unmount. */+ ring: { current: number | null };+ setFocusedId: (update: (current: string | null) => string | null) => void;+}++/**+ * Bring a thread's card into view and ring it.+ *+ * The scroll is retried across a few frames rather than attempted once: opening+ * a thread is what MOUNTS this panel in the common case (clicking a highlight+ * switches the doc panel to the Comments tab), and on a cold open the threads+ * are still arriving, so the card can be a frame or two behind the request to+ * scroll to it. The ring is set immediately either way — it is state, not+ * geometry, so it lands on the card whenever the card does.+ */+function focusCard(threadId: string, handles: FocusHandles): void {+ const { cards, frame, ring, setFocusedId } = handles;+ setFocusedId(() => threadId);+ if (frame.current !== null) cancelAnimationFrame(frame.current);+ let attempts = 0;+ const attempt = (): void => {+ frame.current = null;+ const card = cards.get(threadId);+ if (card) {+ // Honours the reader's motion setting, like every other jump in this+ // subsystem (`scrollAnchorIntoView` asks the same question before it+ // scrolls the document to the passage this card is about — the two move+ // together on one click, so only one of them respecting it would be worse+ // than neither).+ const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;+ card.scrollIntoView({ block: 'center', behavior: reduceMotion ? 'auto' : 'smooth' });+ return;+ }+ attempts += 1;+ if (attempts >= SCROLL_FRAME_BUDGET) return;+ frame.current = requestAnimationFrame(attempt);+ };+ attempt();+ if (ring.current !== null) window.clearTimeout(ring.current);+ ring.current = window.setTimeout(() => {+ ring.current = null;+ setFocusedId((current) => (current === threadId ? null : current));+ }, RING_MS);+}+export function CommentListPanel({threads,groupByDocument = false,@@ -73,12 +135,12 @@ export function CommentListPanel({// rest instead of silently landing folded because it was not in an opened-set.const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(() => new Set());const sending = useQueueSelection();- // The thread whose popover is OPEN in the document — mirrored onto its card- // so the two sides of the screen point at each other. Popover-open only, not- // hover: washing a card because the pointer touched it (or its highlight)- // made every pass of the mouse a light show. One subscription for the whole- // panel, like `sending`.- const activeId = usePinnedThread();+ // The thread the reader has OPEN — washed on its card, deepened on its+ // passage in the document, so the two sides of the screen point at each+ // other. Open only, not hover: washing a card because the pointer touched it+ // (or its highlight) made every pass of the mouse a light show. One+ // subscription for the whole panel, like `sending`.+ const activeId = useOpenThread();function toggleFile(docName: string, open: boolean) {setCollapsed((prev) => {@@ -89,25 +151,56 @@ export function CommentListPanel({});}- // 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.+ // The ring's timer and the scroll's frame are held so they can be cancelled.+ // Left dangling the timer fired after unmount, and every focus 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);+ const scrollFrame = useRef<number | null>(null);+ // Every member is stable for the life of the component — two refs, the card+ // map they are held beside, and a state setter — so this is rebuilt per call+ // rather than memoized or carried in a ref of its own.+ const focusHandles = (): FocusHandles => ({+ cards: cardRefs.current,+ frame: scrollFrame,+ ring: ringTimer,+ setFocusedId,+ });++ // Opening a thread — an in-doc highlight, a margin marker, a commented+ // property value, a queue card — brings its card here. This is the whole of+ // "show me that comment" now: the panel is where the comment is READ, so the+ // signal has to land the card in front of the reader rather than merely wash+ // it.+ //+ // BOTH halves are load-bearing, and each covers what the other cannot:+ //+ // - the EVENT, because opening the thread that is already open is a real+ // gesture. Scroll the panel away, click the same highlight to get back to+ // the card: the id has not changed, so state-driven focus sees an+ // identical snapshot, React bails out of the render, and the click does+ // nothing at all.+ // - the mount READ, because the open that switches the doc panel to this+ // tab is the same open that MOUNTS this panel, and no subscription can+ // hear the event that brought it into being.+ //+ // Reveals that do not open a thread come in on their own signal: a comment+ // whose passage is gone still has to light up when its document arrives.+ // biome-ignore lint/correctness/useExhaustiveDependencies: focusHandles closes over refs and a state setter only, all stable for the component's life; keying the effect on it would re-subscribe on every renderuseEffect(() => {- 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);+ const focus = (threadId: string) => focusCard(threadId, focusHandles());+ const pending = getOpenThread();+ if (pending !== null) focus(pending);+ const stopOpens = subscribeOpenThread((threadId) => {+ // Standing a thread down is not a request to look at anything.+ if (threadId !== null) focus(threadId);});+ const stopReveals = subscribeFocusThread(focus);return () => {- stop();+ stopOpens();+ stopReveals();if (ringTimer.current !== null) window.clearTimeout(ringTimer.current);+ if (scrollFrame.current !== null) cancelAnimationFrame(scrollFrame.current);};}, []);diff --git a/packages/app/src/comments/CommentMarginRail.tsx b/packages/app/src/comments/CommentMarginRail.tsxindex 3005c4d7b..c5d303f85 100644--- a/packages/app/src/comments/CommentMarginRail.tsx+++ b/packages/app/src/comments/CommentMarginRail.tsx@@ -3,8 +3,9 @@** 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).+ * and opens its thread — which is to say it brings that comment up in the+ * Comments panel (via the shared open-thread bus), rather than floating a card+ * over the words the reader came to read.** 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@@ -44,10 +45,10 @@ import {import { findScrollContainer, scrollAnchorIntoView, scrollportInsetTop } from './scroll-to-anchor';import {clearActiveThread,- emitOpenThreadPopover,+ emitOpenThread,setActiveThread,- subscribeOpenThreadPopover,useCommentThreads,+ useOpenThread,} from './store';const RAIL_WIDTH = 34;@@ -157,12 +158,16 @@ export function layoutMarkers(export function CommentMarginRail({ editor, docName }: { editor: Editor; docName: string }) {const { t } = useLingui();const threads = useCommentThreads(docName);- const [activeId, setActiveId] = useState<string | null>(null);+ // Read from the store rather than held locally and fed by a subscription.+ // Local state starts at null and only learns from the NEXT event, so a rail+ // that mounts while a thread is already open — the editor pool recycles this+ // component on every visit to a document — drew its marker unlit and then got+ // the toggle backwards: `jumpTo` compares against this value, so the first+ // click on the lit marker re-opened the thread instead of closing it.+ const activeId = useOpenThread();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;@@ -246,11 +251,11 @@ export function CommentMarginRail({ editor, docName }: { editor: Editor; docName}, [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).+ // Second click on the marker you are already reading stands the thread+ // down. The rail mirrors the open-thread state rather than keeping its own,+ // so this stays right when the thread was closed from somewhere else.if (activeId === threadId) {- emitOpenThreadPopover(null);+ emitOpenThread(null);return;}const thread = threads.find((x) => x.id === threadId);@@ -272,7 +277,7 @@ export function CommentMarginRail({ editor, docName }: { editor: Editor; docNameconst range = findQuoteRange(editor.state.doc, thread.anchor.quote, thread.anchor);if (range) scrollAnchorIntoView(editor, range, thread.docName);}- emitOpenThreadPopover(threadId);+ emitOpenThread(threadId);}if (rail === null || positions.length === 0) return null;@@ -291,8 +296,12 @@ export function CommentMarginRail({ editor, docName }: { editor: Editor; docNamekey={pos.id}type="button"variant="ghost"+ // The label carries the state on its own. No `aria-expanded`: this+ // marker no longer unfolds anything beside itself — it shows the+ // comment in the Comments panel, a region it does not own — and a+ // button claiming a collapsed disclosure that is not there sends a+ // screen-reader user looking for one.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.diff --git a/packages/app/src/comments/CommentSelectionAffordance.tsx b/packages/app/src/comments/CommentSelectionAffordance.tsxindex 4f0342a4d..ce27bcd35 100644--- a/packages/app/src/comments/CommentSelectionAffordance.tsx+++ b/packages/app/src/comments/CommentSelectionAffordance.tsx@@ -231,8 +231,9 @@ export function CommentSelectionAffordance({return createPortal(<divref={floatingRef}- // Same borrowed `PopoverContent` chrome as the thread popover, and for the- // same reason — a virtual anchor Radix cannot take.+ // Borrowed `PopoverContent` chrome rather than a real one: this follows a+ // ProseMirror text range through a floating-ui virtual element, and+ // Radix's anchor takes a DOM node.className="z-[60] flex w-80 flex-col gap-2 rounded-lg border bg-popover p-3 text-popover-foreground shadow-md"style={{ position: 'fixed', top: 0, left: 0 }}data-testid="comment-composer"diff --git a/packages/app/src/comments/CommentThreadPopover.tsx b/packages/app/src/comments/CommentThreadPopover.tsxdeleted file mode 100644index b471dd430..000000000--- a/packages/app/src/comments/CommentThreadPopover.tsx+++ /dev/null@@ -1,179 +0,0 @@-/**- * 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 { propertyRowRect } from './property-row-rect';-import {- emitOpenThreadPopover,- subscribeOpenThreadPopover,- useAllThreads,- useCommentThreads,- useQueueSelection,-} from './store';-import { ThreadCard } from './ThreadCard';--export function CommentThreadPopover({ editor, docName }: { editor: Editor; docName: string }) {- const [threadId, setThreadId] = useState<string | null>(null);- const floatingRef = useRef<HTMLDivElement>(null);- const threads = useCommentThreads(docName);- const thread = threadId ? (threads.find((t) => t.id === threadId) ?? null) : null;- // The card's tick is a controlled checkbox, so this popover has to subscribe- // to the send list the same way the panels do. Without it the box rendered- // from `undefined` — permanently unchecked, however many times you clicked it,- // while the click itself went through to the store. The state was right and- // only this view disagreed, which is the worst shape a bug like this can take.- const sending = useQueueSelection();-- // Open on highlight/marker click.- useEffect(() => {- return subscribeOpenThreadPopover((id) => setThreadId(id));- }, []);-- // Another document's thread — that document's own instance is showing it.- //- // The editor pool keeps recently visited docs mounted, so several of these- // exist at once and the open signal is a single project-wide bus that reaches- // all of them. An instance that answered a thread it does not own by- // BROADCASTING a close slammed the popover shut for the instance that had just- // opened it, and which one spoke last was down to tree order — so clicking a- // passage worked or did nothing depending on how many tabs were open.- //- // Looked up across every doc rather than inferred from this one's miss: "not- // in my list" alone cannot tell a thread that belongs elsewhere from one that- // was deleted, and only the second is this instance's business.- const allThreads = useAllThreads();- const ownedElsewhere =- threadId !== null && thread === null && allThreads.some((t) => t.id === threadId);-- // 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 (ownedElsewhere) return;- if (threadId !== null && (thread === null || thread.status !== 'open')) {- emitOpenThreadPopover(null);- }- }, [threadId, thread, ownedElsewhere]);-- // 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;- // The card's edit field is the `@`-mention composer, whose results portal- // to `document.body` — outside this card by DOM, inside it by intent.- // Picking a file must not read as clicking away. Same guard the selection- // composer carries, for the same popup.- if (target?.closest('[data-suggestion-popup]')) 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}- // Chrome borrowed from `PopoverContent`, since this cannot BE one: the- // card follows a ProseMirror text range through a floating-ui virtual- // element, and Radix's anchor takes a DOM node. Its border and padding are- // deliberately left off — `ThreadCard` brings both, and doubling them- // draws two outlines a couple of pixels apart.- className="z-50 w-80 rounded-lg bg-popover text-popover-foreground shadow-md"- style={{ position: 'fixed', top: 0, left: 0 }}- >- {/* No quote and no close button: the card is pinned to the passage it is- about, with that passage highlighted underneath, and Escape or a click- outside dismisses it (see the effect above). */}- <ThreadCard- // Keyed, so retargeting this popover REMOUNTS the card rather than- // handing the next thread the last one's state. Clicking a second- // highlight while the first is open swaps `thread` in place — no null- // in between — and an unkeyed card kept its open edit field, its seeded- // draft and its settled flag across the swap, which filed one comment's- // words as a revision of another. The remount also lets the outgoing- // card's click-away commit save its own edit, against its own id.- key={thread.id}- thread={thread}- focused={false}- showQuote={false}- sending={sending.includes(thread.id)}- cardRef={() => {}}- />- </div>,- document.body,- );-}diff --git a/packages/app/src/comments/CommentsTab.tsx b/packages/app/src/comments/CommentsTab.tsxindex 309e55217..1f84878bc 100644--- a/packages/app/src/comments/CommentsTab.tsx+++ b/packages/app/src/comments/CommentsTab.tsx@@ -10,13 +10,20 @@import { useEffect, useState } from 'react';import { type PanelScope, PanelScopeHeader } from '@/components/PanelScopeHeader';+import { useSingleFileMode } from '@/lib/single-file-mode';import { CommentProjectPanel } from './CommentProjectPanel';import { CommentsPanel } from './CommentsPanel';import { consumePendingCommentScope, subscribeCommentScopeRequests } from './reveal-queue';import { setVisibleCommentScope } from './visible-scope';export function CommentsTab({ docName }: { docName: string }) {- const [scope, setScope] = useState<PanelScope>('doc');+ const [requestedScope, setRequestedScope] = useState<PanelScope>('doc');+ // A `ok <file>` session has no project to widen to — the one document IS the+ // whole of it. So the scope is pinned to "This doc" and the switch is not+ // drawn, rather than offering a second view of the same list under a name+ // that promises files the session cannot reach.+ const singleFile = useSingleFileMode();+ const scope: PanelScope = singleFile ? 'doc' : requestedScope;// Reveals set this tab's scope from outside — posting a comment lands on// "This doc" (the comment you just made, beside its passage), the composer// chip on "This project" (its batch spans documents). The scope lives here, so@@ -25,8 +32,8 @@ export function CommentsTab({ docName }: { docName: string }) {// this component exists to hear it.useEffect(() => {const pending = consumePendingCommentScope();- if (pending !== null) setScope(pending);- return subscribeCommentScopeRequests(setScope);+ if (pending !== null) setRequestedScope(pending);+ return subscribeCommentScopeRequests(setRequestedScope);}, []);// Publish what is on screen so ⇧⌘Enter sends the batch the visible button// would. Cleared on unmount — this tab is conditionally rendered, so leaving a@@ -47,14 +54,12 @@ export function CommentsTab({ docName }: { docName: string }) {// the title looked like a heading for the list alone.// No `projectLabel`: "This project" is the shared default now, so both// panels say it without either one restating it.+ const scopeSwitch = singleFile ? undefined : (+ <PanelScopeHeader scope={scope} onScopeChange={setRequestedScope} />+ );return scope === 'doc' ? (- <CommentsPanel- docName={docName}- scopeSwitch={<PanelScopeHeader scope={scope} onScopeChange={setScope} />}- />+ <CommentsPanel docName={docName} scopeSwitch={scopeSwitch} />) : (- <CommentProjectPanel- scopeSwitch={<PanelScopeHeader scope={scope} onScopeChange={setScope} />}- />+ <CommentProjectPanel scopeSwitch={scopeSwitch} />);}diff --git a/packages/app/src/comments/ThreadCard.tsx b/packages/app/src/comments/ThreadCard.tsxindex 868cd4ee5..59d50720d 100644--- a/packages/app/src/comments/ThreadCard.tsx+++ b/packages/app/src/comments/ThreadCard.tsx@@ -4,8 +4,8 @@* Thread lifecycle rendered from the store: the anchored quote, the comment* itself (editable in place), the tick that decides whether it goes out with* the next send, resolve, and the explicit orphaned-"re-place" state. Shared by- * both comment scopes and by the in-document popover, so a comment looks and- * behaves the same wherever it is met.+ * both comment scopes, so a comment looks and behaves the same wherever it is+ * met.** 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@@ -36,7 +36,7 @@ import {clearActiveThread,deleteThread,editComment,- emitOpenThreadPopover,+ emitOpenThread,reopenThread,replaceOrphan,setActiveThread,@@ -84,32 +84,20 @@ export function ThreadCard({thread,cardRef,focused,- active = false,+ active,sending,- showQuote = true,}: {thread: CommentThread;cardRef: (el: HTMLElement | null) => void;focused: boolean;/**- * This thread's in-doc popover is OPEN. The card answers with the same amber- * WASH the passage carries — background only, no border (a border reads as a- * statement about selection, which the tick owns). Popover-open specifically,- * not hover: hosts used to pass the pointer-following active thread, and every- * card lit itself as the mouse crossed it. Optional because the popover host- * renders exactly one card and pinning it as active would just tint the card- * the reader is already inside.+ * The reader has this thread OPEN. The card answers with the same amber WASH+ * the passage carries — background only, no border (a border reads as a+ * statement about selection, which the tick owns). Open specifically, not+ * hover: hosts used to pass the pointer-following active thread, and every+ * card lit itself as the mouse crossed it.*/- active?: boolean;- /**- * Render the quoted passage the comment is anchored to.- *- * On in the panels, which sit away from the text and have to say what each- * comment is on. Off in the in-document popover, which is already pinned to- * that passage with the passage itself highlighted underneath — quoting it- * there prints the same words twice, inches apart.- */- showQuote?: boolean;+ active: boolean;/*** Ticked for the next send. Passed in rather than read here so one* subscription serves a whole panel of cards.@@ -202,11 +190,12 @@ export function ThreadCard({deleteThread(thread.id);}- // Click-away SAVES, like Notion — not silently discards. The popover host- // closes on any outside click, unmounting this card mid-edit; before this,- // that threw the revision away with nothing saying so, which read as "my- // edit didn't reflect". Escape remains the explicit discard, and it settles- // the edit first so this cleanup stands down.+ // Click-away SAVES, like Notion — not silently discards. A card can unmount+ // mid-edit under the reader (the panel switches scope, the thread resolves,+ // the document changes); before this, that threw the revision away with+ // nothing saying so, which read as "my edit didn't reflect". Escape remains+ // the explicit discard, and it settles the edit first so this cleanup stands+ // down.//// The commit must fire exactly when the edit session ends, not when the// thread re-renders mid-edit.@@ -239,7 +228,7 @@ export function ThreadCard({start: thread.anchor.start,end: thread.anchor.end,});- emitOpenThreadPopover(thread.id);+ emitOpenThread(thread.id);return;}const editor = getVisibleEditorForDoc(thread.docName);@@ -256,7 +245,7 @@ export function ThreadCard({// Our own scroll, not ProseMirror's: its minimal scroll lands the passage// under the floating toolbar.scrollAnchorIntoView(editor, range, thread.docName);- emitOpenThreadPopover(thread.id);+ emitOpenThread(thread.id);}function rePlaceOnSelection() {@@ -276,10 +265,8 @@ export function ThreadCard({// Clicking the card SELECTS ONLY this comment, or clears it when it is// already the only one; the checkbox stays additive, and the quote row keeps- // the jump. Panel cards only (`showQuote` is the proxy — the popover's card- // has no batch column beside it), never while editing, and a resolved card- // has no tick to narrow.- const cardSelects = showQuote && !editing && !isResolved;+ // the jump. Never while editing, and a resolved card has no tick to narrow.+ const cardSelects = !editing && !isResolved;return (// biome-ignore lint/a11y/useKeyWithClickEvents: pointer-only affordance — clicking the card's whitespace solos its tick; keyboard/AT users compose the same state from the real controls (the card's checkbox + the footer's master tick). See focus-composer-on-card-pointer.ts for the sibling pattern.@@ -430,13 +417,12 @@ export function ThreadCard({</div></div>- {/* Anchor quote. The orphaned block is the card's state rather than a- quote row — a thread that lost its passage has to say so wherever it is- rendered — so `showQuote` does not gate it. It still SHOWS the quote:+ {/* Anchor quote — the card sits away from the text, so it has to say what+ the comment is on. The orphaned block stands in for it: a thread that+ lost its passage says so instead, and still SHOWS the quote, becauseorphaning mutates state alone, so the stored words survive as the lastthing the comment was on, and they are what tells a reader which of- several comments this is. The popover has no passage underneath to- duplicate, that being the whole problem.+ several comments this is.Same chrome as the live quote row it stands in for — a lost passage isstill the passage this comment is on, so it reads as that row struck@@ -460,7 +446,7 @@ export function ThreadCard({</Trans></p></div>- ) : showQuote ? (+ ) : (<Tooltip>{/* `asChild` onto a DISABLED button would lose the hint — a disabledelement fires no pointer events, so Radix never sees the hover.@@ -500,7 +486,7 @@ export function ThreadCard({)}</TooltipContent></Tooltip>- ) : null}+ )}{/* The comment, or the field that revises it — one slot, never both. Thefield used to open BENEATH the text it was seeded from, so a card indiff --git a/packages/app/src/comments/active-thread.test.ts b/packages/app/src/comments/active-thread.test.tsindex dc080d03f..440ce5921 100644--- a/packages/app/src/comments/active-thread.test.ts+++ b/packages/app/src/comments/active-thread.test.ts@@ -1,7 +1,7 @@import { beforeEach, describe, expect, it, vi } from 'vitest';import {clearActiveThread,- emitOpenThreadPopover,+ emitOpenThread,getActiveThread,setActiveThread,subscribeActiveThread,@@ -9,7 +9,7 @@ import {beforeEach(() => {setActiveThread(null);- emitOpenThreadPopover(null);+ emitOpenThread(null);});describe('active thread', () => {@@ -32,14 +32,14 @@ describe('active thread', () => {expect(getActiveThread()).toBe('b');});- it('keeps the open popover active underneath the pointer', () => {- emitOpenThreadPopover('p');+ it('keeps the open thread active underneath the pointer', () => {+ emitOpenThread('p');expect(getActiveThread()).toBe('p');setActiveThread('a');expect(getActiveThread()).toBe('a');clearActiveThread('a');expect(getActiveThread()).toBe('p');- emitOpenThreadPopover(null);+ emitOpenThread(null);expect(getActiveThread()).toBeNull();});diff --git a/packages/app/src/comments/anchor-decorations.tsx b/packages/app/src/comments/anchor-decorations.tsxindex 8bfe37b4f..815c1b676 100644--- a/packages/app/src/comments/anchor-decorations.tsx+++ b/packages/app/src/comments/anchor-decorations.tsx@@ -19,8 +19,9 @@ import { useEffect } from 'react';import { buildAnchorSegments, type PlacedAnchor } from './anchor-layers';import { createAnchorResolver } from './anchor-search';import {- emitOpenThreadPopover,+ emitOpenThread,getActiveThread,+ getOpenThread,getThreads,refresh,subscribe,@@ -57,7 +58,26 @@ export function setCommentDraftRange(editor: Editor, range: DraftRange | null):}function openThread(threadId: string): void {- emitOpenThreadPopover(threadId);+ emitOpenThread(threadId);+}++/**+ * Stand the open thread down — the click landed in the document, away from+ * every highlight, or Escape was pressed with the caret in the text.+ *+ * The floating card used to own this: it listened on `document` for a click+ * outside itself and closed, which also cleared the deepened passage and the+ * washed card in the panel. With the card gone, nothing else says "I am done+ * with that comment", so a highlight you had opened stayed lit while you read+ * on somewhere else in the file.+ *+ * Guarded on something actually being open so an ordinary click in an ordinary+ * paragraph — the overwhelming majority of clicks in a document — does not+ * dispatch an event that every panel then re-reads.+ */+function standDown(): void {+ if (getOpenThread() === null) return;+ emitOpenThread(null);}/**@@ -186,16 +206,22 @@ function createCommentAnchorPlugin(docName: string): Plugin<AnchorPluginState> {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;- // One click, both meanings — the Google Docs gesture. The thread opens- // beside the passage AND the click falls through to ProseMirror as an- // ordinary caret placement, so a commented passage stays editable text- // rather than a button. The two never conflicted: a plain caret paints- // no selection and opens no bubble menu, and the popover takes no+ // Clicked in the text but not on a comment: the reader has moved on to+ // an unrelated passage, and the mark on the one they came from stops+ // meaning anything. Still `false` — this decides nothing about where+ // the caret goes.+ if (hit?.id == null) {+ standDown();+ return false;+ }+ // One click, both meanings — the Google Docs gesture. The thread comes+ // up in the Comments panel AND the click falls through to ProseMirror as+ // an ordinary caret placement, so a commented passage stays editable+ // text rather than a button. The two never conflicted: a plain caret+ // paints no selection and opens no bubble menu, and the panel takes no// focus, so reading and typing coexist. (An earlier cut captured the// click and blurred the editor, which made editing inside a highlight- // impossible — the popover's dismisser ignores highlight clicks, so- // the card also stays up while you type.)+ // impossible.)openThread(hit.id);return false;},@@ -239,10 +265,31 @@ export function CommentAnchorLayer({ editor, docName }: { editor: Editor; docNamconst unsubscribe = subscribe(redraw);const unsubscribeActive = subscribeActiveThread(redraw);+ // Escape stands the open thread down, from wherever the reader is.+ //+ // On `document`, not on the editor: the ProseMirror `handleKeyDown` prop is+ // bound to `view.dom`, and the Comments panel is a sibling rail rather than+ // a descendant — so a keyboard user who had tabbed into a card to read it+ // was the one person Escape could not reach, and the deepened passage stayed+ // lit until they tabbed all the way back to the marker that opened it.+ //+ // Neither consumed nor stopped: Escape is a shared key — the bubble menu, a+ // node selection, the suggestion popups all answer it — and a comment+ // standing down is not a reason for any of them to stay up. Several editors+ // are mounted at once (the pool), so several copies of this listener run per+ // press; `standDown` is guarded on something being open, which makes every+ // copy after the first a no-op rather than a second event.+ const onEscape = (event: KeyboardEvent) => {+ if (event.key !== 'Escape') return;+ standDown();+ };+ document.addEventListener('keydown', onEscape);+return () => {disposed = true;unsubscribe();unsubscribeActive();+ document.removeEventListener('keydown', onEscape);if (!editor.isDestroyed) editor.unregisterPlugin(commentAnchorKey);};}, [editor, docName]);diff --git a/packages/app/src/comments/edit-propagation.dom.test.tsx b/packages/app/src/comments/edit-propagation.dom.test.tsxindex 483e6d068..96a50071b 100644--- a/packages/app/src/comments/edit-propagation.dom.test.tsx+++ b/packages/app/src/comments/edit-propagation.dom.test.tsx@@ -1,10 +1,11 @@/*** A saved edit reaches every surface rendering the thread.*- * The popover and the panel show the same comment through two `ThreadCard`- * instances over one store, so revising it in one must update the other the- * moment the server accepts — not on the next CC1 push, and not never. Real- * store, real cards; only the network client is doubled.+ * Two `ThreadCard` instances over one store can be showing the same comment —+ * the two comment scopes, or a card that survives a scope switch — so revising+ * it in one must update the other the moment the server accepts: not on the+ * next CC1 push, and not never. Real store, real cards; only the network client+ * is doubled.*/import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';@@ -50,24 +51,31 @@ vi.doMock('./comments-client', () => ({const store = await import('./store');const { ThreadCard } = await import('./ThreadCard');-/** Two live instances of the same thread — the popover's card and the panel's. */+/** Two live instances of the same thread — the panel lists one card per+ * thread, and both comment scopes can be showing the same comment. */function Surfaces() {const threads = store.useCommentThreads('notes/rollout');const thread = threads[0];if (!thread) return null;return (<TooltipProvider>- <div data-testid="popover-side">+ <div data-testid="doc-side"><ThreadCardthread={thread}cardRef={() => {}}focused={false}+ active={false}sending={false}- showQuote={false}/></div>- <div data-testid="panel-side">- <ThreadCard thread={thread} cardRef={() => {}} focused={false} sending={false} />+ <div data-testid="project-side">+ <ThreadCard+ thread={thread}+ cardRef={() => {}}+ focused={false}+ active={false}+ sending={false}+ /></div></TooltipProvider>);@@ -80,12 +88,12 @@ describe('editing a comment', () => {render(<Surfaces />);await waitFor(() => expect(screen.getAllByText('first draft')).toHaveLength(2));- // Open the edit in the FIRST card (the popover's), revise, save.- const popover = screen.getByTestId('popover-side');+ // Open the edit in the FIRST card, revise, save.+ const docSide = screen.getByTestId('doc-side');fireEvent.click(// eslint-style queries scoped by container: the two cards are identical.// biome-ignore lint/style/noNonNullAssertion: the card renders its edit button or the earlier waitFor failed- popover.querySelector('button[aria-label="Edit this comment"]')!,+ docSide.querySelector('button[aria-label="Edit this comment"]')!,);const field = await screen.findByRole('textbox', { name: /edit this comment/i });const editor = (@@ -96,10 +104,10 @@ describe('editing a comment', () => {// BOTH surfaces converge on the revision once the server accepts.await waitFor(() => {- const panel = screen.getByTestId('panel-side');- expect(panel.textContent).toContain('second thoughts');+ const projectSide = screen.getByTestId('project-side');+ expect(projectSide.textContent).toContain('second thoughts');});- expect(screen.getByTestId('popover-side').textContent).toContain('second thoughts');+ expect(screen.getByTestId('doc-side').textContent).toContain('second thoughts');expect(screen.queryByText('first draft')).toBeNull();});});diff --git a/packages/app/src/comments/popover-bus.test.ts b/packages/app/src/comments/open-thread-bus.test.tssimilarity index 61%rename from packages/app/src/comments/popover-bus.test.tsrename to packages/app/src/comments/open-thread-bus.test.tsindex 3e50ffbb1..3b42d8306 100644--- a/packages/app/src/comments/popover-bus.test.ts+++ b/packages/app/src/comments/open-thread-bus.test.ts@@ -1,16 +1,16 @@/**- * The open-popover signal is shared state, not a one-way "open" command.+ * The open-thread 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.+ * Two bugs came from it being one-way. The thread was closed privately on+ * Escape / resolve, so the margin rail kept a marker lit for a thread nothing+ * was showing — 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 { afterEach, describe, expect, test, vi } from 'vitest';import { consumePendingDocPanelTabRequest } from '@/components/doc-panel-events';-import { emitOpenThreadPopover, subscribeOpenThreadPopover } from './store';+import { emitOpenThread, subscribeOpenThread } from './store';afterEach(() => {vi.restoreAllMocks();@@ -20,14 +20,14 @@ afterEach(() => {/** 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));+ const stop = subscribeOpenThread((id) => seen.push(id));return { seen, stop };}-describe('the thread-popover bus', () => {+describe('the open-thread bus', () => {test('carries an id when a thread opens', () => {const bus = record();- emitOpenThreadPopover('t1');+ emitOpenThread('t1');expect(bus.seen).toEqual(['t1']);bus.stop();});@@ -35,34 +35,34 @@ describe('the thread-popover bus', () => {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);+ emitOpenThread('t1');+ emitOpenThread(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');+ emitOpenThread('t1');+ emitOpenThread('t2');expect(bus.seen).toEqual(['t1', 't2']);bus.stop();});test('an unsubscribed listener stops hearing', () => {const bus = record();- emitOpenThreadPopover('t1');+ emitOpenThread('t1');bus.stop();- emitOpenThreadPopover('t2');+ emitOpenThread('t2');expect(bus.seen).toEqual(['t1']);});test('every listener sees the same signal', () => {- // The popover and the rail both subscribe; they must not diverge.+ // The panel and the rail both subscribe; they must not diverge.const a = record();const b = record();- emitOpenThreadPopover('t1');- emitOpenThreadPopover(null);+ emitOpenThread('t1');+ emitOpenThread(null);expect(a.seen).toEqual(b.seen);a.stop();b.stop();@@ -72,13 +72,13 @@ describe('the thread-popover bus', () => {describe('opening a thread opens the Comments tab beside it', () => {test('an id requests the tab; a close leaves the panel alone', () => {consumePendingDocPanelTabRequest();- emitOpenThreadPopover('t1');+ emitOpenThread('t1');// The pending-tab latch is how the panel host learns of the request even// when it has not mounted yet — the same channel every open path lands on.expect(consumePendingDocPanelTabRequest()).toBe('comments');- emitOpenThreadPopover(null);- // Dismissing a popover is not a statement about the panel.+ emitOpenThread(null);+ // Standing down from a comment is not a statement about the panel.expect(consumePendingDocPanelTabRequest()).toBeNull();});});diff --git a/packages/app/src/comments/open-thread-lifecycle.test.ts b/packages/app/src/comments/open-thread-lifecycle.test.tsnew file mode 100644index 000000000..26d1f62bf--- /dev/null+++ b/packages/app/src/comments/open-thread-lifecycle.test.ts@@ -0,0 +1,131 @@+/**+ * A thread that goes away stops being the open one.+ *+ * Every OTHER way a thread stands down is a statement about the reader —+ * clicking away in the document, Escape, re-clicking a lit margin marker. This+ * is the case with no reader in it: sending a batch resolves its comments, and+ * a resolved thread drops its highlight AND its margin marker, so nothing is+ * left on screen either pointing at the open thread or offering to clear it.+ * The store is what has to notice, because it is the only thing that sees every+ * mutation — including one made in another window, which arrives over CC1 with+ * no local call to hang the check off.+ */++import { beforeEach, describe, expect, test, vi } from 'vitest';++/** The list the mocked client answers with — reassigned per test. */+let metas: Array<Record<string, unknown>> = [];++function meta(threadId: string, state: string): Record<string, unknown> {+ return {+ threadId,+ docName: 'notes/rollout',+ anchor: { exact: 'minimal downtime', prefix: '', suffix: '', start: 0, end: 16 },+ state,+ queued: true,+ latestComment: 'still true?',+ createdBy: 'principal-abc',+ createdAt: 900,+ };+}++vi.mock('./comments-client', () => ({+ listThreads: vi.fn(async () => metas),+ createThread: vi.fn(),+ editComment: 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: [] })),+}));++// The tab request rides every open; nothing here is about the doc panel.+vi.mock('@/components/doc-panel-events', () => ({ requestDocPanelTab: vi.fn() }));++describe('the open thread across a refresh', () => {+ beforeEach(() => {+ vi.resetModules();+ vi.clearAllMocks();+ metas = [meta('t1', 'anchored')];+ });++ test('survives a refresh that still lists it as open', async () => {+ const store = await import('./store');+ await store.refresh('notes/rollout');+ store.emitOpenThread('t1');++ await store.refresh('notes/rollout');++ expect(store.getOpenThread()).toBe('t1');+ });++ test('stands down when its thread resolves', async () => {+ const store = await import('./store');+ await store.refresh('notes/rollout');+ store.emitOpenThread('t1');++ // What a send does to every comment it carries.+ metas = [meta('t1', 'resolved')];+ await store.refresh('notes/rollout');++ expect(store.getOpenThread()).toBeNull();+ });++ test('stands down when its thread is deleted', async () => {+ const store = await import('./store');+ await store.refresh('notes/rollout');+ store.emitOpenThread('t1');++ metas = [];+ await store.refresh('notes/rollout');++ expect(store.getOpenThread()).toBeNull();+ });++ test('stands down when its passage is lost, like the card that used to', async () => {+ const store = await import('./store');+ await store.refresh('notes/rollout');+ store.emitOpenThread('t1');++ // Orphaned is not open: the highlight is gone, and the card says so in the+ // panel instead. Matches what the in-doc card did with the same state.+ metas = [meta('t1', 'orphaned')];+ await store.refresh('notes/rollout');++ expect(store.getOpenThread()).toBeNull();+ });++ test('tells its subscribers, so the rail and the panel clear too', async () => {+ const store = await import('./store');+ await store.refresh('notes/rollout');+ store.emitOpenThread('t1');++ const seen: (string | null)[] = [];+ const stop = store.subscribeOpenThread((id) => seen.push(id));+ metas = [];+ await store.refresh('notes/rollout');+ stop();++ // A silent clear would leave the margin marker lit for a thread the store+ // no longer considers open — the exact failure the two-way signal exists+ // to prevent.+ expect(seen).toEqual([null]);+ });++ test('leaves a thread on ANOTHER document alone', async () => {+ // The queue spans the project, so a doc-scoped refresh routinely runs while+ // the open thread belongs to a file this refresh was not about. Checking+ // the per-doc slice would clear it for being absent from the wrong list.+ const store = await import('./store');+ metas = [meta('t1', 'anchored'), { ...meta('t2', 'anchored'), docName: 'notes/other' }];+ await store.refresh('notes/other');+ store.emitOpenThread('t2');++ await store.refresh('notes/rollout');++ expect(store.getOpenThread()).toBe('t2');+ });+});diff --git a/packages/app/src/comments/open-thread-panel.dom.test.tsx b/packages/app/src/comments/open-thread-panel.dom.test.tsxnew file mode 100644index 000000000..a0ddbed05--- /dev/null+++ b/packages/app/src/comments/open-thread-panel.dom.test.tsx@@ -0,0 +1,183 @@+/**+ * Opening a thread brings its card up in the panel.+ *+ * The comment used to be shown twice: a floating card pinned over the passage+ * AND the same comment in the panel. The floating one covered the document at+ * the moment the reader was trying to read it, so it is gone — which makes the+ * panel the only place a comment is read, and makes "the card is in the list+ * somewhere" not good enough. The card has to be IN VIEW.+ *+ * The awkward half is the ordering: opening a thread is what switches the doc+ * panel to the Comments tab, so this panel is usually MOUNTED BY the open it+ * has to answer and can never hear the signal that caused it. Reading the open+ * thread as state rather than as an event is what covers that, and the first+ * test is the one that would fail if it went back to a subscription.+ */++import * as actualLinguiMacro from '@lingui/react/macro';+import { act, cleanup, render, screen } from '@testing-library/react';+import { type ReactNode, useSyncExternalStore } from 'react';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import type { CommentThread } from './types';++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] ?? ''}`, ''),+ }),+}));++/** The open thread, as the store holds it: state with a signal over it. */+let openThreadId: string | null = null;+const snapshotListeners = new Set<() => void>();+const openListeners = new Set<(id: string | null) => void>();++/**+ * The real `emitOpenThread`, doubled: write the state, then announce it —+ * ALWAYS, including when the id has not changed. That last part is what the+ * repeat-open case turns on, so the double would hide the bug if it deduped.+ */+function openThread(id: string | null): void {+ openThreadId = id;+ for (const listener of snapshotListeners) listener();+ for (const listener of openListeners) listener(id);+}++vi.doMock('./store', () => ({+ useQueueSelection: () => [],+ setSendingAll: () => {},+ getOpenThread: () => openThreadId,+ subscribeOpenThread: (onChange: (id: string | null) => void) => {+ openListeners.add(onChange);+ return () => openListeners.delete(onChange);+ },+ useOpenThread: () =>+ useSyncExternalStore(+ (onChange: () => void) => {+ snapshotListeners.add(onChange);+ return () => snapshotListeners.delete(onChange);+ },+ () => openThreadId,+ () => null,+ ),+ subscribeFocusThread: () => () => {},+ emitOpenThread: () => {},+ toggleSending: () => {},+ deleteThread: () => {},+ editComment: () => {},+ reopenThread: () => {},+ replaceOrphan: () => {},+ setActiveThread: () => {},+ clearActiveThread: () => {},+}));++// The footer drags in the agent picker and the sessions dock; neither is what+// these tests are about.+vi.doMock('./CommentSendFooter', () => ({ CommentSendFooter: () => null }));++function thread(id: string): CommentThread {+ return {+ id,+ docName: 'recipes/stir-fry',+ target: { kind: 'body' },+ anchor: { quote: 'the tofu', prefix: '', suffix: '', start: 0, end: 8 },+ status: 'open',+ body: `comment ${id}`,+ createdAt: 1000,+ updatedAt: 1000,+ queued: false,+ };+}++const THREADS = [thread('t1'), thread('t2'), thread('t3')];++/** Which card each `scrollIntoView` was called on, by the comment it carries. */+const scrolled: string[] = [];++async function renderPanel() {+ const { CommentListPanel } = await import('./CommentListPanel');+ const { TooltipProvider } = await import('@/components/ui/tooltip');+ return render(+ <TooltipProvider>+ <CommentListPanel threads={THREADS} empty={<span>none</span>} testIdPrefix="comment-doc" />+ </TooltipProvider>,+ );+}++beforeEach(() => {+ openThreadId = null;+ scrolled.length = 0;+ // jsdom has no layout, so `scrollIntoView` is not implemented — the double is+ // both the stand-in and the probe. On `HTMLElement`, where the jsdom preload+ // puts its own no-op stub: patched one level up on `Element` instead, that+ // stub shadows this and every card scrolls silently past the probe.+ HTMLElement.prototype.scrollIntoView = function scrollIntoViewDouble(this: HTMLElement) {+ scrolled.push(this.textContent ?? '');+ };+});++afterEach(() => {+ cleanup();+ snapshotListeners.clear();+ openListeners.clear();+});++describe('the panel and the open thread', () => {+ test('scrolls to a thread opened BEFORE it mounted', async () => {+ // The real order: a highlight click opens the thread, which switches the+ // doc panel to this tab, which mounts this panel.+ openThread('t2');+ await renderPanel();++ await vi.waitFor(() => expect(scrolled.length).toBe(1));+ expect(scrolled[0]).toContain('comment t2');+ });++ test('scrolls to a thread opened while it is already up', async () => {+ await renderPanel();+ expect(scrolled).toEqual([]);++ act(() => openThread('t3'));++ await vi.waitFor(() => expect(scrolled.length).toBe(1));+ expect(scrolled[0]).toContain('comment t3');+ });++ test('scrolls again when the thread already open is opened a second time', async () => {+ // Scroll the panel away from the card, click the same highlight to come+ // back: the id has not moved, so nothing about the panel's STATE changed+ // and a state-driven scroll bails out with the render — a click that does+ // nothing at all. The ring is gone by then too, so there is not even a+ // trace of the card left to follow.+ openThread('t2');+ await renderPanel();+ await vi.waitFor(() => expect(scrolled.length).toBe(1));++ act(() => openThread('t2'));++ await vi.waitFor(() => expect(scrolled.length).toBe(2));+ expect(scrolled[1]).toContain('comment t2');+ });++ test('rings the card it lands on, so the eye finds it in a long list', async () => {+ openThread('t2');+ await renderPanel();++ const card = (await screen.findByText('comment t2')).closest('article');+ expect(card?.className).toContain('ring-2');+ });++ test('stands down for a thread this scope does not list', async () => {+ // This-doc lists one file; the queue spans the project, so the open thread+ // can be a comment on a document this panel is not showing.+ openThread('t-elsewhere');+ await renderPanel();++ // Deliberately given time to be wrong: the scroll is chased across frames,+ // so an assertion on the next tick alone would pass whatever it did.+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(scrolled).toEqual([]);+ });+});diff --git a/packages/app/src/comments/orphan-deleted-quote.dom.test.tsx b/packages/app/src/comments/orphan-deleted-quote.dom.test.tsxindex d8c0b56cc..55ea4f289 100644--- a/packages/app/src/comments/orphan-deleted-quote.dom.test.tsx+++ b/packages/app/src/comments/orphan-deleted-quote.dom.test.tsx@@ -16,7 +16,7 @@ import type { CommentThread } from './types';const QUOTE = 'add pepitas for crunch.';-function renderCard(overrides: Partial<CommentThread> = {}, showQuote = true) {+function renderCard(overrides: Partial<CommentThread> = {}) {const thread: CommentThread = {id: 't1',docName: 'recipes/vegetarian/bowls',@@ -35,8 +35,8 @@ function renderCard(overrides: Partial<CommentThread> = {}, showQuote = true) {thread={thread}cardRef={() => {}}focused={false}+ active={false}sending={false}- showQuote={showQuote}/></TooltipProvider>,);@@ -57,14 +57,6 @@ describe('an orphaned card', () => {expect(screen.getByText(/The original text was deleted/)).toBeTruthy();});- test('shows the deleted text in the popover too, where showQuote is off', () => {- // The popover suppresses the quote row because the passage sits highlighted- // underneath it. For an orphan there is no passage underneath — that being- // the whole problem — so the words have nowhere else to come from.- renderCard({}, false);- expect(screen.getByText(`“${QUOTE}”`)).toBeTruthy();- });-test('still offers the one-click recovery', () => {renderCard();expect(screen.getByText('Re-place on selected text')).toBeTruthy();diff --git a/packages/app/src/comments/popover-cross-doc.dom.test.tsx b/packages/app/src/comments/popover-cross-doc.dom.test.tsxdeleted file mode 100644index 86ccb26d8..000000000--- a/packages/app/src/comments/popover-cross-doc.dom.test.tsx+++ /dev/null@@ -1,144 +0,0 @@-/**- * Several popovers, one bus.- *- * The editor pool keeps recently visited documents mounted, and each one hosts- * its own `CommentThreadPopover` — but "open thread X" is a single project-wide- * signal that reaches all of them. Only one owns X. The others used to answer by- * BROADCASTING a close, which shut the popover the owner had just opened, and- * which instance spoke last came down to render order: clicking a commented- * passage worked or silently did nothing depending on how many tabs were open.- *- * The rule these pin: an instance may close a thread it owns and must stay- * silent about one it does not.- */--import * as actualLinguiMacro from '@lingui/react/macro';-import { cleanup, render, screen } from '@testing-library/react';-import type { ReactNode } from 'react';-import { afterEach, describe, expect, test, vi } from 'vitest';-import { TooltipProvider } from '@/components/ui/tooltip';-import type { CommentThread } from './types';--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] ?? ''}`, ''),- }),-}));--function thread(id: string, docName: string): CommentThread {- return {- id,- docName,- target: { kind: 'body' },- anchor: { quote: 'the tofu', prefix: '', suffix: '', start: 0, end: 8 },- status: 'open',- body: 'press it?',- createdAt: 1000,- updatedAt: 1000,- queued: false,- };-}--const ALFREDO = thread('t-alfredo', 'recipes/chicken-alfredo-pasta');-const SATAY = thread('t-satay', 'recipes/chicken-satay');-const ALL = [ALFREDO, SATAY];--let openPopover: ((id: string | null) => void) | null = null;-const emitted: (string | null)[] = [];--vi.doMock('./store', () => ({- useCommentThreads: (docName: string) => ALL.filter((t) => t.docName === docName),- useAllThreads: () => ALL,- useQueueSelection: () => [],- subscribeOpenThreadPopover: (cb: (id: string | null) => void) => {- // Every mounted instance subscribes; the real bus fans out to all of them,- // which is the whole point of this file.- const previous = openPopover;- openPopover = (id) => {- previous?.(id);- cb(id);- };- return () => {- openPopover = previous;- };- },- emitOpenThreadPopover: (id: string | null) => {- emitted.push(id);- },- toggleSending: () => {},- deleteThread: () => {},- editComment: () => {},- reopenThread: () => {},- replaceOrphan: () => {},- setActiveThread: () => {},- clearActiveThread: () => {},-}));--vi.doMock('@/editor/utils/get-editor-view', () => ({ getEditorView: () => null }));-vi.doMock('./anchor-search', () => ({- findQuoteRange: () => ({ from: 0, to: 8 }),- captureSelectionContext: () => ({ prefix: '', suffix: '' }),-}));-vi.doMock('./property-row-rect', () => ({- propertyRowRect: () => null,- revealPropertyValueRange: () => true,-}));--const { CommentThreadPopover } = await import('./CommentThreadPopover');--/** Two docs in the pool, each with its own popover — the real arrangement. */-function Pool() {- return (- <TooltipProvider>- {/* biome-ignore lint/suspicious/noExplicitAny: structural editor double */}- <CommentThreadPopover editor={{ state: {} } as any} docName="recipes/chicken-satay" />- {/* biome-ignore lint/suspicious/noExplicitAny: structural editor double */}- <CommentThreadPopover editor={{ state: {} } as any} docName="recipes/chicken-alfredo-pasta" />- </TooltipProvider>- );-}--afterEach(() => {- cleanup();- openPopover = null;- emitted.length = 0;-});--describe('a pool of thread popovers', () => {- test('a thread opens even with another document mounted beside it', async () => {- render(<Pool />);- openPopover?.('t-alfredo');-- expect(await screen.findByText('press it?')).toBeTruthy();- });-- test('the non-owning instance does not broadcast a close', async () => {- render(<Pool />);- openPopover?.('t-alfredo');- await screen.findByText('press it?');-- // Silence is the assertion. A `null` here is the sibling shutting the- // popover its neighbour just opened.- expect(emitted).toEqual([]);- });-- test('exactly one instance renders the thread', async () => {- render(<Pool />);- openPopover?.('t-alfredo');- await screen.findByText('press it?');-- expect(screen.getAllByText('press it?')).toHaveLength(1);- });-- test('a thread that exists nowhere still closes', async () => {- render(<Pool />);- openPopover?.('t-deleted');-- // Nobody owns it and nobody can show it, so the close is right — this is the- // case the silence rule must not swallow.- await vi.waitFor(() => expect(emitted).toContain(null));- });-});diff --git a/packages/app/src/comments/popover-retarget.dom.test.tsx b/packages/app/src/comments/popover-retarget.dom.test.tsxdeleted file mode 100644index 158046de7..000000000--- a/packages/app/src/comments/popover-retarget.dom.test.tsx+++ /dev/null@@ -1,158 +0,0 @@-/**- * Clicking a second highlight while the popover is open.- *- * The popover swaps its thread IN PLACE — the bus hands it the next id and- * there is no null in between — so the card underneath is at the same position- * in the tree with the same type across the swap. Unkeyed, React keeps that- * instance: its open edit field, the draft seeded from the FIRST comment, and- * the flag saying the edit had not settled yet all carried over to the second- * thread, and the next settle filed one comment's words as a revision of- * another. What pins the fix is that the card is a different card afterwards.- */--import * as actualLinguiMacro from '@lingui/react/macro';-import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';-import type { ReactNode } from 'react';-import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';-import { MockComposerMentionInput } from '@/components/acp/composer-mention-input.test-helper';-import { TooltipProvider } from '@/components/ui/tooltip';-import type { CommentThread } from './types';--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] ?? ''}`, ''),- }),-}));--// The real field is a ProseMirror contentEditable that jsdom cannot type into.-vi.doMock('@/editor/ComposerMentionInput', () => ({- ComposerMentionInput: MockComposerMentionInput,-}));--function thread(id: string, body: string): CommentThread {- return {- id,- docName: 'recipes/wiki',- target: { kind: 'body' },- anchor: { quote: 'the tofu', prefix: '', suffix: '', start: 0, end: 8 },- status: 'open',- body,- createdAt: 1000,- updatedAt: 1000,- queued: true,- };-}--const THREADS = [thread('t1', 'press it?'), thread('t2', 'drain it?')];-const editComment = vi.fn();--vi.doMock('./store', () => ({- useCommentThreads: () => THREADS,- useAllThreads: () => THREADS,- useQueueSelection: () => [],- subscribeOpenThreadPopover: (cb: (id: string | null) => void) => {- openPopover = cb;- return () => {- openPopover = null;- };- },- editComment,- emitOpenThreadPopover: () => {},- toggleSending: () => {},- deleteThread: () => {},- reopenThread: () => {},- replaceOrphan: () => {},- setActiveThread: () => {},- clearActiveThread: () => {},-}));--// Positioning reads a live ProseMirror view; nothing here is about where the-// card lands.-vi.doMock('@/editor/utils/get-editor-view', () => ({ getEditorView: () => null }));-vi.doMock('@/editor/active-editor', () => ({ getVisibleEditorForDoc: () => null }));-vi.doMock('./anchor-search', () => ({- findQuoteRange: () => null,- captureSelectionContext: () => ({ prefix: '', suffix: '' }),-}));-vi.doMock('./property-row-rect', () => ({- propertyRowRect: () => null,- revealPropertyValueRange: () => true,-}));-vi.doMock('./comment-chips', () => ({- propertyAddress: (key: string) => key,- revealThread: () => {},-}));--let openPopover: ((id: string | null) => void) | null = null;--async function renderPopover() {- const { CommentThreadPopover } = await import('./CommentThreadPopover');- return render(- <TooltipProvider>- {/* biome-ignore lint/suspicious/noExplicitAny: structural editor double */}- <CommentThreadPopover editor={{ state: {} } as any} docName="recipes/wiki" />- </TooltipProvider>,- );-}--beforeEach(() => editComment.mockClear());--afterEach(() => {- cleanup();- openPopover = null;-});--describe('retargeting the popover mid-edit', () => {- test('the outgoing edit is filed against the comment it was typed on', async () => {- await renderPopover();- act(() => openPopover?.('t1'));- fireEvent.click(await screen.findByRole('button', { name: /edit this comment/i }));- fireEvent.change(screen.getByRole('textbox', { name: /edit this comment/i }), {- target: { value: 'press it overnight' },- });-- // The reader clicks another highlight without dismissing this one first.- // Wrapped, because the bus is not a React event — without flushing the- // re-render the assertions would read the pre-swap tree and pass either way.- act(() => openPopover?.('t2'));-- // Click-away saves, and the words belong to t1 — the card that held them.- expect(editComment).toHaveBeenCalledWith('t1', 'press it overnight');- expect(editComment).toHaveBeenCalledTimes(1);- });-- test('the next thread arrives as a fresh card, not mid-edit', async () => {- await renderPopover();- act(() => openPopover?.('t1'));- fireEvent.click(await screen.findByRole('button', { name: /edit this comment/i }));- fireEvent.change(screen.getByRole('textbox', { name: /edit this comment/i }), {- target: { value: 'press it overnight' },- });-- act(() => openPopover?.('t2'));-- // No field open, and the second comment's own text on screen — the field- // used to survive the swap still holding the first comment's draft.- expect(screen.queryByRole('textbox', { name: /edit this comment/i })).toBeNull();- expect(screen.getByTestId('thread-comment-body').textContent).toBe('drain it?');- });-- test('editing the second comment writes against the second id', async () => {- await renderPopover();- act(() => openPopover?.('t1'));- act(() => openPopover?.('t2'));-- fireEvent.click(await screen.findByRole('button', { name: /edit this comment/i }));- const field = screen.getByRole('textbox', { name: /edit this comment/i });- // Seeded from t2, so the swap re-ran the seed rather than keeping t1's.- expect((field as HTMLTextAreaElement).value).toBe('drain it?');-- fireEvent.change(field, { target: { value: 'drain it twice' } });- fireEvent.click(screen.getByRole('button', { name: /save this comment/i }));-- expect(editComment).toHaveBeenCalledWith('t2', 'drain it twice');- });-});diff --git a/packages/app/src/comments/popover-send-tick.dom.test.tsx b/packages/app/src/comments/popover-send-tick.dom.test.tsxdeleted file mode 100644index 95dc2430f..000000000--- a/packages/app/src/comments/popover-send-tick.dom.test.tsx+++ /dev/null@@ -1,94 +0,0 @@-/**- * The in-document popover's send tick reflects the store.- *- * The popover renders the panels' card, and for a while it rendered it without- * saying whether the comment was ticked. The box drew permanently unchecked- * while the click behind it went through to the store — state and view- * disagreeing, which reads as "the checkbox is broken" when nothing about the- * send was. The prop is required now, so a host that forgets cannot compile;- * this covers the half a type cannot: that the value passed is the LIVE one.- */--import * as actualLinguiMacro from '@lingui/react/macro';-import { cleanup, render, screen } from '@testing-library/react';-import type { ReactNode } from 'react';-import { afterEach, describe, expect, test, vi } from 'vitest';-import { TooltipProvider } from '@/components/ui/tooltip';-import type { CommentThread } from './types';--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] ?? ''}`, ''),- }),-}));--const THREAD: CommentThread = {- id: 't1',- docName: 'recipes/wiki',- target: { kind: 'body' },- anchor: { quote: "er's d", prefix: '', suffix: '', start: 0, end: 6 },- status: 'open',- body: 'hi',- createdAt: 1000,- updatedAt: 1000,- queued: true,-};--// `t1` is in the send list — the state the popover used to draw as unchecked.-vi.doMock('./store', () => ({- useCommentThreads: () => [THREAD],- useAllThreads: () => [THREAD],- useQueueSelection: () => ['t1'],- subscribeOpenThreadPopover: (cb: (id: string | null) => void) => {- openPopover = cb;- return () => {- openPopover = null;- };- },- emitOpenThreadPopover: () => {},- toggleSending: () => {},- deleteThread: () => {},- editComment: () => {},- reopenThread: () => {},- replaceOrphan: () => {},- setActiveThread: () => {},- clearActiveThread: () => {},-}));--// Positioning reads a live ProseMirror view; nothing here is about where the-// card lands.-vi.doMock('@/editor/utils/get-editor-view', () => ({ getEditorView: () => null }));-vi.doMock('./anchor-search', () => ({- findQuoteRange: () => null,- captureSelectionContext: () => ({ prefix: '', suffix: '' }),-}));-vi.doMock('./property-row-rect', () => ({- propertyRowRect: () => null,- revealPropertyValueRange: () => true,-}));--let openPopover: ((id: string | null) => void) | null = null;--afterEach(() => {- cleanup();- openPopover = null;-});--describe('the thread popover', () => {- test('draws its tick from the send list, not from nothing', async () => {- const { CommentThreadPopover } = await import('./CommentThreadPopover');- render(- <TooltipProvider>- {/* biome-ignore lint/suspicious/noExplicitAny: structural editor double */}- <CommentThreadPopover editor={{ state: {} } as any} docName="recipes/wiki" />- </TooltipProvider>,- );- openPopover?.('t1');-- const tick = await screen.findByRole('checkbox');- expect(tick.getAttribute('data-state')).toBe('checked');- });-});diff --git a/packages/app/src/comments/project-file-groups.dom.test.tsx b/packages/app/src/comments/project-file-groups.dom.test.tsxindex 7a36e59ae..2056676f0 100644--- a/packages/app/src/comments/project-file-groups.dom.test.tsx+++ b/packages/app/src/comments/project-file-groups.dom.test.tsx@@ -34,7 +34,9 @@ vi.doMock('./store', () => ({setSendingAll: (ids: readonly string[], sending: boolean) => {bulkCalls.push({ ids: [...ids], sending });},- usePinnedThread: () => null,+ useOpenThread: () => null,+ getOpenThread: () => null,+ subscribeOpenThread: () => () => {},subscribeFocusThread: () => () => {},toggleSending: () => {},deleteThread: () => {},diff --git a/packages/app/src/comments/property-anchor-click.dom.test.tsx b/packages/app/src/comments/property-anchor-click.dom.test.tsxindex cb0ad0e0f..a611c768e 100644--- a/packages/app/src/comments/property-anchor-click.dom.test.tsx+++ b/packages/app/src/comments/property-anchor-click.dom.test.tsx@@ -3,10 +3,9 @@* `<textarea>` in a real property row.** The matcher's own rules are pinned in `property-anchor-click.test.ts`. What- * needs a DOM is everything the matcher cannot see — that the listener finds the- * row, reads the caret the browser placed, leaves the click otherwise alone, and- * stamps the attribute the popover's dismisser looks for BEFORE that dismisser- * runs.+ * needs a DOM is everything the matcher cannot see — that the listener finds+ * the row, reads the caret the browser placed, and leaves the click otherwise+ * alone.*/import { cleanup, render } from '@testing-library/react';@@ -19,9 +18,12 @@ const opened: (string | null)[] = [];let threads: CommentThread[] = [];vi.doMock('./store', () => ({- emitOpenThreadPopover: (id: string | null) => {+ emitOpenThread: (id: string | null) => {opened.push(id);},+ // The double IS the store's state here: the listener reads it to decide+ // whether a click on an uncommented value has anything to stand down.+ getOpenThread: () => (opened.length === 0 ? null : opened[opened.length - 1]),getThreads: () => threads,}));@@ -92,6 +94,17 @@ describe('clicking a commented property value', () => {expect(opened).toEqual([]);});+ test('a click into an uncommented value stands the open thread down', () => {+ // Same gesture the body reads as "I have moved on": with a comment open,+ // clicking text that carries none has to clear it, or the highlight stays+ // lit for a passage the reader has left. The two tests above pin the other+ // half — with nothing open, the same click says nothing at all.+ const { getByLabelText } = render(<Panel />);+ clickAt(getByLabelText('cuisine') as HTMLTextAreaElement, 8);+ clickAt(getByLabelText('protein') as HTMLTextAreaElement, 3);+ expect(opened).toEqual(['t1', null]);+ });+test('the click is not consumed — the caret the reader aimed at stands', () => {const { getByLabelText } = render(<Panel />);const field = getByLabelText('cuisine') as HTMLTextAreaElement;@@ -102,66 +115,4 @@ describe('clicking a commented property value', () => {expect(event.defaultPrevented).toBe(false);expect(field.selectionStart).toBe(8);});-- test('mousedown stamps the attribute the popover dismisser exempts', () => {- const { getByLabelText } = render(<Panel />);- const field = getByLabelText('cuisine') as HTMLTextAreaElement;- field.setSelectionRange(8, 8);- // Read during the dismisser's own phase: it listens on `document` in the- // bubble phase, which is strictly after this hook's capture listener.- let seenDuringBubble: string | null = null;- const spy = (event: Event) => {- seenDuringBubble =- (event.target as HTMLElement)- .closest('[data-comment-thread]')- ?.getAttribute('data-comment-thread') ?? null;- };- document.addEventListener('mousedown', spy);- field.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));- document.removeEventListener('mousedown', spy);-- expect(seenDuringBubble).toBe('t1');- });-- test('clicking the same passage twice keeps the thread open', () => {- // The field report: the first click opened the thread and the second put it- // back. Reproduced against a stand-in for the real dismisser, because the- // second click is the FIRST one it is registered for — `CommentThreadPopover`- // only binds `mousedown` while a thread is showing, so click one never meets- // it and click two always does.- const { getByLabelText } = render(<Panel />);- const field = getByLabelText('cuisine') as HTMLTextAreaElement;- clickAt(field, 8);-- const dismisser = (event: Event) => {- const target = event.target as HTMLElement | null;- if (target?.closest('[data-comment-thread]')) return;- opened.push(null);- };- document.addEventListener('mousedown', dismisser);- clickAt(field, 8);- document.removeEventListener('mousedown', dismisser);-- // No `null` in the middle: the dismisser has to see the attribute and stand- // down, or the popover closes and reopens on one gesture.- expect(opened).toEqual(['t1', 't1']);- });-- test('an uncommented value carries no such attribute', () => {- const { getByLabelText } = render(<Panel />);- const field = getByLabelText('protein') as HTMLTextAreaElement;- field.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));- expect(field.hasAttribute('data-comment-thread')).toBe(false);- });-- test('the attribute clears once the thread is gone', () => {- const { getByLabelText } = render(<Panel />);- const field = getByLabelText('cuisine') as HTMLTextAreaElement;- field.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));- expect(field.getAttribute('data-comment-thread')).toBe('t1');-- threads = [];- field.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));- expect(field.hasAttribute('data-comment-thread')).toBe(false);- });});diff --git a/packages/app/src/comments/property-anchor-click.ts b/packages/app/src/comments/property-anchor-click.tsindex 99f579484..dbd9a7afd 100644--- a/packages/app/src/comments/property-anchor-click.ts+++ b/packages/app/src/comments/property-anchor-click.ts@@ -25,35 +25,11 @@import { type RefObject, useEffect } from 'react';import { locateInValue } from './property-row-rect';-import { emitOpenThreadPopover, getThreads } from './store';+import { emitOpenThread, getOpenThread, getThreads } from './store';import type { CommentThread } from './types';const ROW_SELECTOR = '[data-testid="property-row"]';-/**- * Marks a value control as belonging to a thread, so the popover's outside-click- * dismisser lets the click through the way it already does for a body highlight- * and a rail marker.- *- * Without it, clicking a commented value while its own popover is open closes it- * on `mousedown` and this listener reopens it on `click` — one gesture, two- * renders, a visible flash. The body never had that problem because its- * decoration carries the same attribute.- *- * Stamped just-in-time on `mousedown` rather than kept in sync with the store:- * the answer depends on the control's CURRENT value (a passage the reader has- * since typed over is no longer there), and the only moment it has to be right- * is the one between the click starting and the dismisser reading it. An- * attribute maintained ahead of time would be a second copy of a fact that- * changes on every keystroke.- *- * Set from here rather than rendered by `FrontmatterRow`: that row is shared by- * templates, skills, and folder cards, none of which have threads, and it is- * kept free of this subsystem for the same reason the comment BUTTON arrives as- * a slot.- */-const THREAD_ATTR = 'data-comment-thread';-/** The row's own key — its last path step, which is what the DOM carries. */function rowKeyOf(thread: CommentThread): string | null {if (thread.target.kind !== 'property') return null;@@ -149,16 +125,6 @@ function caretOffset(control: HTMLTextAreaElement | HTMLInputElement): number |}}-/** Every thread with a range in this control's value, or `[]`. */-function threadsOn(- control: HTMLTextAreaElement | HTMLInputElement,- docName: string,-): PlacedRange[] {- const rowKey = rowKeyFor(control);- if (rowKey === null) return [];- return placeValueThreads(getThreads(docName), rowKey, control.value);-}-/*** Wire click-to-open for every commented value in one property panel.*@@ -175,20 +141,9 @@ export function usePropertyAnchorClick(const container = containerRef.current;if (container === null) return;- // Capture phase, so this runs before the popover's own document-level- // `mousedown` dismisser — capture descends to the target before bubbling- // climbs back to `document`, and that ordering is the whole point.- const onMouseDownCapture = (event: MouseEvent) => {- const control = valueControl(event.target);- if (control === null) return;- const placed = threadsOn(control, docName);- if (placed.length === 0) control.removeAttribute(THREAD_ATTR);- else control.setAttribute(THREAD_ATTR, placed[0].threadId);- };-// The click itself is NOT consumed — no `preventDefault`, no `focus` call.- // The caret lands where the reader aimed it and the popover opens beside- // it, which is the body's bargain too: a commented passage stays ordinary+ // The caret lands where the reader aimed it and the comment comes up in the+ // panel, which is the body's bargain too: a commented value stays ordinary// editable text rather than becoming a button.const onClick = (event: MouseEvent) => {const control = valueControl(event.target);@@ -201,13 +156,19 @@ export function usePropertyAnchorClick(const offset = caretOffset(control);if (offset === null) return;const threadId = threadAtValueOffset(getThreads(docName), rowKey, control.value, offset);- if (threadId !== null) emitOpenThreadPopover(threadId);+ if (threadId !== null) {+ emitOpenThread(threadId);+ return;+ }+ // Clicked into a value that carries no comment — the same "I have moved+ // on" the body reads from a click beside a highlight, so the open thread+ // stands down here too. Guarded, so an ordinary click in an ordinary+ // field does not dispatch to every panel.+ if (getOpenThread() !== null) emitOpenThread(null);};- container.addEventListener('mousedown', onMouseDownCapture, true);container.addEventListener('click', onClick);return () => {- container.removeEventListener('mousedown', onMouseDownCapture, true);container.removeEventListener('click', onClick);};}, [containerRef, docName]);diff --git a/packages/app/src/comments/property-row-rect.ts b/packages/app/src/comments/property-row-rect.tsindex 0cc099493..eb064b77e 100644--- a/packages/app/src/comments/property-row-rect.ts+++ b/packages/app/src/comments/property-row-rect.ts@@ -1,10 +1,10 @@/*** 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+ * A property comment has no ProseMirror position, which is why the rail cannot+ * ask the editor to place its marker. It 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.*diff --git a/packages/app/src/comments/queued-toggle.dom.test.tsx b/packages/app/src/comments/queued-toggle.dom.test.tsxindex f165f22ee..403e91b5c 100644--- a/packages/app/src/comments/queued-toggle.dom.test.tsx+++ b/packages/app/src/comments/queued-toggle.dom.test.tsx@@ -36,7 +36,7 @@ function renderCard(t: CommentThread, sending = true) {// The app has one at its root; a standalone render has to bring its own.return render(<TooltipProvider>- <ThreadCard thread={t} cardRef={() => {}} focused={false} sending={sending} />+ <ThreadCard thread={t} cardRef={() => {}} focused={false} active={false} sending={sending} /></TooltipProvider>,);}@@ -125,7 +125,7 @@ describe('the active-thread tint', () => {</TooltipProvider>,);// The same statement the document already makes in the other direction —- // touching a card deepens its passage; an open popover tints its card.+ // touching a card deepens its passage; the open thread tints its card.// A WASH, deliberately not a border: an outline reads as "this comment is// picked", and being read is not being selected — the tick owns that.const card = screen.getByRole('article');@@ -136,7 +136,13 @@ describe('the active-thread tint', () => {test('an inactive card carries none', () => {render(<TooltipProvider>- <ThreadCard thread={thread()} cardRef={() => {}} focused={false} sending={false} />+ <ThreadCard+ thread={thread()}+ cardRef={() => {}}+ focused={false}+ active={false}+ sending={false}+ /></TooltipProvider>,);expect(screen.getByRole('article').className).not.toContain('bg-amber-500/10');diff --git a/packages/app/src/comments/reveal-comment.dom.test.ts b/packages/app/src/comments/reveal-comment.dom.test.tsindex a35b88ab7..33da7b642 100644--- a/packages/app/src/comments/reveal-comment.dom.test.ts+++ b/packages/app/src/comments/reveal-comment.dom.test.ts@@ -93,7 +93,7 @@ vi.doMock('@/editor/active-editor', () => ({vi.doMock('./store', () => ({emitFocusThread: (id: string) => captured.focused.push(id),- emitOpenThreadPopover: (id: string) => captured.opened.push(id),+ emitOpenThread: (id: string) => captured.opened.push(id),}));const toasted: string[] = [];diff --git a/packages/app/src/comments/reveal-comment.ts b/packages/app/src/comments/reveal-comment.tsindex 334e73154..da466e58a 100644--- a/packages/app/src/comments/reveal-comment.ts+++ b/packages/app/src/comments/reveal-comment.ts@@ -28,7 +28,7 @@ import { getVisibleEditorForDoc, subscribeEditorRegistry } from '@/editor/activeimport { hashFromDocName } from '@/lib/doc-hash';import { type AnchorContext, findQuoteRange } from './anchor-search';import { scrollAnchorIntoView } from './scroll-to-anchor';-import { emitFocusThread, emitOpenThreadPopover } from './store';+import { emitFocusThread, emitOpenThread } from './store';/** Give up on a document that never arrives (bad docName, failed load, dead sync). */const REVEAL_WAIT_MS = 10_000;@@ -102,7 +102,7 @@ export function revealComment(input: {if (input.quote === '') {if (landedAt === null) {landedAt = Date.now();- emitOpenThreadPopover(input.threadId);+ emitOpenThread(input.threadId);}return true;}@@ -130,7 +130,7 @@ export function revealComment(input: {if (!scrollAnchorIntoView(editor, range, input.docName, { instant: true })) return false;if (landedAt === null) {landedAt = Date.now();- emitOpenThreadPopover(input.threadId);+ emitOpenThread(input.threadId);}return true;};diff --git a/packages/app/src/comments/scroll-to-anchor.ts b/packages/app/src/comments/scroll-to-anchor.tsindex 6a83183ad..bb3d7a643 100644--- a/packages/app/src/comments/scroll-to-anchor.ts+++ b/packages/app/src/comments/scroll-to-anchor.ts@@ -12,7 +12,7 @@* 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.+ * declares, and keep room beneath it.*/import type { Editor } from '@tiptap/react';@@ -23,11 +23,11 @@ import {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.+ * Room left below the passage. Generous on purpose — a passage landing on the+ * last visible line is technically on screen and useless: the reader arrives at+ * a comment and cannot see a word of what follows the words it is about.*/-const CARD_ROOM_PX = 220;+const BOTTOM_ROOM_PX = 220;/** Breathing room below the toolbar when we do move, so it isn't flush. */const LEAD_PX = 24;@@ -90,7 +90,7 @@ export interface AnchorViewport {*/export function scrollDeltaForAnchor(v: AnchorViewport): number {const restTop = v.viewTop + v.insetTop;- const restBottom = v.viewBottom - CARD_ROOM_PX;+ const restBottom = v.viewBottom - BOTTOM_ROOM_PX;if (v.anchorTop >= restTop && v.anchorBottom <= restBottom) return 0;return v.anchorTop - (restTop + LEAD_PX);}@@ -119,7 +119,7 @@ export function scrollportInsetTop(container: HTMLElement): number {}/**- * Bring a comment's passage into a readable position, with room for its card.+ * Bring a comment's passage into a readable position, with room beneath it.** Returns whether the navigation RAN — see {@link applyJumpScroll} for what can* decline it and for the two scroll writers a jump has to out-rank. `docName` isdiff --git a/packages/app/src/comments/store.ts b/packages/app/src/comments/store.tsindex 70621003b..8b002761c 100644--- a/packages/app/src/comments/store.ts+++ b/packages/app/src/comments/store.ts@@ -5,7 +5,7 @@* (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).+ * (focus a thread, open a thread, start the composer).** useSyncExternalStore contract: `getThreads(docName)` returns a referentially* stable array between refreshes — the array identity changes only when data@@ -152,6 +152,29 @@ export async function refresh(docName?: string): Promise<void> {// whatever reads them next, so a subscriber reading during this same tick// cannot see them disagree with `allThreads`.bump();+ standDownIfGone(nextAll);+}++/**+ * A thread that has been resolved or deleted cannot still be the open one.+ *+ * Every reader gesture that stands a thread down is a statement about the+ * READER — clicking away, Escape, re-clicking a lit marker. This is the other+ * half: the thread itself going away. Sending a batch resolves its comments,+ * and a resolved thread drops its highlight and its margin marker, so the open+ * thread would otherwise be a comment with nothing left on screen pointing at+ * it — and nothing left to click to clear it either.+ *+ * Here rather than at each mutation because every one of them lands its data+ * through {@link refresh}, including changes made in another window that arrive+ * over CC1 with no local call to hang this off. Project-wide, not per doc: the+ * open thread can belong to a document this refresh was not about, and a+ * per-doc check would clear it for being absent from the wrong list.+ */+function standDownIfGone(threads: readonly CommentThread[]): void {+ if (openThreadId === null) return;+ if (threads.some((thread) => thread.id === openThreadId && thread.status === 'open')) return;+ emitOpenThread(null);}/**@@ -725,7 +748,7 @@ async function runDispatch(// ---------------------------------------------------------------------------const FOCUS_EVENT = 'open-knowledge:comment-focus-thread';-const POPOVER_EVENT = 'open-knowledge:comment-open-popover';+const OPEN_THREAD_EVENT = 'open-knowledge:comment-open-thread';const START_EVENT = 'open-knowledge:comment-start';const POSTED_EVENT = 'open-knowledge:comment-posted';@@ -745,7 +768,7 @@ export function subscribeFocusThread(onFocus: (threadId: string) => void): () =>}/**- * Which thread the reader is on right now — its popover is open, or the pointer+ * Which thread the reader is on right now — it is the open one, 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@@ -754,14 +777,14 @@ export function subscribeFocusThread(onFocus: (threadId: string) => void): () =>* 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 openThreadId: 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. */+/** Pointing at something wins over the open thread; it's the newer intent. */function recomputeActive(): void {- const next = pointedThreadId ?? pinnedThreadId;+ const next = pointedThreadId ?? openThreadId;if (next === activeThreadId) return;activeThreadId = next;for (const listener of activeListeners) listener();@@ -781,7 +804,7 @@ export function setActiveThread(threadId: string | null): void {* 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.+ * thread stays active underneath.*/export function clearActiveThread(threadId: string): void {if (pointedThreadId !== threadId) return;@@ -797,55 +820,69 @@ export function subscribeActiveThread(listener: () => void): () => void {}/**- * The thread whose in-doc popover is OPEN, for React — deliberately narrower- * than the active thread, which also follows the pointer. The panel's card- * wash keys on this: hover-driven washing meant every card lit itself up as- * the pointer crossed it, noise with no information. A popover being open is- * a fact worth mirroring; a pointer passing through is not.+ * The OPEN thread, for React — deliberately narrower than the active thread,+ * which also follows the pointer. The panel's card wash keys on this, and so+ * does the scroll that brings the card into view: hover-driven washing meant+ * every card lit itself up as the pointer crossed it, noise with no+ * information. A thread being open is a fact worth mirroring; a pointer passing+ * through is not.*/-export function usePinnedThread(): string | null {- return useSyncExternalStore(subscribePinnedThread, getPinnedThread, () => null);+export function useOpenThread(): string | null {+ return useSyncExternalStore(subscribeOpenThreadChanges, getOpenThread, () => null);}// Module-level, like every other binding here: `useSyncExternalStore` tears the// subscription down and rebuilds it whenever the subscribe function's identity// changes, so an inline lambda re-subscribes on every render of every panel// reading this.-function subscribePinnedThread(listener: () => void): () => void {- return subscribeOpenThreadPopover(() => listener());+function subscribeOpenThreadChanges(listener: () => void): () => void {+ return subscribeOpenThread(() => listener());}-function getPinnedThread(): string | null {- return pinnedThreadId;+/**+ * The open thread, read imperatively.+ *+ * For the handlers that have to know whether anything is open before they act —+ * the click that lands beside a highlight rather than on one, and stands the+ * open thread down. They run outside React (a ProseMirror plugin, a DOM+ * listener), so the hook above is not available to them.+ */+export function getOpenThread(): string | null {+ return openThreadId;}/**- * Which thread's in-doc popover is open — `null` for none.+ * Which thread the reader has open — `null` for none.+ *+ * The comment itself is shown in ONE place, the Comments panel: this switches+ * the doc panel to that tab, the panel scrolls to the card and rings it, and+ * the passage deepens in the document underneath. It used to also float a card+ * over the text at the passage, which covered the document at the moment the+ * reader was trying to read it, and put the same comment on screen twice.+ *+ * One signal both ways, rather than "open" one-way. The open thread used to+ * clear itself privately (Escape, outside click, thread resolved), so the+ * margin rail never learned about it: the rail kept a marker lit for a card+ * that was gone, and could not tell whether clicking a marker should open or+ * close.*- * 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.+ * The tab request lives here rather than at each open site (highlight click,+ * margin marker, property value, panel jump) so no path can forget; it is a+ * no-op when the tab is already showing, and closing (null) deliberately+ * leaves the panel as it is — the reader opened it, and standing down from one+ * comment is not a statement about the panel.*/-export function emitOpenThreadPopover(threadId: string | null): void {- pinnedThreadId = threadId;+export function emitOpenThread(threadId: string | null): void {+ openThreadId = threadId;recomputeActive();- // Opening a thread also opens the Comments tab beside it — the popover shows- // ONE comment, and the panel is where its neighbours, its checkbox column,- // and the send all live. Here rather than at each open site (highlight click,- // margin marker, jump) so no path can forget; a no-op when the tab is already- // showing, and closing (null) deliberately leaves the panel as it is — the- // reader opened it, dismissing a popover is not a statement about it.if (threadId !== null) requestDocPanelTab('comments');- bus.dispatchEvent(new CustomEvent(POPOVER_EVENT, { detail: threadId }));+ bus.dispatchEvent(new CustomEvent(OPEN_THREAD_EVENT, { detail: threadId }));}-export function subscribeOpenThreadPopover(- onChange: (threadId: string | null) => void,-): () => void {+export function subscribeOpenThread(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);+ bus.addEventListener(OPEN_THREAD_EVENT, handler);+ return () => bus.removeEventListener(OPEN_THREAD_EVENT, handler);}/**diff --git a/packages/app/src/comments/thread-card-click.dom.test.tsx b/packages/app/src/comments/thread-card-click.dom.test.tsxindex e598f0ef3..56aec63a9 100644--- a/packages/app/src/comments/thread-card-click.dom.test.tsx+++ b/packages/app/src/comments/thread-card-click.dom.test.tsx@@ -34,7 +34,7 @@ vi.doMock('./store', () => ({captured.deleted += 1;},editComment: () => {},- emitOpenThreadPopover: () => {},+ emitOpenThread: () => {},reopenThread: () => {},replaceOrphan: () => {},setActiveThread: () => {},@@ -60,15 +60,15 @@ function thread(overrides: Partial<CommentThread> = {}): CommentThread {};}-function renderCard(overrides: Partial<CommentThread> = {}, showQuote = true) {+function renderCard(overrides: Partial<CommentThread> = {}) {return render(<TooltipProvider><ThreadCardthread={thread(overrides)}cardRef={() => {}}focused={false}+ active={false}sending={false}- showQuote={showQuote}/></TooltipProvider>,);@@ -130,12 +130,6 @@ describe('clicking a card', () => {fireEvent.click(screen.getByRole('article'));expect(captured.toggled).toEqual([]);});-- test('the popover card has no batch column beside it, so its body does nothing', () => {- renderCard({}, false);- fireEvent.click(screen.getByRole('article'));- expect(captured.toggled).toEqual([]);- });});/**diff --git a/packages/app/src/comments/thread-edit-save.dom.test.tsx b/packages/app/src/comments/thread-edit-save.dom.test.tsxindex c538f5156..44dd040fc 100644--- a/packages/app/src/comments/thread-edit-save.dom.test.tsx+++ b/packages/app/src/comments/thread-edit-save.dom.test.tsx@@ -41,7 +41,7 @@ vi.doMock('./store', () => ({editComment,clearActiveThread: () => {},deleteThread,- emitOpenThreadPopover: () => {},+ emitOpenThread: () => {},reopenThread: () => {},replaceOrphan: () => {},setActiveThread: () => {},@@ -68,7 +68,7 @@ function thread(overrides: Partial<CommentThread> = {}): CommentThread {function renderEditing(t: CommentThread = thread()) {const view = render(<TooltipProvider>- <ThreadCard thread={t} cardRef={() => {}} focused={false} sending={false} />+ <ThreadCard thread={t} cardRef={() => {}} focused={false} active={false} sending={false} /></TooltipProvider>,);fireEvent.click(screen.getByRole('button', { name: /edit this comment/i }));diff --git a/packages/app/src/comments/thread-edited-stamp.dom.test.tsx b/packages/app/src/comments/thread-edited-stamp.dom.test.tsxindex 319f821c9..0987e0a2b 100644--- a/packages/app/src/comments/thread-edited-stamp.dom.test.tsx+++ b/packages/app/src/comments/thread-edited-stamp.dom.test.tsx@@ -35,7 +35,13 @@ function renderEdited(updatedAt: number) {// The card's hints are shadcn Tooltips, which Radix requires a provider for.return render(<TooltipProvider>- <ThreadCard thread={thread} cardRef={() => {}} focused={false} sending={false} />+ <ThreadCard+ thread={thread}+ cardRef={() => {}}+ focused={false}+ active={false}+ sending={false}+ /></TooltipProvider>,);}diff --git a/packages/app/src/components/DocPanel.dom.test.tsx b/packages/app/src/components/DocPanel.dom.test.tsxindex 2a4a68fd7..0127f37a1 100644--- a/packages/app/src/components/DocPanel.dom.test.tsx+++ b/packages/app/src/components/DocPanel.dom.test.tsx@@ -128,12 +128,17 @@ describe('DocPanel — tab gating', () => {expect(screen.getByTestId('outline-panel')).toBeTruthy();});- test('single-file mode keeps only Outline + Problems', () => {+ test('single-file mode keeps Outline + Problems + Comments', () => {singleFileValue = true;// Persisted selection is 'graph' — it must coerce back to Outline rather// than render a now-hidden panel.renderPanel('graph');- expect(screen.getAllByRole('tab')).toHaveLength(2);+ // Links, Graph and Timeline need a knowledge base or a git history and go.+ // Comments STAYS: a lone file can carry comments like any other, and this+ // panel is the only place a comment is read — dropping the tab left them+ // unreachable.+ expect(screen.getAllByRole('tab')).toHaveLength(3);+ expect(screen.getByRole('tab', { name: /comments/i })).toBeTruthy();expect(screen.getByTestId('outline-panel')).toBeTruthy();});diff --git a/packages/app/src/components/DocPanel.tsx b/packages/app/src/components/DocPanel.tsxindex b5d2654e5..2183c9bab 100644--- a/packages/app/src/components/DocPanel.tsx+++ b/packages/app/src/components/DocPanel.tsx@@ -36,14 +36,13 @@ export const TABS: { id: PanelTab; icon: typeof ListTree }[] = [{ id: 'graph', icon: Network },{ id: 'timeline', icon: Clock },{ 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 }[] = [+ // One Comments tab, carrying its own This-doc / This-project scope toggle.{ id: 'comments', icon: MessageSquare },];+/** What a `ok <file>` session keeps — see `tabs` below for why each one. */+const SINGLE_FILE_TABS: readonly PanelTab[] = ['outline', 'problems', 'comments'];+function countsOf(diagnostics: readonly { severity: string }[]): DocProblemCounts {let errorCount = 0;let warningCount = 0;@@ -182,25 +181,26 @@ export function DocPanel({},);};- // Single-file `ok <file>` keeps only the Outline + Problems tabs. Links/Graph- // need a multi-doc knowledge base, and Timeline is git history — all empty or- // inert for a lone git-off file; linting applies to any single file. Coerce a- // persisted now-hidden selection back to outline so the rail never renders a+ // Single-file `ok <file>` drops Links, Graph and Timeline: the first two need+ // a multi-doc knowledge base and the third is git history, all empty or inert+ // for a lone git-off file. Linting applies to any single file, so Problems+ // stays — and so does Comments: the queue spans documents, which is why that+ // tab used to go too, but the panel is where a comment is READ, and a+ // single-file session can carry comments like any other, so withholding it+ // left them unreadable. What single-file drops there is the project SCOPE+ // inside the tab, which `CommentsTab` handles. A persisted selection naming a+ // dropped tab coerces back to Outline below, so the rail never renders a// hidden panel.const singleFile = useSingleFileMode();- 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 tabs = singleFile ? TABS.filter((tab) => SINGLE_FILE_TABS.includes(tab.id)) : TABS;const effectiveTab: PanelTab = tabs.some((tab) => tab.id === activeTab) ? activeTab : 'outline';const showTabStrip = mode === 'doc' && tabs.length > 1;// Published for surfaces that offer a route TO the queue — the selection// composer withholds its "View comments" button while the reader is already// looking at one. The effective tab rather than `activeTab`: a persisted- // 'comments' selection is coerced away in single-file mode, and the button- // must stay on offer when the tab it points at is not the one showing.+ // selection can name a tab this mode does not offer (Links and Graph in+ // single-file), and the button must stay on offer when the tab it points at+ // is not the one showing.useEffect(() => {setCommentsPanelOnScreen(!isCollapsed && mode === 'doc' && effectiveTab === 'comments');return () => setCommentsPanelOnScreen(false);diff --git a/packages/app/src/editor/TiptapEditor.tsx b/packages/app/src/editor/TiptapEditor.tsxindex 02d18387c..69a95df1b 100644--- a/packages/app/src/editor/TiptapEditor.tsx+++ b/packages/app/src/editor/TiptapEditor.tsx@@ -35,7 +35,6 @@ 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';@@ -1717,7 +1716,6 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({shortcutEnabled={docName === activeDocName}/><CommentAnchorLayer editor={editor} docName={docName} />- <CommentThreadPopover editor={editor} docName={docName} />{docName === activeDocName && <CommentMarginRail editor={editor} docName={docName} />}</CommentsBoundary>)}diff --git a/packages/app/tests/stress/comment-opens-in-panel.e2e.ts b/packages/app/tests/stress/comment-opens-in-panel.e2e.tsnew file mode 100644index 000000000..a0ddabd93--- /dev/null+++ b/packages/app/tests/stress/comment-opens-in-panel.e2e.ts@@ -0,0 +1,201 @@+/**+ * A comment is read in the doc panel, never over the document.+ *+ * Clicking a highlighted passage (or its margin icon) used to float the thread+ * up as a card pinned to the text, Google-Docs style. It covered the paragraphs+ * around the passage — the ones you need in order to judge the comment — and+ * printed the same comment twice, since the panel was showing it as well.+ *+ * This is the tier that can tell those two apart: the card portalled to+ * `document.body`, so no unit test of either surface sees the doubling. What+ * this pins is the whole user-visible contract — one copy of the comment, and+ * that copy inside the Comments tab.+ *+ * Requires: Playwright browsers installed. Server provided per-worker by the+ * `workerServer` fixture in `_helpers/fixtures.ts`.+ */++import { expect, test, waitForActiveProviderSynced } from './_helpers';++const PASSAGE = 'toast the pepitas';+const SEED = `Warm the bowl, then ${PASSAGE} until they pop.\n\nServe with the dressing on the side.`;+const COMMENT = 'Toast or roast? Say which.';++/** The comment body, wherever in the page it is rendered. */+const commentBodies = '[data-testid="thread-comment-body"]';++test('clicking a commented passage shows the comment in the panel, not over the doc', async ({+ page,+ api,+}) => {+ const docName = `comment-in-panel-${Date.now()}`;+ await api.seedDocs([{ name: docName, markdown: SEED }]);++ const created = await page.request.post('/api/comments', {+ data: { docName, quote: PASSAGE, body: COMMENT },+ });+ expect(created.ok()).toBe(true);++ await page.goto(`/#/${docName}`);+ await waitForActiveProviderSynced(page);++ const editor = page.locator('.tiptap-editor .ProseMirror').first();+ await expect(editor).toContainText('Warm the bowl');++ // The highlight the thread anchors to — the thing a reader clicks.+ const highlight = editor.locator('[data-comment-thread]').first();+ await expect(highlight).toBeVisible();+ // Nothing is showing the comment yet: the panel opens on the click, and this+ // is what makes the assertions below about THIS click.+ await expect(page.locator(commentBodies)).toHaveCount(0);++ await highlight.click();++ // The Comments tab came up on its own — a collapsed rail expands, and a rail+ // on another tab switches.+ const panel = page.locator('#panel-comments');+ await expect(panel.locator(commentBodies)).toHaveText(COMMENT);++ // Exactly one copy in the whole page. A card floating over the passage lives+ // outside this panel (it portals to `document.body`), so it would show up+ // here as a second body even though the panel assertion above passed.+ await expect(page.locator(commentBodies)).toHaveCount(1);+});++test('clicking unrelated text stands the comment down again', async ({ page, api }) => {+ const docName = `comment-stand-down-${Date.now()}`;+ await api.seedDocs([{ name: docName, markdown: SEED }]);++ const created = await page.request.post('/api/comments', {+ data: { docName, quote: PASSAGE, body: COMMENT },+ });+ expect(created.ok()).toBe(true);++ await page.goto(`/#/${docName}`);+ await waitForActiveProviderSynced(page);++ const editor = page.locator('.tiptap-editor .ProseMirror').first();+ await expect(editor).toContainText('Warm the bowl');++ // The rail marker's own label is the state, in the vocabulary a screen reader+ // gets: "Close comment" while this thread is the open one, "Open comment"+ // when it is not. Truer than a CSS class, and it moves with the same signal+ // the passage highlight and the panel card's wash read.+ const marker = page.getByRole('button', { name: 'Open comment', exact: true });+ const litMarker = page.getByRole('button', { name: 'Close comment', exact: true });++ await editor.locator('[data-comment-thread]').first().click();+ await expect(litMarker).toBeVisible();++ // Click a paragraph that carries no comment — the reader has moved on.+ await editor.getByText('Serve with the dressing').click();++ await expect(marker).toBeVisible();+ await expect(litMarker).toHaveCount(0);+ // The panel keeps the comment listed. Standing down from one comment says+ // nothing about the panel the reader opened.+ await expect(page.locator('#panel-comments').locator(commentBodies)).toHaveText(COMMENT);+});++test('Escape stands the comment down from inside the panel', async ({ page, api }) => {+ const docName = `comment-escape-${Date.now()}`;+ await api.seedDocs([{ name: docName, markdown: SEED }]);++ const created = await page.request.post('/api/comments', {+ data: { docName, quote: PASSAGE, body: COMMENT },+ });+ expect(created.ok()).toBe(true);++ await page.goto(`/#/${docName}`);+ await waitForActiveProviderSynced(page);++ const editor = page.locator('.tiptap-editor .ProseMirror').first();+ await expect(editor).toContainText('Warm the bowl');+ await editor.locator('[data-comment-thread]').first().click();++ const litMarker = page.getByRole('button', { name: 'Close comment', exact: true });+ await expect(litMarker).toBeVisible();++ // Focus inside the card, the way a keyboard reader arrives at it — the panel+ // is a sibling rail, not a descendant of the editor, so this is the position+ // an editor-scoped key handler cannot serve.+ await page+ .locator('#panel-comments')+ .getByRole('button', { name: /edit this comment/i })+ .focus();+ await page.keyboard.press('Escape');++ await expect(page.getByRole('button', { name: 'Open comment', exact: true })).toBeVisible();+ await expect(litMarker).toHaveCount(0);+});++test('the margin icon opens the same comment in the same place', async ({ page, api }) => {+ const docName = `comment-in-panel-rail-${Date.now()}`;+ await api.seedDocs([{ name: docName, markdown: SEED }]);++ const created = await page.request.post('/api/comments', {+ data: { docName, quote: PASSAGE, body: COMMENT },+ });+ expect(created.ok()).toBe(true);++ await page.goto(`/#/${docName}`);+ await waitForActiveProviderSynced(page);+ await expect(page.locator('.tiptap-editor .ProseMirror').first()).toContainText('Warm the bowl');++ // The rail marker sits beside the line it is anchored to, outside the editor.+ // `exact`, because the editor's own tab strip carries an "Open …" / "Close+ // <file>.md" pair that a substring match sweeps up with it.+ await page.getByRole('button', { name: 'Open comment', exact: true }).click();++ await expect(page.locator('#panel-comments').locator(commentBodies)).toHaveText(COMMENT);+ await expect(page.locator(commentBodies)).toHaveCount(1);++ // Clicking the lit marker again stands the comment down without closing the+ // panel — the reader opened that, and the second click is about the comment.+ await page.getByRole('button', { name: 'Close comment', exact: true }).click();+ await expect(page.locator('#panel-comments').locator(commentBodies)).toHaveText(COMMENT);+});++test('the margin icon is still lit for the open comment after leaving and returning', async ({+ page,+ api,+}) => {+ // The rail is remounted on every visit to a document, and which thread is+ // open outlives that mount. A rail that learned the answer only from the next+ // signal came back unlit — and, worse, backwards: its close/open toggle reads+ // the same value, so the first click on the marker for the comment already+ // open re-opened it instead of standing it down.+ const docName = `comment-rail-remount-${Date.now()}`;+ const other = `comment-rail-elsewhere-${Date.now()}`;+ await api.seedDocs([+ { name: docName, markdown: SEED },+ { name: other, markdown: 'Somewhere else entirely.' },+ ]);++ const created = await page.request.post('/api/comments', {+ data: { docName, quote: PASSAGE, body: COMMENT },+ });+ expect(created.ok()).toBe(true);++ await page.goto(`/#/${docName}`);+ await waitForActiveProviderSynced(page);+ await expect(page.locator('.tiptap-editor .ProseMirror').first()).toContainText('Warm the bowl');++ await page.getByRole('button', { name: 'Open comment', exact: true }).click();+ await expect(page.getByRole('button', { name: 'Close comment', exact: true })).toBeVisible();++ // Away, then back — the round trip that rebuilds the rail from scratch.+ await page.goto(`/#/${other}`);+ await expect(page.locator('.tiptap-editor .ProseMirror').first()).toContainText(+ 'Somewhere else entirely',+ );+ await page.goto(`/#/${docName}`);+ await waitForActiveProviderSynced(page);+ await expect(page.locator('.tiptap-editor .ProseMirror').first()).toContainText('Warm the bowl');++ // Lit for the comment that is still open, so the next click closes it.+ const litMarker = page.getByRole('button', { name: 'Close comment', exact: true });+ await expect(litMarker).toBeVisible();+ await litMarker.click();+ await expect(page.getByRole('button', { name: 'Open comment', exact: true })).toBeVisible();+});