Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

make editorial-note triage scroll-free and impact preview legibly hunked

[._.]/ Adam Eivycf54dc516e02
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index ef965cece9..b0e13e6a11 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,10 @@
## Added
+- **Manuscript editor: triage editorial feedback without the scroll-marathon** — clicking an editorial note used to scroll the page all the way to the bottom (the suggested-fix card rendered below the entire section), and getting to the next note meant scrolling all the way back up. Now the open note's card is injected **into the prose right at its anchor**, so the text being discussed and the Accept/Dismiss actions are on screen together; the card also gains a **‹ N of M › stepper** that walks every open note in story/anchor order (cross-issue, in both Live and Review modes), and **resolving a note auto-advances to the next open one** — working through 29 notes is one action per note, no sidebar round-trips. The sidebar index keeps its active row scrolled into view so it tracks where the pass is. (`client/src/components/pipeline/manuscript/`, `client/src/pages/PipelineManuscriptEditor.jsx`)
+
+- **Manuscript impact preview shows a real diff instead of a red/green wall** — the whole-section before/after in **Impact preview** ran a flat word-level diff that tripped its safety cap on manuscript-sized sections and fell back to "everything red on the left, everything green on the right." Sections are now diffed with a new hunked renderer (`HunkDiff`): unchanged text collapses to "⋯ N unchanged lines ⋯" (click to expand, two context lines kept around each change) and each changed region gets precise word-level red/green highlights, so what an accepted batch of edits *actually changes* is legible at a glance. The underlying word diff also trims common prefix/suffix text before hitting its cap, so the per-note edit diffs stay granular on long quotes too. (`client/src/lib/diffLines.js`, `client/src/components/ui/HunkDiff.jsx`, `client/src/lib/diffWords.js`)
+
- **Editorial review can draft every fix in one pass** — the manuscript editor's **Run editorial review** now has a second checkbox, **Generate edits for every finding**, next to *Start fresh*. With it on, the completeness pass returns not just the itemized editorial notes but a concrete rewrite (`replace`) for each one, so every comment lands with its fix already attached — you go straight to reviewing the full diff and accepting edits one-by-one, with no per-note **Generate fix** click. The model returns each finding's edit inline (a single LLM pass, no N+1 round-trips), and the run streams per-chunk progress over SSE (`Drafting edits — chunk 2 of 4…`) with a Cancel button, re-attaching if you reload mid-run. Findings whose anchor can't be located verbatim stay advice-only and fall back to manual fix generation, so nothing presents an unappliable diff. Leaving the box off keeps today's findings-only behavior unchanged. The new `replace` field rides in a `{{#withEdits}}` block of the completeness prompt (migration 083; the prior prompt auto-upgrades on existing installs). (`server/services/pipeline/arcPlanner.js`, `manuscriptReview.js`, `manuscriptCompletenessRunner.js`, `client/src/pages/PipelineManuscriptEditor.jsx`)
- **Animated 3D mini-character CoS avatars (bundled, CC0)** — two new Chief-of-Staff avatar styles, **Mini Character — Male (3D)** and **Mini Character — Female (3D)**, ship as rigged, animated GLB models out of the box (no user setup, no download). Unlike the `muse` style (which needs you to drop your own `data/avatar/model.glb`), these render immediately and play real skeletal animations mapped to the CoS agent state — `idle` while thinking, `walk` while coding, `sit` while sleeping, `sprint` while ideating, `emote-yes` while reviewing — plus a slow turntable rotation and a speaking head-bob, with clips crossfading on state change. The models are Kenney's [Mini Characters](https://kenney.nl/assets/mini-characters) (Creative Commons Zero), re-exported with the texture embedded and Draco compression disabled so they render offline / over Tailscale without fetching an external decoder from a CDN. Each is ~210 KB and ships in `data.reference/avatar/` (seeded into `data/avatar/` by `npm run setup:data`). The avatar route gained a safe `?variant=<name>` selector (strict `[a-z0-9-]` validation, no path traversal) so multiple bundled characters share one endpoint. Drop any rigged GLB at `data/avatar/<name>.glb` to add your own.
diff --git a/client/src/components/pipeline/manuscript/AnnotatedManuscriptSection.jsx b/client/src/components/pipeline/manuscript/AnnotatedManuscriptSection.jsx
index 46b40f732a..8b4e59237f 100644
--- a/client/src/components/pipeline/manuscript/AnnotatedManuscriptSection.jsx
+++ b/client/src/components/pipeline/manuscript/AnnotatedManuscriptSection.jsx
@@ -3,7 +3,10 @@
* (highlights + click-to-expand cards) for a focused editorial sweep, and flips
* to the plain editable `<textarea>` on demand via an Edit toggle. Blur in edit
* mode saves and returns to the annotated view, which re-locates anchors against
- * the new text. The open comment's card expands inline beneath the prose.
+ * the new text. The open comment's card is injected into the prose at its
+ * anchor (so acting on a note keeps the text it's about on screen); a note
+ * whose anchor isn't located in the current draft falls back to expanding
+ * beneath the prose.
*/
import { useEffect, useMemo, useRef } from 'react';
@@ -22,11 +25,12 @@ export default function AnnotatedManuscriptSection({
const content = section.content || '';
const byId = useMemo(() => new Map(comments.map((c) => [c.id, c])), [comments]);
const openComment = openCommentId && byId.get(openCommentId)?.status === 'open' ? byId.get(openCommentId) : null;
+ const located = openComment ? spans.some((s) => s.commentId === openComment.id) : false;
const cardRef = useRef(null);
- // The card expands beneath the (often long) prose, so bring it into view when
- // it opens — otherwise clicking a highlight mid-section looks like nothing
- // happened. Only the section that actually owns the open comment scrolls.
+ // Bring the open card (and with it the anchor text it sits under) into view —
+ // on open, and again when stepping prev/next between notes. Only the section
+ // that actually owns the open comment scrolls.
useEffect(() => {
if (openComment) cardRef.current?.scrollIntoView?.({ behavior: 'smooth', block: 'center' });
}, [openComment?.id]); // eslint-disable-line react-hooks/exhaustive-deps
@@ -34,6 +38,21 @@ export default function AnnotatedManuscriptSection({
// Esc closes the open note — parity with the Live popover.
useEscapeKey(openComment, onCloseComment);
+ const card = openComment && !editing ? (
+ <div ref={cardRef} className="relative border-l-2 border-port-accent/50 pl-2">
+ <button
+ type="button"
+ onClick={onCloseComment}
+ className="absolute right-1 top-1 z-10 text-gray-500 hover:text-white"
+ aria-label="Close note"
+ title="Close note"
+ >
+ <X size={14} />
+ </button>
+ <CommentCardFromProps comment={openComment} commentCardProps={commentCardProps} idScope={`review-${openComment.id}`} />
+ </div>
+ ) : null;
+
const editToggle = (
<button
type="button"
@@ -63,23 +82,11 @@ export default function AnnotatedManuscriptSection({
spans={spans}
openCommentId={openCommentId}
onOpenComment={onOpenComment}
+ inlineCard={located ? card : null}
/>
)}
- {!editing && openComment ? (
- <div ref={cardRef} className="relative border-l-2 border-port-accent/50 pl-2">
- <button
- type="button"
- onClick={onCloseComment}
- className="absolute right-1 top-1 z-10 text-gray-500 hover:text-white"
- aria-label="Close note"
- title="Close note"
- >
- <X size={14} />
- </button>
- <CommentCardFromProps comment={openComment} commentCardProps={commentCardProps} idScope={`review-${openComment.id}`} />
- </div>
- ) : null}
+ {card && !located ? card : null}
</ManuscriptSectionFrame>
);
}
diff --git a/client/src/components/pipeline/manuscript/ManuscriptCommentCard.jsx b/client/src/components/pipeline/manuscript/ManuscriptCommentCard.jsx
index ad9ccd61b1..626b1b93fd 100644
--- a/client/src/components/pipeline/manuscript/ManuscriptCommentCard.jsx
+++ b/client/src/components/pipeline/manuscript/ManuscriptCommentCard.jsx
@@ -11,7 +11,7 @@
*/
import { useMemo, useState } from 'react';
-import { Loader2, Sparkles, Check, X, Columns2, Rows2, Copy } from 'lucide-react';
+import { Loader2, Sparkles, Check, X, Columns2, Rows2, Copy, ChevronLeft, ChevronRight } from 'lucide-react';
import InlineDiff from '../../ui/InlineDiff';
import SideBySideDiff from '../../ui/SideBySideDiff';
import toast from '../../ui/Toast';
@@ -90,8 +90,19 @@ export function selectedEditsFor(comment, draft) {
// Bind a comment card to the page's shared `commentCardProps` (handlers + the
// per-comment draft keyed by id). The card renders identically in the Live
// popover, the Review inline expansion, and the sidebar index — only `idScope`
-// differs — so this wrapper is the single place that prop shape lives.
+// differs — so this wrapper is the single place that prop shape lives. When the
+// page supplies `openNav` (the triage order over open notes + a goto handler),
+// the card grows a ‹ N of M › stepper so a review pass never detours back
+// through the sidebar between notes.
export function CommentCardFromProps({ comment, commentCardProps, idScope }) {
+ const order = commentCardProps.openNav?.order || [];
+ const idx = order.indexOf(comment.id);
+ const nav = idx !== -1 && order.length > 1 ? {
+ index: idx,
+ total: order.length,
+ onPrev: () => commentCardProps.openNav.goto(order[(idx - 1 + order.length) % order.length]),
+ onNext: () => commentCardProps.openNav.goto(order[(idx + 1) % order.length]),
+ } : null;
return (
<ManuscriptCommentCard
comment={comment}
@@ -103,12 +114,13 @@ export function CommentCardFromProps({ comment, commentCardProps, idScope }) {
onAccepted={commentCardProps.onAccepted}
draft={commentCardProps.fixDrafts[comment.id]}
onDraftChange={(entry) => commentCardProps.setCommentDraft(comment.id, entry)}
+ nav={nav}
/>
);
}
export default function ManuscriptCommentCard({
- comment, seriesId, providerOverride, modelOverride, onCommentChange, onAccepted, idScope, draft, onDraftChange,
+ comment, seriesId, providerOverride, modelOverride, onCommentChange, onAccepted, idScope, draft, onDraftChange, nav,
}) {
// Namespace form ids so two copies of an open comment don't share ids.
const scope = idScope || comment.id;
@@ -170,7 +182,32 @@ export default function ManuscriptCommentCard({
<div className="border border-port-border rounded-lg bg-port-bg/40 p-2.5 space-y-2">
<div className="flex items-center justify-between gap-2">
<Badge comment={comment} />
- <CopyId id={comment.id} />
+ <span className="flex items-center gap-2">
+ {nav ? (
+ <span className="inline-flex items-center gap-0.5 text-[10px] text-gray-400">
+ <button
+ type="button"
+ onClick={nav.onPrev}
+ className="p-0.5 rounded hover:text-white hover:bg-port-border/60"
+ aria-label="Previous open note"
+ title="Previous open note"
+ >
+ <ChevronLeft size={13} />
+ </button>
+ <span className="tabular-nums whitespace-nowrap">{nav.index + 1} of {nav.total}</span>
+ <button
+ type="button"
+ onClick={nav.onNext}
+ className="p-0.5 rounded hover:text-white hover:bg-port-border/60"
+ aria-label="Next open note"
+ title="Next open note"
+ >
+ <ChevronRight size={13} />
+ </button>
+ </span>
+ ) : null}
+ <CopyId id={comment.id} />
+ </span>
</div>
<p className="text-xs text-gray-200">{comment.problem}</p>
diff --git a/client/src/components/pipeline/manuscript/ManuscriptCommentIndex.jsx b/client/src/components/pipeline/manuscript/ManuscriptCommentIndex.jsx
index 55bc6d07dd..563f3d40c9 100644
--- a/client/src/components/pipeline/manuscript/ManuscriptCommentIndex.jsx
+++ b/client/src/components/pipeline/manuscript/ManuscriptCommentIndex.jsx
@@ -5,15 +5,22 @@
* Accepted / Dismissed groups. A row reveals + opens that note in the manuscript.
*/
-import { useMemo, useState } from 'react';
+import { useEffect, useMemo, useRef, useState } from 'react';
import { ChevronDown, ChevronRight, Check, X, MapPin } from 'lucide-react';
import { Badge, CommentCardFromProps } from './ManuscriptCommentCard';
const SEVERITIES = ['high', 'medium', 'low'];
function CommentRow({ comment, located, active, onReveal }) {
+ const ref = useRef(null);
+ // Keep the active row visible while the card's ‹ › stepper (or auto-advance)
+ // walks the open notes — the sidebar tracks where the triage pass is.
+ useEffect(() => {
+ if (active) ref.current?.scrollIntoView?.({ block: 'nearest' });
+ }, [active]);
return (
<button
+ ref={ref}
type="button"
onClick={() => onReveal(comment)}
className={`block w-full text-left border rounded p-2 bg-port-bg/30 hover:border-port-accent/40 ${active ? 'border-port-accent/60' : 'border-port-border'}`}
diff --git a/client/src/components/pipeline/manuscript/ManuscriptHighlightedProse.jsx b/client/src/components/pipeline/manuscript/ManuscriptHighlightedProse.jsx
index 5eb54873f3..f6f51653ed 100644
--- a/client/src/components/pipeline/manuscript/ManuscriptHighlightedProse.jsx
+++ b/client/src/components/pipeline/manuscript/ManuscriptHighlightedProse.jsx
@@ -1,8 +1,10 @@
/**
* Read-only annotated prose for Review mode: renders manuscript text with each
* anchored editorial comment as a clickable, severity-toned highlight. Clicking
- * a highlight opens its comment (handled by the parent, which expands the card
- * inline beneath the section). Plain (non-highlighted) text renders verbatim,
+ * a highlight opens its comment (handled by the parent). When the parent passes
+ * `inlineCard`, the open note's card is injected INTO the prose flow at the end
+ * of the line containing its highlight — acting on a note never means scrolling
+ * away from the text it's about. Plain (non-highlighted) text renders verbatim,
* preserving whitespace.
*/
@@ -10,28 +12,77 @@ import { useMemo } from 'react';
import { buildHighlightSegments } from '../../../lib/manuscriptAnchors';
import { SEVERITY_TONE } from './constants';
-export default function ManuscriptHighlightedProse({ content, spans, openCommentId, onOpenComment }) {
- const segments = useMemo(() => buildHighlightSegments(content || '', spans), [content, spans]);
+export default function ManuscriptHighlightedProse({ content, spans, openCommentId, onOpenComment, inlineCard }) {
+ const text = content || '';
+ const segments = useMemo(() => buildHighlightSegments(text, spans), [text, spans]);
+
+ // Character offset where the inline card splices into the prose: just past
+ // the newline ending the line that contains the open note's highlight (or the
+ // end of the text). -1 = no card to place. If the note's span isn't located
+ // (shouldn't happen — the parent only passes inlineCard for located notes),
+ // fall back to appending at the end rather than dropping the card.
+ const cutAt = useMemo(() => {
+ if (!inlineCard) return -1;
+ const owned = (spans || []).filter((s) => s.commentId === openCommentId);
+ if (!owned.length) return text.length;
+ const end = Math.max(...owned.map((s) => s.end));
+ const nl = text.indexOf('\n', end);
+ return nl === -1 ? text.length : nl + 1;
+ }, [inlineCard, openCommentId, spans, text]);
+
+ const renderSegment = (seg, key, textOverride) => {
+ const segText = textOverride ?? seg.text;
+ if (!segText) return null;
+ if (!seg.commentIds.length) return <span key={key}>{segText}</span>;
+ const active = seg.commentIds.includes(openCommentId);
+ const tone = SEVERITY_TONE[seg.topSeverity] || SEVERITY_TONE.low;
+ return (
+ <button
+ key={key}
+ type="button"
+ onClick={() => onOpenComment(seg.commentIds[0])}
+ aria-expanded={active}
+ className={`rounded-sm border-b-2 px-0.5 -mx-0.5 text-left align-baseline ${tone} ${active ? 'ring-1 ring-port-accent/60' : ''}`}
+ title="Open editorial note"
+ >
+ {segText}
+ </button>
+ );
+ };
+
+ // The card is block content inside a pre-wrap container — reset whitespace
+ // and font so it renders as a normal card, not monospace prose.
+ const cardNode = (
+ <div key="inline-card" className="my-2 font-sans whitespace-normal">
+ {inlineCard}
+ </div>
+ );
+
+ const nodes = [];
+ let offset = 0;
+ let injected = cutAt < 0;
+ segments.forEach((seg, i) => {
+ const len = seg.text.length;
+ if (!injected && cutAt <= offset) {
+ nodes.push(cardNode);
+ injected = true;
+ }
+ if (!injected && cutAt < offset + len) {
+ const at = cutAt - offset;
+ nodes.push(renderSegment(seg, `${i}-a`, seg.text.slice(0, at)));
+ nodes.push(cardNode);
+ nodes.push(renderSegment(seg, `${i}-b`, seg.text.slice(at)));
+ injected = true;
+ } else {
+ nodes.push(renderSegment(seg, i));
+ }
+ offset += len;
+ });
+ if (!injected) nodes.push(cardNode);
return (
<div className="w-full px-3 py-2 bg-port-card border border-port-border rounded text-sm text-gray-100 font-mono leading-relaxed whitespace-pre-wrap break-words">
- {segments.map((seg, i) => {
- if (!seg.commentIds.length) return <span key={i}>{seg.text}</span>;
- const active = seg.commentIds.includes(openCommentId);
- const tone = SEVERITY_TONE[seg.topSeverity] || SEVERITY_TONE.low;
- return (
- <button
- key={i}
- type="button"
- onClick={() => onOpenComment(seg.commentIds[0])}
- aria-expanded={active}
- className={`rounded-sm border-b-2 px-0.5 -mx-0.5 text-left align-baseline ${tone} ${active ? 'ring-1 ring-port-accent/60' : ''}`}
- title="Open editorial note"
- >
- {seg.text}
- </button>
- );
- })}
+ {nodes}
</div>
);
}
diff --git a/client/src/components/pipeline/manuscript/ManuscriptHighlightedProse.test.jsx b/client/src/components/pipeline/manuscript/ManuscriptHighlightedProse.test.jsx
new file mode 100644
index 0000000000..ba3548da91
--- /dev/null
+++ b/client/src/components/pipeline/manuscript/ManuscriptHighlightedProse.test.jsx
@@ -0,0 +1,58 @@
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen, fireEvent } from '@testing-library/react';
+
+import ManuscriptHighlightedProse from './ManuscriptHighlightedProse';
+
+const CONTENT = 'line one ANCHOR tail\nline two\nline three';
+const SPANS = [{ commentId: 'c1', severity: 'high', start: CONTENT.indexOf('ANCHOR'), end: CONTENT.indexOf('ANCHOR') + 'ANCHOR'.length }];
+
+describe('ManuscriptHighlightedProse', () => {
+ it('renders the content verbatim with a clickable highlight', () => {
+ const onOpen = vi.fn();
+ const { container } = render(
+ <ManuscriptHighlightedProse content={CONTENT} spans={SPANS} openCommentId={null} onOpenComment={onOpen} />,
+ );
+ expect(container.textContent).toBe(CONTENT);
+ fireEvent.click(screen.getByText('ANCHOR'));
+ expect(onOpen).toHaveBeenCalledWith('c1');
+ });
+
+ it('injects the inline card at the end of the line containing the open note anchor', () => {
+ const { container } = render(
+ <ManuscriptHighlightedProse
+ content={CONTENT}
+ spans={SPANS}
+ openCommentId="c1"
+ onOpenComment={() => {}}
+ inlineCard={<div data-testid="card">CARD</div>}
+ />,
+ );
+ expect(screen.getByTestId('card')).toBeInTheDocument();
+ const text = container.textContent;
+ // The card splices in after the anchor's line, before the following line.
+ expect(text.indexOf('CARD')).toBeGreaterThan(text.indexOf('ANCHOR tail'));
+ expect(text.indexOf('CARD')).toBeLessThan(text.indexOf('line two'));
+ // The prose itself is still intact around the card.
+ expect(text.replace('CARD', '')).toBe(CONTENT);
+ });
+
+ it('appends the card at the end when the open note has no located span', () => {
+ const { container } = render(
+ <ManuscriptHighlightedProse
+ content={CONTENT}
+ spans={SPANS}
+ openCommentId="c-unlocated"
+ onOpenComment={() => {}}
+ inlineCard={<div data-testid="card">CARD</div>}
+ />,
+ );
+ expect(container.textContent.endsWith('CARD')).toBe(true);
+ });
+
+ it('renders no card when inlineCard is absent', () => {
+ render(
+ <ManuscriptHighlightedProse content={CONTENT} spans={SPANS} openCommentId="c1" onOpenComment={() => {}} />,
+ );
+ expect(screen.queryByTestId('card')).not.toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/pipeline/manuscript/ManuscriptImpactPreview.jsx b/client/src/components/pipeline/manuscript/ManuscriptImpactPreview.jsx
index 3a45e126ee..1fcbda3051 100644
--- a/client/src/components/pipeline/manuscript/ManuscriptImpactPreview.jsx
+++ b/client/src/components/pipeline/manuscript/ManuscriptImpactPreview.jsx
@@ -6,14 +6,17 @@
* uses) to a COPY of each section client-side. Preview only — accept still goes
* through the authoritative server route.
*
- * Diffs per changed section (never one giant concatenation) so the diff cell
- * cap isn't tripped on a long manuscript.
+ * Sections are diffed with the hunked `HunkDiff` (line-level blocks, unchanged
+ * context collapsed, word-level highlights inside each changed block) — a whole
+ * section is thousands of words, so a flat word diff would either drown the
+ * change in unchanged text or trip the diff cell cap and render everything
+ * red/green. Diffs per changed section, never one giant concatenation.
*/
import { useMemo } from 'react';
import { X } from 'lucide-react';
import Modal from '../../ui/Modal';
-import SideBySideDiff from '../../ui/SideBySideDiff';
+import HunkDiff from '../../ui/HunkDiff';
import { planManuscriptEdits } from '../../../lib/applyManuscriptEdits';
import { selectedEditsFor } from './ManuscriptCommentCard';
import { STAGE_LABEL } from './constants';
@@ -94,7 +97,7 @@ export default function ManuscriptImpactPreview({ open, onClose, sections, comme
{overlapping} of these edits overlap — accepting will be rejected; regenerate the fix. Preview below shows the non-overlapping subset.
</p>
) : null}
- <SideBySideDiff oldText={before} newText={after} oldLabel="Current" newLabel="With edits" />
+ <HunkDiff oldText={before} newText={after} oldLabel="Current" newLabel="With edits" />
</div>
))
)}
diff --git a/client/src/components/ui/HunkDiff.jsx b/client/src/components/ui/HunkDiff.jsx
new file mode 100644
index 0000000000..d0aa6085af
--- /dev/null
+++ b/client/src/components/ui/HunkDiff.jsx
@@ -0,0 +1,98 @@
+/**
+ * Hunked side-by-side diff for long texts — line-level blocks from
+ * `diffLineBlocks`, with unchanged runs collapsed to "⋯ N unchanged lines"
+ * (keeping a couple of context lines around each change) and each changed block
+ * rendered as word-highlighted before/after columns. Built for the manuscript
+ * impact preview, where a section runs thousands of words but the edits are
+ * localized — the flat `SideBySideDiff` stays the right tool for short texts.
+ */
+
+import { memo, useMemo, useState } from 'react';
+import { diffLineBlocks } from '../../lib/diffLines';
+import { diffWords } from '../../lib/diffWords';
+import { renderRuns } from './diffRuns';
+
+// Unchanged lines kept visible on each side of a change before collapsing.
+const CONTEXT_LINES = 2;
+
+function ChangeBlock({ oldLines, newLines }) {
+ const oldText = oldLines.join('\n');
+ const newText = newLines.join('\n');
+ const { tooLarge, oldRuns, newRuns } = useMemo(() => diffWords(oldText, newText), [oldText, newText]);
+ return (
+ <div className="flex gap-4 px-3 py-2 bg-port-card/50 border-y border-port-border/60">
+ <div className="min-w-0 flex-1 whitespace-pre-wrap break-words leading-relaxed text-red-200">
+ {tooLarge ? <span className="text-red-400">{oldText}</span> : renderRuns(oldRuns, false)}
+ </div>
+ <div className="min-w-0 flex-1 whitespace-pre-wrap break-words leading-relaxed text-green-200">
+ {tooLarge ? <span className="text-green-400">{newText}</span> : renderRuns(newRuns, true)}
+ </div>
+ </div>
+ );
+}
+
+function SameBlock({ lines, isFirst, isLast }) {
+ const [expanded, setExpanded] = useState(false);
+ // Context lines hug the adjacent change: none after the top of the diff,
+ // none before the very end.
+ const head = isFirst ? 0 : CONTEXT_LINES;
+ const tail = isLast ? 0 : CONTEXT_LINES;
+ const hidden = lines.length - head - tail;
+ if (expanded || hidden <= 1) {
+ return <div className="px-3 py-1.5 whitespace-pre-wrap break-words leading-relaxed text-gray-500">{lines.join('\n')}</div>;
+ }
+ return (
+ <div className="text-gray-500">
+ {head ? <div className="px-3 pt-1.5 whitespace-pre-wrap break-words leading-relaxed">{lines.slice(0, head).join('\n')}</div> : null}
+ <button
+ type="button"
+ onClick={() => setExpanded(true)}
+ className="w-full text-center text-[11px] text-gray-600 hover:text-gray-300 py-1"
+ title="Show the unchanged lines"
+ >
+ ⋯ {hidden} unchanged line{hidden === 1 ? '' : 's'} ⋯
+ </button>
+ {tail ? <div className="px-3 pb-1.5 whitespace-pre-wrap break-words leading-relaxed">{lines.slice(lines.length - tail).join('\n')}</div> : null}
+ </div>
+ );
+}
+
+const HunkDiff = memo(function HunkDiff({
+ oldText, newText, oldLabel = 'Before', newLabel = 'After', emptyLabel = 'No changes.',
+}) {
+ const oldStr = oldText || '';
+ const newStr = newText || '';
+ const blocks = useMemo(
+ () => (oldStr === newStr ? null : diffLineBlocks(oldStr, newStr).blocks),
+ [oldStr, newStr],
+ );
+
+ if (!blocks) {
+ return (
+ <div className="font-mono text-xs p-4 bg-port-bg">
+ <div className="text-gray-500">{emptyLabel}</div>
+ </div>
+ );
+ }
+
+ const changeCount = blocks.filter((b) => b.type === 'change').length;
+
+ return (
+ <div className="font-mono text-xs bg-port-bg">
+ <div className="flex items-center gap-4 px-3 py-2 border-b border-port-border/60 text-[10px] uppercase tracking-wider text-gray-500">
+ <div className="min-w-0 flex-1">{oldLabel}</div>
+ <div className="min-w-0 flex-1">{newLabel}</div>
+ <span className="text-gray-600 normal-case tracking-normal whitespace-nowrap">
+ {changeCount} changed region{changeCount === 1 ? '' : 's'}
+ </span>
+ </div>
+ {blocks.map((b, i) => (b.type === 'same' ? (
+ <SameBlock key={i} lines={b.lines} isFirst={i === 0} isLast={i === blocks.length - 1} />
+ ) : (
+ <ChangeBlock key={i} oldLines={b.oldLines} newLines={b.newLines} />
+ )))}
+ </div>
+ );
+});
+
+export default HunkDiff;
diff --git a/client/src/components/ui/HunkDiff.test.jsx b/client/src/components/ui/HunkDiff.test.jsx
new file mode 100644
index 0000000000..32279067fa
--- /dev/null
+++ b/client/src/components/ui/HunkDiff.test.jsx
@@ -0,0 +1,55 @@
+import { describe, it, expect } from 'vitest';
+import { render, screen, fireEvent } from '@testing-library/react';
+
+import HunkDiff from './HunkDiff';
+
+const lines = (p, n) => Array.from({ length: n }, (_, i) => `${p} line ${i}`).join('\n');
+
+describe('HunkDiff', () => {
+ it('shows the empty-label when the two texts are identical', () => {
+ render(<HunkDiff oldText="same\ntext" newText="same\ntext" />);
+ expect(screen.getByText('No changes.')).toBeInTheDocument();
+ });
+
+ it('word-highlights only the changed region, with surrounding context dimmed', () => {
+ const oldText = `${lines('top', 3)}\nThe cat sat here\n${lines('bottom', 3)}`;
+ const newText = `${lines('top', 3)}\nThe dog sat here\n${lines('bottom', 3)}`;
+ const { container } = render(<HunkDiff oldText={oldText} newText={newText} />);
+ const removed = container.querySelectorAll('.bg-red-900\\/50');
+ const added = container.querySelectorAll('.bg-green-900\\/50');
+ expect(removed).toHaveLength(1);
+ expect(added).toHaveLength(1);
+ expect(removed[0].textContent).toBe('cat');
+ expect(added[0].textContent).toBe('dog');
+ expect(screen.getByText(/1 changed region/)).toBeInTheDocument();
+ });
+
+ it('collapses long unchanged runs and expands them on click', () => {
+ const oldText = `start A\n${lines('mid', 20)}\nend A`;
+ const newText = `start B\n${lines('mid', 20)}\nend B`;
+ render(<HunkDiff oldText={oldText} newText={newText} />);
+ // 20 unchanged middle lines minus 2 context on each side = 16 hidden.
+ const toggle = screen.getByText(/16 unchanged lines/);
+ expect(screen.queryByText(/mid line 10/)).not.toBeInTheDocument();
+ fireEvent.click(toggle);
+ expect(screen.getByText(/mid line 10/)).toBeInTheDocument();
+ expect(screen.queryByText(/16 unchanged lines/)).not.toBeInTheDocument();
+ });
+
+ it('stays word-granular on a long manuscript-sized section (past the flat word-diff cap)', () => {
+ const body = Array.from({ length: 3000 }, (_, i) => `word${i}`).join(' ');
+ const oldText = `${body}\nmiddle cat paragraph\n${body}`;
+ const newText = `${body}\nmiddle dog paragraph\n${body}`;
+ const { container } = render(<HunkDiff oldText={oldText} newText={newText} />);
+ const removed = container.querySelectorAll('.bg-red-900\\/50');
+ expect(removed).toHaveLength(1);
+ expect(removed[0].textContent).toBe('cat');
+ expect(screen.queryByText(/Diff too large/)).not.toBeInTheDocument();
+ });
+
+ it('renders custom column labels', () => {
+ render(<HunkDiff oldText="a" newText="b" oldLabel="Current" newLabel="With edits" />);
+ expect(screen.getByText('Current')).toBeInTheDocument();
+ expect(screen.getByText('With edits')).toBeInTheDocument();
+ });
+});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index a06a577db3..d0330eb646 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -68,7 +68,8 @@ grep -i "what you want to do" client/src/lib/README.md
| `clipboard.js` | `copyToClipboard`, `writeClipboardSilently`, `readClipboard` — safe across insecure-origin contexts. Use these instead of `navigator.clipboard.writeText` inline. |
| `compareHelpers.js` | `equalByKeys(a, b, keys)` / `equalListByKeys(a, b, keys)` — typed key-based equality for `useAutoRefetch`'s `compare`. Keys are property names, dotted paths (`'context.running'`), or `(item) => value` accessors. The typed alternative to `sameJsonShape` when a monotonic timestamp or unrendered field would break stringify-equality dedup. |
| `consoleFilters.js` | `installConsoleFilters()` — drops a small allow-list of known-noise console strings (THREE.js `Clock` deprecation, expected WebGL `Context Lost.`) from `console.{warn,log,debug}`. Idempotent; auto-installed on import. Imported for its side effect from `main.jsx`. |
-| `diffWords.js` | `diffWords(oldText, newText)` → `{ tooLarge, oldRuns, newRuns }` — word-level Myers LCS core (tokenize on whitespace, collapse to `{ text, changed }` runs, 4M-cell `DIFF_CELL_CAP` guard). Shared by `InlineDiff` (stacked) and `SideBySideDiff` (columnar). |
+| `diffLines.js` | `diffLineBlocks(oldText, newText)` → `{ blocks }` (`{ type: 'same', lines }` / `{ type: 'change', oldLines, newLines }`) — line-level Myers LCS with common prefix/suffix trim and a 4M-cell `LINE_DIFF_CELL_CAP` guard. The structural layer behind `HunkDiff` (collapse same-blocks to context, word-diff each change-block). |
+| `diffWords.js` | `diffWords(oldText, newText)` → `{ tooLarge, oldRuns, newRuns }` — word-level Myers LCS core (tokenize on whitespace, common prefix/suffix trim, collapse to `{ text, changed }` runs, 4M-cell `DIFF_CELL_CAP` guard on the trimmed middle). Shared by `InlineDiff` (stacked), `SideBySideDiff` (columnar), and `HunkDiff`'s change blocks. |
| `genUtils.js` | Shared bits between Image Gen and Video Gen pages. |
| `healthProvenance.js` | `PROVENANCE_LEVELS` / `getProvenanceLevel(level)` — the `data-backed`/`inferred`/`experimental`/`speculative` trust taxonomy (label, tone, description, "what would change this?" copy) behind the `ProvenanceChip` source-style chips on MeatSpace / genome / death-clock / longevity views. Pure data; the chip component maps tone→color and id→icon. |
| `joinInfluenceList.js` | Mirror of `joinInfluenceList` in server universe builder. |
diff --git a/client/src/lib/diffLines.js b/client/src/lib/diffLines.js
new file mode 100644
index 0000000000..f23071a3ea
--- /dev/null
+++ b/client/src/lib/diffLines.js
@@ -0,0 +1,90 @@
+/**
+ * Line-block diff (Myers LCS over lines) — the structural layer behind the
+ * hunked manuscript diffs. Pure / no React.
+ *
+ * diffLineBlocks(oldText, newText) → { blocks }
+ * block = { type: 'same', lines } | { type: 'change', oldLines, newLines }
+ *
+ * Blocks tile both texts in order: joining every same-block's `lines` plus every
+ * change-block's `oldLines` with '\n' reproduces the old text verbatim (and
+ * `newLines` the new). Renderers collapse the same-blocks to context and run a
+ * word-level diff (`diffWords`) inside each change-block — that two-level split
+ * is what keeps a several-thousand-word manuscript section diffable: the line
+ * LCS is cheap (common prefix/suffix lines are trimmed first), and each
+ * word-level pass only sees one small changed region.
+ *
+ * If even the trimmed middle exceeds the cell cap, it degrades to ONE coarse
+ * change block — surrounding context is still preserved, unlike an
+ * everything-changed fallback.
+ */
+
+import { trimCommonEnds } from './diffWords.js';
+
+export const LINE_DIFF_CELL_CAP = 4_000_000;
+
+// LCS over lines, returning [oldIndex, newIndex] pairs (not values) so
+// duplicate lines — blank lines especially — can't be mis-aligned.
+function lcsPairs(a, b) {
+ const m = a.length, n = b.length;
+ const dp = new Int32Array((m + 1) * (n + 1));
+ const stride = n + 1;
+ for (let i = 1; i <= m; i++) {
+ const row = i * stride;
+ const prevRow = row - stride;
+ for (let j = 1; j <= n; j++) {
+ dp[row + j] = a[i - 1] === b[j - 1]
+ ? dp[prevRow + j - 1] + 1
+ : Math.max(dp[prevRow + j], dp[row + j - 1]);
+ }
+ }
+ const pairs = [];
+ let i = m, j = n;
+ while (i > 0 && j > 0) {
+ if (a[i - 1] === b[j - 1]) { pairs.unshift([i - 1, j - 1]); i--; j--; }
+ else if (dp[(i - 1) * stride + j] >= dp[i * stride + j - 1]) i--;
+ else j--;
+ }
+ return pairs;
+}
+
+export function diffLineBlocks(oldText, newText) {
+ const a = (oldText || '').split('\n');
+ const b = (newText || '').split('\n');
+
+ const { pre, suf, aMid, bMid } = trimCommonEnds(a, b);
+
+ const blocks = [];
+ const pushSame = (lines) => {
+ if (!lines.length) return;
+ const last = blocks[blocks.length - 1];
+ if (last?.type === 'same') last.lines = last.lines.concat(lines);
+ else blocks.push({ type: 'same', lines });
+ };
+ const pushChange = (oldLines, newLines) => {
+ if (!oldLines.length && !newLines.length) return;
+ blocks.push({ type: 'change', oldLines, newLines });
+ };
+
+ pushSame(a.slice(0, pre));
+ if (aMid.length * bMid.length > LINE_DIFF_CELL_CAP) {
+ pushChange(aMid, bMid);
+ } else {
+ const pairs = lcsPairs(aMid, bMid);
+ let pi = 0, pj = 0;
+ let sameBuf = [];
+ pairs.forEach(([ai, bj]) => {
+ if (ai > pi || bj > pj) {
+ pushSame(sameBuf);
+ sameBuf = [];
+ pushChange(aMid.slice(pi, ai), bMid.slice(pj, bj));
+ }
+ sameBuf.push(aMid[ai]);
+ pi = ai + 1;
+ pj = bj + 1;
+ });
+ pushSame(sameBuf);
+ pushChange(aMid.slice(pi), bMid.slice(pj));
+ }
+ pushSame(suf ? a.slice(a.length - suf) : []);
+ return { blocks };
+}
diff --git a/client/src/lib/diffLines.test.js b/client/src/lib/diffLines.test.js
new file mode 100644
index 0000000000..ac9b51761f
--- /dev/null
+++ b/client/src/lib/diffLines.test.js
@@ -0,0 +1,93 @@
+import { describe, it, expect } from 'vitest';
+import { diffLineBlocks, LINE_DIFF_CELL_CAP } from './diffLines.js';
+
+// Reassemble each side from the block stream — the tiling invariant every
+// renderer depends on.
+const oldOf = (blocks) => blocks.flatMap((b) => (b.type === 'same' ? b.lines : b.oldLines)).join('\n');
+const newOf = (blocks) => blocks.flatMap((b) => (b.type === 'same' ? b.lines : b.newLines)).join('\n');
+
+describe('diffLineBlocks', () => {
+ it('returns one same block for identical texts', () => {
+ const text = 'one\ntwo\nthree';
+ const { blocks } = diffLineBlocks(text, text);
+ expect(blocks).toEqual([{ type: 'same', lines: ['one', 'two', 'three'] }]);
+ });
+
+ it('isolates a localized change between same blocks', () => {
+ const oldText = 'a\nb\nc\nd\ne';
+ const newText = 'a\nb\nC!\nd\ne';
+ const { blocks } = diffLineBlocks(oldText, newText);
+ expect(blocks.map((b) => b.type)).toEqual(['same', 'change', 'same']);
+ expect(blocks[1].oldLines).toEqual(['c']);
+ expect(blocks[1].newLines).toEqual(['C!']);
+ expect(oldOf(blocks)).toBe(oldText);
+ expect(newOf(blocks)).toBe(newText);
+ });
+
+ it('handles pure insertion (empty oldLines)', () => {
+ const { blocks } = diffLineBlocks('a\nb', 'a\nx\ny\nb');
+ const change = blocks.find((b) => b.type === 'change');
+ expect(change.oldLines).toEqual([]);
+ expect(change.newLines).toEqual(['x', 'y']);
+ });
+
+ it('handles pure deletion (empty newLines)', () => {
+ const { blocks } = diffLineBlocks('a\nx\nb', 'a\nb');
+ const change = blocks.find((b) => b.type === 'change');
+ expect(change.oldLines).toEqual(['x']);
+ expect(change.newLines).toEqual([]);
+ });
+
+ it('aligns duplicate blank lines by index, keeping separate edits separate', () => {
+ const oldText = 'one\n\ntwo\n\nthree';
+ const newText = 'ONE\n\ntwo\n\nTHREE';
+ const { blocks } = diffLineBlocks(oldText, newText);
+ const changes = blocks.filter((b) => b.type === 'change');
+ expect(changes).toHaveLength(2);
+ expect(changes[0].oldLines).toEqual(['one']);
+ expect(changes[1].oldLines).toEqual(['three']);
+ expect(oldOf(blocks)).toBe(oldText);
+ expect(newOf(blocks)).toBe(newText);
+ });
+
+ it('tiles both sides verbatim across mixed edits', () => {
+ const oldText = 'h1\np p p\np q p\n\ntail\nend';
+ const newText = 'h1\nnew intro\np p p\np Q p\n\nend';
+ const { blocks } = diffLineBlocks(oldText, newText);
+ expect(oldOf(blocks)).toBe(oldText);
+ expect(newOf(blocks)).toBe(newText);
+ });
+
+ it('treats null/undefined as empty', () => {
+ const { blocks } = diffLineBlocks(null, undefined);
+ expect(blocks).toEqual([{ type: 'same', lines: [''] }]);
+ });
+
+ it('keeps a localized edit cheap in a text far beyond the cap-sized line count', () => {
+ const lines = Array.from({ length: 5000 }, (_, i) => `line ${i}`);
+ const changed = lines.slice();
+ changed[2500] = 'REPLACED';
+ const { blocks } = diffLineBlocks(lines.join('\n'), changed.join('\n'));
+ // Prefix/suffix trim leaves a one-line middle — no coarse fallback.
+ expect(blocks.map((b) => b.type)).toEqual(['same', 'change', 'same']);
+ expect(blocks[1].oldLines).toEqual(['line 2500']);
+ expect(blocks[1].newLines).toEqual(['REPLACED']);
+ });
+
+ it('degrades to one coarse change block past the cell cap, preserving context', () => {
+ // Every middle line differs and lines are unique, so no prefix/suffix trim
+ // helps; 2500×2500 > 4M cells.
+ const build = (p) => ['ctx-top', ...Array.from({ length: 2500 }, (_, i) => `${p}${i}`), 'ctx-bottom'];
+ const a = build('a');
+ const b = build('b');
+ const { blocks } = diffLineBlocks(a.join('\n'), b.join('\n'));
+ expect(blocks.map((x) => x.type)).toEqual(['same', 'change', 'same']);
+ expect(blocks[0].lines).toEqual(['ctx-top']);
+ expect(blocks[2].lines).toEqual(['ctx-bottom']);
+ expect(blocks[1].oldLines).toHaveLength(2500);
+ });
+
+ it('exports the documented cap', () => {
+ expect(LINE_DIFF_CELL_CAP).toBe(4_000_000);
+ });
+});
diff --git a/client/src/lib/diffWords.js b/client/src/lib/diffWords.js
index 198ccf1821..6b5fde06f9 100644
--- a/client/src/lib/diffWords.js
+++ b/client/src/lib/diffWords.js
@@ -10,14 +10,27 @@
* run = { text, changed } // changed=true ⇒ removed (old) / added (new)
*
* `tooLarge` guards the (m+1)×(n+1) DP allocation. The product — not either
- * side — is what matters; cap at 4M cells (~16MB Int32Array). `split(/(\s+)/)`
- * roughly doubles the word count (word + whitespace token), so a ~1000-word vs
- * ~1000-word diff lands at 2000×2000 = 4M cells, right at the cap. Past it,
- * callers fall back to showing both versions in full rather than risk a freeze.
+ * side — is what matters; cap at 4M cells (~16MB Int32Array). Common
+ * prefix/suffix tokens are trimmed before sizing the table, so a localized edit
+ * inside an arbitrarily long text stays under the cap — only texts whose
+ * *differing middle* exceeds ~1000×1000 words trip it. Past it, callers fall
+ * back to showing both versions in full rather than risk a freeze.
*/
export const DIFF_CELL_CAP = 4_000_000;
+// Trim the common prefix/suffix off two token arrays so only the differing
+// middle pays for LCS. Shared with the line-level `diffLines.js`.
+export function trimCommonEnds(a, b) {
+ let pre = 0;
+ const maxPre = Math.min(a.length, b.length);
+ while (pre < maxPre && a[pre] === b[pre]) pre++;
+ let suf = 0;
+ const maxSuf = maxPre - pre;
+ while (suf < maxSuf && a[a.length - 1 - suf] === b[b.length - 1 - suf]) suf++;
+ return { pre, suf, aMid: a.slice(pre, a.length - suf), bMid: b.slice(pre, b.length - suf) };
+}
+
function lcs(a, b) {
const m = a.length, n = b.length;
// Single Int32Array — exactly 4 bytes/cell, no per-element boxing the way a
@@ -68,13 +81,31 @@ function toRuns(words, commonSeq) {
return runs;
}
+// Glue an unchanged prefix/suffix run back onto a run list, merging with an
+// adjacent unchanged run so consecutive same-state runs stay collapsed.
+function wrapRuns(prefix, runs, suffix) {
+ const out = runs.filter((r) => r.text);
+ if (prefix) {
+ if (out[0] && !out[0].changed) out[0] = { text: prefix + out[0].text, changed: false };
+ else out.unshift({ text: prefix, changed: false });
+ }
+ if (suffix) {
+ const last = out[out.length - 1];
+ if (last && !last.changed) out[out.length - 1] = { text: last.text + suffix, changed: false };
+ else out.push({ text: suffix, changed: false });
+ }
+ return out;
+}
+
export function diffWords(oldText, newText) {
const oldStr = oldText || '';
const newStr = newText || '';
const oldWords = oldStr.split(/(\s+)/);
const newWords = newStr.split(/(\s+)/);
- if (oldWords.length * newWords.length > DIFF_CELL_CAP) {
+ const { pre, suf, aMid: oldMid, bMid: newMid } = trimCommonEnds(oldWords, newWords);
+
+ if (oldMid.length * newMid.length > DIFF_CELL_CAP) {
return {
tooLarge: true,
oldRuns: oldStr ? [{ text: oldStr, changed: true }] : [],
@@ -82,10 +113,12 @@ export function diffWords(oldText, newText) {
};
}
- const commonSeq = lcs(oldWords, newWords);
+ const commonSeq = lcs(oldMid, newMid);
+ const prefix = oldWords.slice(0, pre).join('');
+ const suffix = suf ? oldWords.slice(oldWords.length - suf).join('') : '';
return {
tooLarge: false,
- oldRuns: toRuns(oldWords, commonSeq),
- newRuns: toRuns(newWords, commonSeq),
+ oldRuns: wrapRuns(prefix, toRuns(oldMid, commonSeq), suffix),
+ newRuns: wrapRuns(prefix, toRuns(newMid, commonSeq), suffix),
};
}
diff --git a/client/src/lib/diffWords.test.js b/client/src/lib/diffWords.test.js
index 922b5c06e8..09354c443f 100644
--- a/client/src/lib/diffWords.test.js
+++ b/client/src/lib/diffWords.test.js
@@ -43,6 +43,22 @@ describe('diffWords', () => {
expect(newRuns).toHaveLength(1);
});
+ it('keeps a localized edit granular in a text far past the cap size', () => {
+ const words = Array.from({ length: 6000 }, (_, i) => `w${i}`);
+ const oldStr = words.join(' ');
+ const changed = words.slice();
+ changed[3000] = 'REPLACED';
+ const newStr = changed.join(' ');
+ const { tooLarge, oldRuns, newRuns } = diffWords(oldStr, newStr);
+ // 6000×6000 words would blow the cap; prefix/suffix trim reduces it to the
+ // one differing token, so the diff stays word-granular.
+ expect(tooLarge).toBe(false);
+ expect(oldRuns.filter((r) => r.changed).map((r) => r.text)).toEqual(['w3000']);
+ expect(newRuns.filter((r) => r.changed).map((r) => r.text)).toEqual(['REPLACED']);
+ expect(oldRuns.map((r) => r.text).join('')).toBe(oldStr);
+ expect(newRuns.map((r) => r.text).join('')).toBe(newStr);
+ });
+
it('stays under the cap when one side is short even if the other is long', () => {
const long = Array.from({ length: 5000 }, (_, i) => `w${i}`).join(' ');
expect(diffWords(long, 'x').tooLarge).toBe(false);
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 98e0030bc8..c22b0635d1 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -39,6 +39,7 @@ export * from './clinicianReport.js';
export * from './clipboard.js';
export * from './compareHelpers.js';
export * from './consoleFilters.js';
+export * from './diffLines.js';
export * from './diffWords.js';
export * from './genUtils.js';
export * from './healthProvenance.js';
diff --git a/client/src/pages/PipelineManuscriptEditor.jsx b/client/src/pages/PipelineManuscriptEditor.jsx
index ae1ec89ae0..ecef4dd013 100644
--- a/client/src/pages/PipelineManuscriptEditor.jsx
+++ b/client/src/pages/PipelineManuscriptEditor.jsx
@@ -13,8 +13,13 @@
* cards and an Edit toggle per section.
* - Right : a navigable/filterable INDEX of editorial comments — click a row
* to reveal + open that note in the manuscript.
- * An "Impact preview" button shows a before/after side-by-side diff of how the
- * selected fixes change the whole manuscript.
+ * The open note's card carries a ‹ N of M › stepper over every open note (in
+ * story/anchor order), and resolving a note (Accept/Dismiss) auto-advances to
+ * the next one — triaging a long review pass is one action per note, with no
+ * scrolling back to the sidebar in between.
+ * An "Impact preview" button shows a hunked before/after diff (unchanged
+ * context collapsed, word-level highlights) of how the selected fixes change
+ * the whole manuscript.
*
* Data: GET /pipeline/series/:id/manuscript (sections) + .../manuscript/review
* (comments). Section saves reuse PATCH /pipeline/issues/:id; fixes go through
@@ -376,26 +381,43 @@ export default function PipelineManuscriptEditor() {
return result;
};
- // Reveal a comment in context: drop into Review mode (where the note expands
- // as an in-context card) and open it, switching to its issue tab if needed.
+ // Step to a note without disturbing the current view mode — shared by the
+ // card's ‹ › stepper, the auto-advance after a resolve, and revealComment.
// The section's card-scroll effect brings the card into view — on arrival for
// a cross-issue jump, or immediately when it's the active issue. A story-level
// note with no issueNumber has no tab, so it expands inline in the sidebar.
- const revealComment = (comment) => {
+ const advanceTo = (comment) => {
setOpenCommentId(comment.id);
- setViewMode('review'); // surface the in-context review card…
- setEditingIssueId(null); // …and make sure it's the card showing, not the editor
+ setEditingIssueId(null); // make sure it's the card showing, not the editor
if (comment.issueNumber == null) return; // unanchored — expands in the sidebar
if (comment.issueNumber !== activeNumber) {
navigate(`/pipeline/series/${seriesId}/manuscript/${comment.issueNumber}`);
}
+ };
+
+ // Reveal a comment in context from the sidebar: drop into Review mode (where
+ // the note expands as an in-context card) and open it.
+ const revealComment = (comment) => {
+ setViewMode('review');
+ advanceTo(comment);
+ if (comment.issueNumber == null) return;
if (comment.stageId && viewType && comment.stageId !== viewType) {
toast(`This note is on the ${STAGE_LABEL[comment.stageId] || comment.stageId} — switch formats to edit it in context`);
}
};
- const updateCommentLocal = (next) =>
+ // Local comment swap + triage auto-advance: resolving the open note (accept
+ // or dismiss) steps straight to the next open one, so a long editorial pass
+ // is one action per note with no scroll-back in between. `openOrder` is
+ // declared below; by the time these handlers run it's populated.
+ const updateCommentLocal = (next) => {
setComments((prev) => prev.map((c) => (c.id === next.id ? next : c)));
+ if (next.id !== openCommentId || next.status === 'open') return;
+ const idx = openOrder.findIndex((c) => c.id === next.id);
+ const following = idx === -1 ? [] : [...openOrder.slice(idx + 1), ...openOrder.slice(0, idx)];
+ if (following.length) advanceTo(following[0]);
+ else setOpenCommentId(null);
+ };
const applyAccepted = ({ comment, section, sections: changedSections }) => {
const list = Array.isArray(changedSections) && changedSections.length ? changedSections : [section].filter(Boolean);
@@ -447,6 +469,30 @@ export default function PipelineManuscriptEditor() {
return map;
}, [openCommentsByNumber]);
+ // Triage order over the open notes that can actually display in the current
+ // format: story order across issues, anchor position within an issue
+ // (unlocated notes after located ones), story-level notes last. Drives the
+ // card's ‹ N of M › stepper and the auto-advance after Accept/Dismiss.
+ const openOrder = useMemo(() => {
+ const startBy = new Map();
+ sectionSpans.forEach((spans) => spans.forEach((s) => {
+ const cur = startBy.get(s.commentId);
+ if (cur == null || s.start < cur) startBy.set(s.commentId, s.start);
+ }));
+ const ordered = [];
+ sections.forEach((s) => {
+ const list = (openCommentsByNumber.get(s.number) || [])
+ .slice()
+ .sort((a, b) => (startBy.get(a.id) ?? Infinity) - (startBy.get(b.id) ?? Infinity));
+ ordered.push(...list);
+ });
+ comments.forEach((c) => {
+ if (c.status === 'open' && c.issueNumber == null) ordered.push(c);
+ });
+ return ordered;
+ }, [sections, sectionSpans, openCommentsByNumber, comments]);
+ const openOrderIds = useMemo(() => openOrder.map((c) => c.id), [openOrder]);
+
// The one issue the editor is focused on. On the bare /manuscript URL (or an
// unknown issue) fall back to the first issue so there's no blank frame, and
// canonicalize the URL to it so the tab highlights and deep links/back work.
@@ -469,6 +515,13 @@ export default function PipelineManuscriptEditor() {
onAccepted: applyAccepted,
fixDrafts,
setCommentDraft,
+ openNav: {
+ order: openOrderIds,
+ goto: (id) => {
+ const target = comments.find((c) => c.id === id);
+ if (target) advanceTo(target);
+ },
+ },
};
const registerSectionRef = (number) => (el) => {