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

show editorial feedback in-context in the manuscript editor

[._.]/ Adam Eivyc93959171ffc
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f1baf8d0a9..b4e912bbdc 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -6,6 +6,7 @@
- **Scheduled "Claim Issue" task** — a new built-in CoS schedule (CoS → Schedule → Claim Issue) that runs the `/claim --issues` flow on a cadence: it picks the next open GitHub issue, creates its own `claim/issue-<num>` worktree, implements the fix, opens a PR that closes the issue, runs the configured reviewers, merges, and cleans up. Configurable per app via an **Issue Author Filter** — claim only issues filed by the repository owner (default) or any open issue regardless of author. Off by default; enable and pick a provider/model per app like the other improvement tasks.
- **Scheduled "Refresh local-LLM catalog" task** — a new built-in CoS schedule that periodically researches the current best local models per category and opens a PR refreshing PortOS's bundled suggested-models catalog (`server/lib/localLlmCatalog.js`) and the editorial model ranking, so the in-app install picker and recommendations don't go stale. It no-ops on any repo lacking the catalog file, so it only does work when enabled on the PortOS app itself. Off by default; weekly when enabled, and it only opens a PR when the catalog is actually out of date.
- **Manuscript editorial review: "Start fresh" re-run mode** — re-running the editorial pass in the manuscript editor previously always *merged*, leaving every prior open note in place even when a later pass no longer flagged it. A new "Start fresh" checkbox next to "Run editorial review" reconciles the open list against the latest pass: open notes it still finds stay open, open notes it no longer finds are auto-dismissed, and genuinely-new findings are added. Your accepted and dismissed decisions are left untouched. Clearing is done by moving notes to dismissed (never by deleting them), so the change syncs correctly across federated machines instead of being resurrected by a peer. Merge stays the default.
+- **Manuscript editor: editorial feedback is now shown in-context, not just in a sidebar** — instead of scrolling a disconnected list of notes, each editorial comment is highlighted directly on the text it points to. A header toggle switches between two modes: **Live** (Grammarly-style — the manuscript stays fully editable and each anchored note shows as a severity-toned underline; click the underlined text or its tag to pop the note's card right there with Generate-fix / Accept / Dismiss) and **Review** (a read-through where the prose is annotated and clicking a highlight expands the note inline, with a per-section Edit toggle to drop into free editing). The right sidebar becomes a filterable index (by severity, with open / accepted / dismissed groups and a "located in text" count) that scrolls to and opens any note. Suggested edits can now be reviewed as a **side-by-side before/after diff** (default) or the prior stacked inline diff, and a new **Impact preview** shows, per affected issue, how accepting the selected fixes changes the whole manuscript before you commit to them. Notes whose anchor text no longer matches the draft degrade gracefully — they stay listed in the sidebar with no in-text highlight rather than disappearing.
## Changed
diff --git a/client/src/components/pipeline/manuscript/AnnotatedManuscriptSection.jsx b/client/src/components/pipeline/manuscript/AnnotatedManuscriptSection.jsx
new file mode 100644
index 0000000000..7edc64f8b5
--- /dev/null
+++ b/client/src/components/pipeline/manuscript/AnnotatedManuscriptSection.jsx
@@ -0,0 +1,76 @@
+/**
+ * Review-mode manuscript section: defaults to a read-only annotated prose view
+ * (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.
+ */
+
+import { useMemo } from 'react';
+import { Pencil, Check } from 'lucide-react';
+import ManuscriptHighlightedProse from './ManuscriptHighlightedProse';
+import ManuscriptCommentCard from './ManuscriptCommentCard';
+import ManuscriptSectionFrame from './ManuscriptSectionFrame';
+import { rowsFor } from './constants';
+
+export default function AnnotatedManuscriptSection({
+ section, comments, spans, saveState, editing, onToggleEdit,
+ openCommentId, onOpenComment,
+ onContentChange, onBlurSave, onRevert, registerRef, commentCardProps,
+}) {
+ 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 editToggle = (
+ <button
+ type="button"
+ onClick={onToggleEdit}
+ className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[11px] border border-port-border text-gray-300 hover:text-white hover:border-port-accent/40"
+ title={editing ? 'Done editing — back to annotated view' : 'Edit this section'}
+ >
+ {editing ? <><Check size={11} /> Done</> : <><Pencil size={11} /> Edit</>}
+ </button>
+ );
+
+ return (
+ <ManuscriptSectionFrame section={section} saveState={saveState} onRevert={onRevert} headerExtra={editToggle}>
+ {editing ? (
+ <textarea
+ ref={registerRef}
+ value={content}
+ onChange={(e) => onContentChange(e.target.value)}
+ onBlur={onBlurSave}
+ rows={rowsFor(content)}
+ spellCheck
+ autoFocus
+ className="w-full px-3 py-2 bg-port-card border border-port-border rounded text-sm text-gray-100 font-mono leading-relaxed resize-y focus:border-port-accent/50 focus:outline-none"
+ />
+ ) : (
+ <ManuscriptHighlightedProse
+ content={content}
+ spans={spans}
+ openCommentId={openCommentId}
+ onOpenComment={onOpenComment}
+ />
+ )}
+
+ {!editing && openComment ? (
+ <div className="border-l-2 border-port-accent/50 pl-2">
+ <ManuscriptCommentCard
+ comment={openComment}
+ idScope={`review-${openComment.id}`}
+ seriesId={commentCardProps.seriesId}
+ providerOverride={commentCardProps.providerOverride}
+ modelOverride={commentCardProps.modelOverride}
+ onCommentChange={commentCardProps.onCommentChange}
+ onAccepted={commentCardProps.onAccepted}
+ draft={commentCardProps.fixDrafts[openComment.id]}
+ onDraftChange={(entry) => commentCardProps.setCommentDraft(openComment.id, entry)}
+ onJump={undefined}
+ />
+ </div>
+ ) : null}
+ </ManuscriptSectionFrame>
+ );
+}
diff --git a/client/src/components/pipeline/manuscript/ManuscriptCommentCard.jsx b/client/src/components/pipeline/manuscript/ManuscriptCommentCard.jsx
new file mode 100644
index 0000000000..173ad5530d
--- /dev/null
+++ b/client/src/components/pipeline/manuscript/ManuscriptCommentCard.jsx
@@ -0,0 +1,259 @@
+/**
+ * One editorial comment, in card form. Rendered in three places — the sidebar
+ * index, the in-context popover/expansion, and the impact-preview list — so its
+ * fix-edit draft state (replacement text + which edits are checked) is OWNED BY
+ * THE PARENT (keyed by comment id) and passed in via `draft`/`onDraftChange`.
+ * Two cards for the same comment therefore share one editing state. `idScope`
+ * namespaces the form ids so two instances don't collide on label/htmlFor.
+ *
+ * The suggested-edit diff toggles between a columnar before/after
+ * (`SideBySideDiff`, default) and the compact stacked `InlineDiff`.
+ */
+
+import { useMemo, useState } from 'react';
+import { Loader2, Sparkles, Check, X, CornerDownRight, Columns2, Rows2 } from 'lucide-react';
+import InlineDiff from '../../ui/InlineDiff';
+import SideBySideDiff from '../../ui/SideBySideDiff';
+import toast from '../../ui/Toast';
+import { useAsyncAction } from '../../../hooks/useAsyncAction';
+import {
+ patchPipelineManuscriptComment, generatePipelineManuscriptFix, acceptPipelineManuscriptFix,
+} from '../../../services/api';
+import { SEVERITY_TONE, CATEGORY_LABEL } from './constants';
+
+export function Badge({ comment }) {
+ return (
+ <span className="flex items-center gap-1.5">
+ <span className={`text-[10px] px-1.5 py-0.5 rounded border ${SEVERITY_TONE[comment.severity] || SEVERITY_TONE.low}`}>
+ {comment.severity}
+ </span>
+ <span className="text-[10px] uppercase tracking-wider text-gray-500">{CATEGORY_LABEL[comment.category] || comment.category}</span>
+ </span>
+ );
+}
+
+// Build the editable edit list off a comment's fix, tolerating both the
+// multi-edit (`fix.edits`) and the legacy single find/replace shape.
+export function fixEditsOf(comment) {
+ if (Array.isArray(comment.fix?.edits) && comment.fix.edits.length) return comment.fix.edits;
+ if (comment.fix?.find || comment.fix?.replace) {
+ return [{
+ issueNumber: comment.issueNumber,
+ issueId: comment.issueId,
+ stageId: comment.stageId,
+ find: comment.fix.find || '',
+ replace: comment.fix.replace || '',
+ fuzzy: comment.fix.fuzzy,
+ }];
+ }
+ return [];
+}
+
+// Stable signature of a fix's edits — a stored draft only applies when its
+// fixKey still matches (a regenerated fix invalidates stale drafts).
+export function fixKeyOf(edits) {
+ return edits.map((e, i) => `${i}:${e.issueId || ''}:${e.stageId || ''}:${e.find}:${e.replace}`).join('\n---\n');
+}
+
+// The edits that would actually be accepted for a comment, honoring the parent's
+// draft (replacement text + which edits are checked). Shared by the card's
+// Accept and the impact preview so the two never diverge.
+export function selectedEditsFor(comment, draft) {
+ const edits = fixEditsOf(comment);
+ const stored = draft && draft.fixKey === fixKeyOf(edits) ? draft : null;
+ return edits
+ .map((e, i) => ({
+ ...e,
+ replace: stored ? (stored.drafts[i] ?? e.replace ?? '') : (e.replace ?? ''),
+ selected: stored ? stored.selected[i] !== false : true,
+ }))
+ .filter((e) => e.selected);
+}
+
+export default function ManuscriptCommentCard({
+ comment, seriesId, providerOverride, modelOverride, onJump, onCommentChange, onAccepted, idScope, draft, onDraftChange,
+}) {
+ // Namespace form ids so two copies of an open comment don't share ids.
+ const scope = idScope || comment.id;
+ const [diffStyle, setDiffStyle] = useState('side'); // 'side' | 'inline'
+ const hasFix = !!comment.fix;
+ const fixEdits = useMemo(() => fixEditsOf(comment), [comment]);
+ const fixKey = useMemo(() => fixKeyOf(fixEdits), [fixEdits]);
+ // Use the stored draft only when it was derived from the current fix; a
+ // (re)generated fix has a new fixKey, so stale drafts fall back to fresh
+ // defaults (every edit checked, replacement prefilled).
+ const stored = draft && draft.fixKey === fixKey ? draft : null;
+ const editDrafts = stored ? stored.drafts : Object.fromEntries(fixEdits.map((e, i) => [i, e.replace || '']));
+ const selectedEdits = stored ? stored.selected : Object.fromEntries(fixEdits.map((_, i) => [i, true]));
+ const setEditDrafts = (updater) =>
+ onDraftChange({ fixKey, drafts: typeof updater === 'function' ? updater(editDrafts) : updater, selected: selectedEdits });
+ const setSelectedEdits = (updater) =>
+ onDraftChange({ fixKey, drafts: editDrafts, selected: typeof updater === 'function' ? updater(selectedEdits) : updater });
+
+ const [runGenerate, generating] = useAsyncAction(
+ () => generatePipelineManuscriptFix(seriesId, comment.id, { providerOverride, modelOverride }),
+ { errorMessage: 'Failed to generate fix' },
+ );
+ const [runAccept, accepting] = useAsyncAction(
+ (selected) => acceptPipelineManuscriptFix(seriesId, comment.id, { edits: selected }),
+ { errorMessage: 'Failed to apply fix' },
+ );
+
+ const generate = async () => {
+ const result = await runGenerate();
+ if (!result) return;
+ if (result.comment) onCommentChange(result.comment);
+ if (result.fix?.fuzzy) toast('The suggested anchor was not found verbatim — edit the manuscript directly, or adjust the replacement.');
+ };
+
+ const accept = async () => {
+ if (!comment.fix) return;
+ // Same selection the impact preview uses, so what you preview is what applies.
+ const selected = selectedEditsFor(comment, draft).map(({ selected: _s, ...edit }) => edit);
+ if (selected.length === 0) {
+ toast('Select at least one suggested edit to apply');
+ return;
+ }
+ const result = await runAccept(selected);
+ if (!result) return;
+ onAccepted(result);
+ toast.success(selected.length === 1 ? 'Fix applied to the manuscript' : `${selected.length} fixes applied to the manuscript`);
+ };
+
+ const dismiss = async () => {
+ const result = await patchPipelineManuscriptComment(seriesId, comment.id, { status: 'dismissed' }, { silent: true })
+ .catch((err) => { toast.error(err.message || 'Failed to dismiss'); return null; });
+ if (result?.comment) onCommentChange(result.comment);
+ };
+
+ const fuzzy = comment.fix?.fuzzy || fixEdits.some((e) => e.fuzzy);
+ const Diff = diffStyle === 'side' ? SideBySideDiff : InlineDiff;
+
+ return (
+ <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} />
+ {onJump ? (
+ <button
+ type="button"
+ onClick={() => onJump(comment)}
+ className="text-[11px] text-port-accent hover:underline inline-flex items-center gap-1"
+ title="Reveal this spot in the manuscript"
+ >
+ <CornerDownRight size={11} />
+ {comment.issueNumber != null ? `Issue ${comment.issueNumber}` : 'Reveal'}
+ </button>
+ ) : null}
+ </div>
+
+ <p className="text-xs text-gray-200">{comment.problem}</p>
+ {comment.suggestion ? <p className="text-[11px] text-gray-400"><span className="text-gray-500">Fix: </span>{comment.suggestion}</p> : null}
+ {comment.anchorQuote ? <p className="text-[11px] text-gray-500 italic line-clamp-2">“{comment.anchorQuote}”</p> : null}
+
+ {hasFix ? (
+ <div className="space-y-1.5">
+ <div className="flex items-center justify-between gap-2">
+ <p className="text-[10px] uppercase tracking-wider text-gray-500">
+ Suggested {fixEdits.length === 1 ? 'edit' : `${fixEdits.length} edits`}
+ </p>
+ {/* Diff layout toggle — columnar before/after (default) vs stacked. */}
+ <div className="inline-flex rounded border border-port-border overflow-hidden">
+ <button
+ type="button"
+ onClick={() => setDiffStyle('side')}
+ aria-pressed={diffStyle === 'side'}
+ title="Side-by-side diff"
+ className={`px-1.5 py-0.5 ${diffStyle === 'side' ? 'bg-port-accent text-white' : 'text-gray-400 hover:text-white'}`}
+ >
+ <Columns2 size={12} />
+ </button>
+ <button
+ type="button"
+ onClick={() => setDiffStyle('inline')}
+ aria-pressed={diffStyle === 'inline'}
+ title="Stacked inline diff"
+ className={`px-1.5 py-0.5 ${diffStyle === 'inline' ? 'bg-port-accent text-white' : 'text-gray-400 hover:text-white'}`}
+ >
+ <Rows2 size={12} />
+ </button>
+ </div>
+ </div>
+ {fixEdits.map((edit, i) => {
+ const draftText = editDrafts[i] ?? edit.replace ?? '';
+ const checked = selectedEdits[i] !== false;
+ const label = edit.issueNumber != null ? `Issue ${edit.issueNumber}` : 'Manuscript';
+ return (
+ <div key={`${i}-${edit.issueId || ''}-${edit.find}`} className="border border-port-border rounded bg-port-card/60 overflow-hidden">
+ <label className="flex items-center gap-2 px-2 py-1.5 border-b border-port-border text-[11px] text-gray-300">
+ <input
+ type="checkbox"
+ checked={checked}
+ onChange={(e) => setSelectedEdits((prev) => ({ ...prev, [i]: e.target.checked }))}
+ className="accent-port-accent"
+ />
+ <span className="font-medium">{label}{edit.title ? ` — ${edit.title}` : ''}</span>
+ {edit.fuzzy ? <span className="ml-auto text-port-warning">fuzzy</span> : null}
+ </label>
+ {edit.note ? <p className="px-2 pt-1.5 text-[11px] text-gray-500">{edit.note}</p> : null}
+ <Diff oldText={edit.find || ''} newText={draftText} emptyLabel="No replacement changes." />
+ <label htmlFor={`fix-replace-${scope}-${i}`} className="block px-2 pt-1.5 text-[10px] uppercase tracking-wider text-gray-500">Replacement (editable)</label>
+ <textarea
+ id={`fix-replace-${scope}-${i}`}
+ value={draftText}
+ onChange={(e) => setEditDrafts((prev) => ({ ...prev, [i]: e.target.value }))}
+ rows={Math.min(14, Math.max(3, draftText.split('\n').length + 1))}
+ className="m-2 mt-1 w-[calc(100%-1rem)] px-2 py-1.5 bg-port-bg border border-port-border rounded text-[12px] text-gray-100 font-mono resize-y focus:border-port-accent/50 focus:outline-none"
+ />
+ </div>
+ );
+ })}
+ {fuzzy ? (
+ <p className="text-[10px] text-port-warning">Anchor not found verbatim — accepting may fail; edit the manuscript directly if so.</p>
+ ) : null}
+ </div>
+ ) : null}
+
+ <div className="flex items-center gap-2 pt-0.5">
+ {!hasFix ? (
+ <button
+ type="button"
+ onClick={generate}
+ disabled={generating}
+ className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded text-[12px] font-medium border bg-port-bg text-port-accent border-port-border hover:border-port-accent/40 disabled:opacity-40"
+ >
+ {generating ? <Loader2 size={12} className="animate-spin" /> : <Sparkles size={12} />}
+ Generate fix
+ </button>
+ ) : (
+ <>
+ <button
+ type="button"
+ onClick={accept}
+ disabled={accepting || !fixEdits.some((_, i) => selectedEdits[i] && (editDrafts[i] || '').trim())}
+ className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded text-[12px] font-medium bg-port-success/20 text-port-success border border-port-success/40 hover:bg-port-success/30 disabled:opacity-40"
+ >
+ {accepting ? <Loader2 size={12} className="animate-spin" /> : <Check size={12} />}
+ Accept
+ </button>
+ <button
+ type="button"
+ onClick={generate}
+ disabled={generating || accepting}
+ className="inline-flex items-center gap-1 px-2 py-1 rounded text-[12px] text-gray-400 hover:text-white disabled:opacity-40"
+ title="Regenerate the suggested fix"
+ >
+ {generating ? <Loader2 size={12} className="animate-spin" /> : <Sparkles size={12} />}
+ </button>
+ </>
+ )}
+ <button
+ type="button"
+ onClick={dismiss}
+ className="ml-auto inline-flex items-center gap-1 px-2 py-1 rounded text-[12px] text-gray-500 hover:text-white"
+ >
+ <X size={12} /> Dismiss
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/pipeline/manuscript/ManuscriptCommentIndex.jsx b/client/src/components/pipeline/manuscript/ManuscriptCommentIndex.jsx
new file mode 100644
index 0000000000..d687550001
--- /dev/null
+++ b/client/src/components/pipeline/manuscript/ManuscriptCommentIndex.jsx
@@ -0,0 +1,126 @@
+/**
+ * Sidebar index for editorial comments — a navigable, filterable list rather
+ * than the primary reading surface (the feedback now lives in-context in the
+ * manuscript). Filter by severity; open notes list first, with collapsible
+ * Accepted / Dismissed groups. A row reveals + opens that note in the manuscript.
+ */
+
+import { useMemo, useState } from 'react';
+import { ChevronDown, ChevronRight, Check, X, MapPin } from 'lucide-react';
+import { Badge } from './ManuscriptCommentCard';
+
+const SEVERITIES = ['high', 'medium', 'low'];
+
+function CommentRow({ comment, located, active, onReveal }) {
+ return (
+ <button
+ 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'}`}
+ >
+ <div className="flex items-center justify-between gap-2 mb-1">
+ <Badge comment={comment} />
+ <span className="flex items-center gap-1 text-[10px] text-gray-500">
+ {comment.issueNumber != null ? `Issue ${comment.issueNumber}` : '—'}
+ {located ? <MapPin size={10} className="text-port-accent" title="Located in the manuscript text" /> : null}
+ </span>
+ </div>
+ <span className="text-[11px] text-gray-400 line-clamp-2">{comment.problem}</span>
+ </button>
+ );
+}
+
+function ResolvedGroup({ label, icon: Icon, items, located, openCommentId, onReveal }) {
+ const [open, setOpen] = useState(false);
+ if (items.length === 0) return null;
+ return (
+ <div className="pt-1">
+ <button
+ type="button"
+ onClick={() => setOpen((o) => !o)}
+ className="w-full flex items-center gap-1.5 text-[11px] uppercase tracking-wider text-gray-500 hover:text-gray-300"
+ >
+ {open ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
+ <Icon size={12} /> {label} ({items.length})
+ </button>
+ {open ? (
+ <div className="mt-1.5 space-y-1.5">
+ {items.map((c) => (
+ <CommentRow key={c.id} comment={c} located={located.has(c.id)} active={c.id === openCommentId} onReveal={onReveal} />
+ ))}
+ </div>
+ ) : null}
+ </div>
+ );
+}
+
+export default function ManuscriptCommentIndex({ comments, locatedCommentIds, openCommentId, onReveal }) {
+ const [severityFilter, setSeverityFilter] = useState(null); // null = all
+
+ const grouped = useMemo(() => ({
+ open: comments.filter((c) => c.status === 'open'),
+ accepted: comments.filter((c) => c.status === 'accepted'),
+ dismissed: comments.filter((c) => c.status === 'dismissed'),
+ }), [comments]);
+
+ const openFiltered = severityFilter
+ ? grouped.open.filter((c) => c.severity === severityFilter)
+ : grouped.open;
+
+ const locatedOpen = grouped.open.filter((c) => locatedCommentIds.has(c.id)).length;
+
+ return (
+ <div className="space-y-3">
+ <div className="flex items-center justify-between gap-2">
+ <h2 className="text-xs uppercase tracking-wider text-gray-500">Editorial comments</h2>
+ <span className="text-[11px] text-gray-600">{grouped.open.length} open</span>
+ </div>
+
+ {grouped.open.length > 0 ? (
+ <>
+ <div className="flex items-center gap-1 flex-wrap">
+ <button
+ type="button"
+ onClick={() => setSeverityFilter(null)}
+ className={`px-2 py-0.5 rounded text-[10px] border ${severityFilter === null ? 'bg-port-accent text-white border-port-accent' : 'text-gray-400 border-port-border hover:text-white'}`}
+ >
+ All
+ </button>
+ {SEVERITIES.map((s) => {
+ const n = grouped.open.filter((c) => c.severity === s).length;
+ if (n === 0) return null;
+ return (
+ <button
+ key={s}
+ type="button"
+ onClick={() => setSeverityFilter(severityFilter === s ? null : s)}
+ className={`px-2 py-0.5 rounded text-[10px] border capitalize ${severityFilter === s ? 'bg-port-accent text-white border-port-accent' : 'text-gray-400 border-port-border hover:text-white'}`}
+ >
+ {s} {n}
+ </button>
+ );
+ })}
+ </div>
+ <p className="text-[10px] text-gray-500" title="Notes whose anchor text was found verbatim in the current draft are highlighted in-context; the rest are listed here only.">
+ {locatedOpen} of {grouped.open.length} located in text
+ </p>
+ </>
+ ) : null}
+
+ {comments.length === 0 ? (
+ <p className="text-xs text-gray-500 italic">
+ No comments yet. Run “Finish the draft” from the series arc to generate editorial feedback here.
+ </p>
+ ) : null}
+
+ <div className="space-y-1.5">
+ {openFiltered.map((c) => (
+ <CommentRow key={c.id} comment={c} located={locatedCommentIds.has(c.id)} active={c.id === openCommentId} onReveal={onReveal} />
+ ))}
+ </div>
+
+ <ResolvedGroup label="Accepted" icon={Check} items={grouped.accepted} located={locatedCommentIds} openCommentId={openCommentId} onReveal={onReveal} />
+ <ResolvedGroup label="Dismissed" icon={X} items={grouped.dismissed} located={locatedCommentIds} openCommentId={openCommentId} onReveal={onReveal} />
+ </div>
+ );
+}
diff --git a/client/src/components/pipeline/manuscript/ManuscriptHighlightedProse.jsx b/client/src/components/pipeline/manuscript/ManuscriptHighlightedProse.jsx
new file mode 100644
index 0000000000..5eb54873f3
--- /dev/null
+++ b/client/src/components/pipeline/manuscript/ManuscriptHighlightedProse.jsx
@@ -0,0 +1,37 @@
+/**
+ * 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,
+ * preserving whitespace.
+ */
+
+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]);
+
+ 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>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/client/src/components/pipeline/manuscript/ManuscriptImpactPreview.jsx b/client/src/components/pipeline/manuscript/ManuscriptImpactPreview.jsx
new file mode 100644
index 0000000000..eb171238f2
--- /dev/null
+++ b/client/src/components/pipeline/manuscript/ManuscriptImpactPreview.jsx
@@ -0,0 +1,94 @@
+/**
+ * Whole-manuscript impact preview — a modal that shows, per affected section, a
+ * before/after side-by-side diff of what accepting the currently-selected
+ * editorial fixes would do. Per-card diffs don't convey cumulative impact; this
+ * applies every selected edit (via the same `selectedEditsFor` logic Accept
+ * 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.
+ */
+
+import { useMemo } from 'react';
+import { X } from 'lucide-react';
+import Modal from '../../ui/Modal';
+import SideBySideDiff from '../../ui/SideBySideDiff';
+import { applyEditsToContent } from '../../../lib/applyManuscriptEdits';
+import { selectedEditsFor } from './ManuscriptCommentCard';
+import { STAGE_LABEL } from './constants';
+
+// Gather every selected edit across the given comments, grouped by the section
+// (issueId:stageId) it targets, carrying its comment's anchorQuote for recurring
+// find disambiguation.
+function editsBySectionKey(comments, fixDrafts) {
+ const map = new Map();
+ comments.forEach((c) => {
+ if (!c.fix) return;
+ selectedEditsFor(c, fixDrafts[c.id]).forEach((e) => {
+ if (!e.find) return;
+ const key = `${e.issueId || ''}:${e.stageId || ''}`;
+ if (!map.has(key)) map.set(key, []);
+ map.get(key).push({ find: e.find, replace: e.replace, anchorQuote: c.anchorQuote });
+ });
+ });
+ return map;
+}
+
+export default function ManuscriptImpactPreview({ open, onClose, sections, comments, fixDrafts }) {
+ const changed = useMemo(() => {
+ if (!open) return [];
+ const edits = editsBySectionKey(comments, fixDrafts);
+ return sections
+ .map((s) => {
+ const key = `${s.issueId}:${s.stageId}`;
+ const sectionEdits = edits.get(key);
+ if (!sectionEdits?.length) return null;
+ const after = applyEditsToContent(s.content || '', sectionEdits);
+ if (after === (s.content || '')) return null;
+ return { section: s, before: s.content || '', after, count: sectionEdits.length };
+ })
+ .filter(Boolean);
+ }, [open, sections, comments, fixDrafts]);
+
+ const totalEdits = changed.reduce((n, c) => n + c.count, 0);
+
+ return (
+ <Modal open={open} onClose={onClose} size="3xl" align="top" ariaLabel="Manuscript impact preview">
+ <div className="bg-port-card border border-port-border rounded-lg max-h-[85vh] flex flex-col">
+ <div className="flex items-center justify-between gap-2 px-4 py-3 border-b border-port-border">
+ <div>
+ <h2 className="text-base font-semibold text-white">Impact preview</h2>
+ <p className="text-[11px] text-gray-500">
+ {totalEdits === 0
+ ? 'No selected edits to preview yet — generate a fix and keep its edits checked.'
+ : `${totalEdits} edit${totalEdits === 1 ? '' : 's'} across ${changed.length} issue${changed.length === 1 ? '' : 's'} (preview only — accept from each note)`}
+ </p>
+ </div>
+ <button type="button" onClick={onClose} className="text-gray-400 hover:text-white" aria-label="Close preview" title="Close (Esc)">
+ <X size={18} />
+ </button>
+ </div>
+
+ <div className="flex-1 overflow-y-auto p-4 space-y-4">
+ {changed.length === 0 ? (
+ <p className="text-sm text-gray-500 italic">
+ Nothing to preview. Generate fixes on the open editorial notes (and leave the edits you want checked); they'll show here as before/after diffs.
+ </p>
+ ) : (
+ changed.map(({ section, before, after, count }) => (
+ <div key={`${section.issueId}:${section.stageId}`} className="border border-port-border rounded-lg overflow-hidden">
+ <div className="px-3 py-2 bg-port-bg/60 border-b border-port-border text-sm text-gray-200">
+ Issue {section.number}{section.title ? ` — ${section.title}` : ''}
+ <span className="ml-2 text-[10px] uppercase tracking-wider text-gray-500">{STAGE_LABEL[section.stageId] || section.stageId}</span>
+ <span className="ml-2 text-[10px] text-port-accent">{count} edit{count === 1 ? '' : 's'}</span>
+ </div>
+ <SideBySideDiff oldText={before} newText={after} oldLabel="Current" newLabel="With edits" />
+ </div>
+ ))
+ )}
+ </div>
+ </div>
+ </Modal>
+ );
+}
diff --git a/client/src/components/pipeline/manuscript/ManuscriptLiveSection.jsx b/client/src/components/pipeline/manuscript/ManuscriptLiveSection.jsx
new file mode 100644
index 0000000000..814d83ce65
--- /dev/null
+++ b/client/src/components/pipeline/manuscript/ManuscriptLiveSection.jsx
@@ -0,0 +1,166 @@
+/**
+ * Live (Grammarly-style) manuscript section: the section stays a fully editable
+ * `<textarea>`, with a backdrop layer behind it painting a severity-toned
+ * underline under each anchored editorial comment. Clicking text on an underline
+ * (or a pin chip) opens that comment's card as a popover anchored just below the
+ * highlighted span.
+ *
+ * Why a backdrop instead of a rich editor: the save/version/accept pipeline
+ * round-trips plain strings, and anchors are verbatim substrings — a transparent
+ * mirror div with identical monospace metrics paints underlines exactly under
+ * the words with zero changes to the editing/persistence path. See the plan at
+ * docs/plans/2026-06-06-manuscript-editor-inline-feedback.md.
+ */
+
+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
+import { X } from 'lucide-react';
+import { buildHighlightSegments } from '../../../lib/manuscriptAnchors';
+import ManuscriptCommentCard from './ManuscriptCommentCard';
+import ManuscriptSectionFrame from './ManuscriptSectionFrame';
+import { SEVERITY_UNDERLINE, SEVERITY_TONE, CATEGORY_LABEL, rowsFor } from './constants';
+
+// Identical typography on the textarea and its backdrop so underlines land under
+// the right words. Monospace keeps alignment exact across the two layers.
+const EDITOR_TYPO = 'px-3 py-2 text-sm font-mono leading-relaxed whitespace-pre-wrap break-words';
+
+export default function ManuscriptLiveSection({
+ section, comments, spans, saveState, openCommentId, onOpenComment, onCloseComment,
+ onContentChange, onBlurSave, onRevert, registerRef, commentCardProps,
+}) {
+ const content = section.content || '';
+ const taRef = useRef(null);
+ const backdropRef = useRef(null);
+ const wrapRef = useRef(null);
+ const [popTop, setPopTop] = useState(0);
+
+ const segments = useMemo(() => buildHighlightSegments(content, spans), [content, spans]);
+
+ const byId = useMemo(() => new Map(comments.map((c) => [c.id, c])), [comments]);
+ const anchoredComments = useMemo(
+ () => spans.map((s) => byId.get(s.commentId)).filter(Boolean),
+ [spans, byId],
+ );
+ const unlocatedCount = comments.length - new Set(spans.map((s) => s.commentId)).size;
+
+ const openComment = openCommentId && byId.get(openCommentId)?.status === 'open' ? byId.get(openCommentId) : null;
+
+ // Open the comment whose anchor span covers the caret.
+ const handleCaret = () => {
+ const ta = taRef.current;
+ if (!ta) return;
+ const idx = ta.selectionStart;
+ const hit = spans.find((s) => idx >= s.start && idx < s.end);
+ if (hit) onOpenComment(hit.commentId);
+ };
+
+ // Position the popover just below the open comment's first underline mark.
+ useLayoutEffect(() => {
+ if (!openComment || !backdropRef.current) return;
+ const marks = backdropRef.current.querySelectorAll('mark[data-cids]');
+ const mark = [...marks].find((m) => (m.dataset.cids || '').split(',').includes(openComment.id));
+ setPopTop(mark ? mark.offsetTop + mark.offsetHeight + 4 : 0);
+ }, [openComment, content, segments]);
+
+ // Esc closes the popover.
+ useEffect(() => {
+ if (!openComment) return undefined;
+ const onKey = (e) => { if (e.key === 'Escape') onCloseComment(); };
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [openComment, onCloseComment]);
+
+ return (
+ <ManuscriptSectionFrame section={section} saveState={saveState} onRevert={onRevert}>
+ {/* Pin chips: a touch-friendly, count-bearing way into each anchored note. */}
+ {anchoredComments.length > 0 || unlocatedCount > 0 ? (
+ <div className="flex flex-wrap items-center gap-1">
+ {anchoredComments.map((c) => (
+ <button
+ key={c.id}
+ type="button"
+ onClick={() => onOpenComment(c.id)}
+ className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded border text-[10px] ${SEVERITY_TONE[c.severity] || SEVERITY_TONE.low}`}
+ title={c.problem}
+ >
+ {CATEGORY_LABEL[c.category] || c.category}
+ </button>
+ ))}
+ {unlocatedCount > 0 ? (
+ <span
+ className="text-[10px] text-gray-500"
+ title="These notes' anchor text was not found verbatim in the current draft — they're listed in the sidebar but have no in-text underline."
+ >
+ {unlocatedCount} not located in text
+ </span>
+ ) : null}
+ </div>
+ ) : null}
+
+ <div ref={wrapRef} className="relative">
+ {/* Backdrop: transparent text, only the per-comment underlines show
+ through behind the textarea's real text. aria-hidden — the marks are
+ decorative; the actionable surface is the pin chips + caret-open. */}
+ <div
+ ref={backdropRef}
+ aria-hidden="true"
+ className={`absolute inset-0 overflow-hidden border border-transparent text-transparent select-none pointer-events-none ${EDITOR_TYPO}`}
+ >
+ {segments.map((seg, i) => (
+ seg.commentIds.length ? (
+ <mark
+ key={i}
+ data-cids={seg.commentIds.join(',')}
+ className={`bg-transparent border-b-2 ${SEVERITY_UNDERLINE[seg.topSeverity] || SEVERITY_UNDERLINE.low}`}
+ >
+ {seg.text}
+ </mark>
+ ) : (
+ <span key={i}>{seg.text}</span>
+ )
+ ))}
+ {/* Trailing newline guard so the box height matches the textarea. */}
+ {'\n'}
+ </div>
+
+ <textarea
+ ref={(el) => { taRef.current = el; registerRef(el); }}
+ value={content}
+ onChange={(e) => onContentChange(e.target.value)}
+ onBlur={onBlurSave}
+ onClick={handleCaret}
+ onKeyUp={handleCaret}
+ rows={rowsFor(content)}
+ spellCheck
+ className={`relative w-full bg-transparent border border-port-border rounded text-gray-100 resize-y focus:border-port-accent/50 focus:outline-none ${EDITOR_TYPO}`}
+ />
+
+ {openComment ? (
+ <div className="absolute left-0 right-0 z-20" style={{ top: popTop }}>
+ <div className="rounded-lg border border-port-accent/50 bg-port-card shadow-xl shadow-black/50">
+ <div className="flex items-center justify-between gap-2 px-2.5 py-1.5 border-b border-port-border">
+ <span className="text-[10px] uppercase tracking-wider text-gray-400">Editorial note</span>
+ <button type="button" onClick={onCloseComment} className="text-gray-500 hover:text-white" aria-label="Close note" title="Close note (Esc)">
+ <X size={13} />
+ </button>
+ </div>
+ <div className="p-2">
+ <ManuscriptCommentCard
+ comment={openComment}
+ idScope={`live-${openComment.id}`}
+ seriesId={commentCardProps.seriesId}
+ providerOverride={commentCardProps.providerOverride}
+ modelOverride={commentCardProps.modelOverride}
+ onCommentChange={commentCardProps.onCommentChange}
+ onAccepted={commentCardProps.onAccepted}
+ draft={commentCardProps.fixDrafts[openComment.id]}
+ onDraftChange={(entry) => commentCardProps.setCommentDraft(openComment.id, entry)}
+ onJump={undefined}
+ />
+ </div>
+ </div>
+ </div>
+ ) : null}
+ </div>
+ </ManuscriptSectionFrame>
+ );
+}
diff --git a/client/src/components/pipeline/manuscript/ManuscriptSectionFrame.jsx b/client/src/components/pipeline/manuscript/ManuscriptSectionFrame.jsx
new file mode 100644
index 0000000000..0e664bc6c1
--- /dev/null
+++ b/client/src/components/pipeline/manuscript/ManuscriptSectionFrame.jsx
@@ -0,0 +1,78 @@
+/**
+ * Shared chrome for one manuscript section — the sticky title bar (issue +
+ * stage), the save badge, and the collapsible version history with one-click
+ * revert. The editing surface itself (Live overlay or Review prose) is passed in
+ * as children; `headerExtra` lets a mode add controls beside the title (e.g. an
+ * Edit toggle).
+ */
+
+import { useState } from 'react';
+import { Loader2, History, RotateCcw } from 'lucide-react';
+import { timeAgo } from '../../../utils/formatters';
+import { STAGE_LABEL } from './constants';
+
+function SaveBadge({ state }) {
+ if (state === 'saving') return <span className="text-[10px] text-gray-500 inline-flex items-center gap-1"><Loader2 size={10} className="animate-spin" /> saving</span>;
+ if (state === 'saved') return <span className="text-[10px] text-port-success">saved</span>;
+ return null;
+}
+
+export default function ManuscriptSectionFrame({ section, saveState, onRevert, headerExtra, children }) {
+ const [showVersions, setShowVersions] = useState(false);
+ const [revertingId, setRevertingId] = useState(null);
+ const versions = section.versions || [];
+
+ const revert = async (runId) => {
+ setRevertingId(runId);
+ await onRevert(runId);
+ setRevertingId(null);
+ };
+
+ return (
+ <article className="space-y-1.5">
+ <div className="flex items-center justify-between gap-2 sticky top-0 bg-port-bg/95 backdrop-blur py-1 z-10">
+ <h2 className="text-sm font-semibold text-gray-200">
+ Issue {section.number}{section.title ? ` — ${section.title}` : ''}
+ <span className="ml-2 text-[10px] uppercase tracking-wider text-gray-500">{STAGE_LABEL[section.stageId] || section.stageId}</span>
+ </h2>
+ <div className="flex items-center gap-2">
+ {headerExtra}
+ <SaveBadge state={saveState} />
+ {versions.length > 0 ? (
+ <button
+ type="button"
+ onClick={() => setShowVersions((v) => !v)}
+ className="inline-flex items-center gap-1 text-[11px] text-gray-400 hover:text-white"
+ title="Show prior saved versions"
+ >
+ <History size={12} /> {versions.length}
+ </button>
+ ) : null}
+ </div>
+ </div>
+
+ {showVersions && versions.length > 0 ? (
+ <div className="border border-port-border rounded bg-port-bg/40 p-2 space-y-1">
+ <p className="text-[10px] uppercase tracking-wider text-gray-500">Version history (newest first)</p>
+ {versions.map((v) => (
+ <div key={v.runId} className="flex items-center justify-between gap-2 text-[11px]">
+ <span className="text-gray-400">{v.createdAt ? timeAgo(v.createdAt) : v.runId}</span>
+ <button
+ type="button"
+ onClick={() => revert(v.runId)}
+ disabled={revertingId === v.runId}
+ className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-gray-300 hover:text-white border border-port-border hover:border-port-accent/40 disabled:opacity-40"
+ title="Revert this section to that version (reversible)"
+ >
+ {revertingId === v.runId ? <Loader2 size={11} className="animate-spin" /> : <RotateCcw size={11} />}
+ Revert
+ </button>
+ </div>
+ ))}
+ </div>
+ ) : null}
+
+ {children}
+ </article>
+ );
+}
diff --git a/client/src/components/pipeline/manuscript/constants.js b/client/src/components/pipeline/manuscript/constants.js
new file mode 100644
index 0000000000..94b6321b93
--- /dev/null
+++ b/client/src/components/pipeline/manuscript/constants.js
@@ -0,0 +1,42 @@
+/**
+ * Shared display constants for the Manuscript editor (page + section + card +
+ * preview). Pure data — co-located with the manuscript components.
+ */
+
+export const STAGE_LABEL = { comicScript: 'comic script', teleplay: 'teleplay', prose: 'prose', idea: 'outline' };
+
+// Format switcher: the three manuscript formats the editor can span the full
+// story in. Order mirrors the server's MANUSCRIPT_STAGES precedence.
+export const MANUSCRIPT_TYPES = [
+ { id: 'comicScript', label: 'Comic' },
+ { id: 'teleplay', label: 'Teleplay' },
+ { id: 'prose', label: 'Prose' },
+];
+
+export const SEVERITY_TONE = {
+ high: 'bg-port-error/15 text-port-error border-port-error/40',
+ medium: 'bg-port-warning/15 text-port-warning border-port-warning/40',
+ low: 'bg-gray-600/20 text-gray-300 border-port-border',
+};
+
+// In-text underline color per severity (the Grammarly-style mark). Kept separate
+// from SEVERITY_TONE (which is the badge pill styling) so the underline reads as
+// a decoration rather than a filled block.
+export const SEVERITY_UNDERLINE = {
+ high: 'border-port-error',
+ medium: 'border-port-warning',
+ low: 'border-gray-500',
+};
+
+export const CATEGORY_LABEL = {
+ 'missing-content': 'Missing content',
+ 'arc-gap': 'Arc gap',
+ 'character-gap': 'Character gap',
+ pacing: 'Pacing',
+ continuity: 'Continuity',
+ other: 'Note',
+};
+
+// Approximate a textarea's height to its content so the manuscript reads as one
+// continuous scroll (lets jump-to-anchor scroll the page, not an inner box).
+export const rowsFor = (text) => Math.min(400, Math.max(8, (text || '').split('\n').length + 1));
diff --git a/client/src/components/ui/InlineDiff.jsx b/client/src/components/ui/InlineDiff.jsx
index effaa63a08..5ce34bfa0e 100644
--- a/client/src/components/ui/InlineDiff.jsx
+++ b/client/src/components/ui/InlineDiff.jsx
@@ -1,54 +1,20 @@
/**
- * Inline word-level diff using Myers LCS. Renders two stacked rows:
+ * Inline word-level diff — two stacked rows:
* - the OLD text with removed words highlighted in red
* - the NEW text with added words highlighted in green
- * Shared component — used by the Cross-Domain Insights narrative diff and the
- * Pipeline text-stage history modal. Pure / memoized / no external deps.
+ * Shared component — used by the Cross-Domain Insights narrative diff, the
+ * Pipeline text-stage history modal, and the Manuscript editor's edit cards.
+ * The LCS/tokenize/cap core lives in `client/src/lib/diffWords.js` (shared with
+ * `SideBySideDiff`); this component only renders. Pure / memoized.
*/
import { memo } from 'react';
-
-function lcs(a, b) {
- const m = a.length, n = b.length;
- // Single Int32Array — exactly 4 bytes/cell, no per-element boxing or array
- // overhead the way a nested JS Array would carry. Indexed as dp[i*(n+1)+j]
- // to keep the same (m+1)×(n+1) shape backtracking expects.
- 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 seq = [];
- let i = m, j = n;
- while (i > 0 && j > 0) {
- if (a[i - 1] === b[j - 1]) { seq.unshift(a[i - 1]); i--; j--; }
- else if (dp[(i - 1) * stride + j] >= dp[i * stride + j - 1]) i--;
- else j--;
- }
- return seq;
-}
-
-// LCS allocates an (m+1)×(n+1) Int32Array; the product — not each side — is
-// what matters. Cap at 4M cells (~16MB allocated by the typed array, still
-// inside browser memory for a per-modal computation). The DP runs over
-// `split(/(\s+)/)` tokens, which roughly doubles the input word count
-// (each word + its trailing whitespace is its own token), so a ~1000-word
-// draft becomes ~2000 tokens and a 1000-word-vs-1000-word diff lands at
-// 2000×2000 = 4M cells — right at the cap. Anything larger bails to the
-// side-by-side fallback below rather than risk a tab freeze.
-const DIFF_CELL_CAP = 4_000_000;
+import { diffWords } from '../../lib/diffWords';
+import { renderRuns } from './diffRuns';
const InlineDiff = memo(function InlineDiff({ oldText, newText, emptyLabel = 'No changes.' }) {
const oldStr = oldText || '';
const newStr = newText || '';
- const oldWords = oldStr.split(/(\s+)/);
- const newWords = newStr.split(/(\s+)/);
if (oldStr === newStr) {
return (
@@ -57,7 +23,10 @@ const InlineDiff = memo(function InlineDiff({ oldText, newText, emptyLabel = 'No
</div>
);
}
- if (oldWords.length * newWords.length > DIFF_CELL_CAP) {
+
+ const { tooLarge, oldRuns, newRuns } = diffWords(oldStr, newStr);
+
+ if (tooLarge) {
return (
<div className="font-mono text-xs p-4 space-y-2 bg-port-bg">
<div className="text-gray-500 text-[11px] uppercase tracking-wider">
@@ -68,42 +37,11 @@ const InlineDiff = memo(function InlineDiff({ oldText, newText, emptyLabel = 'No
</div>
);
}
- const commonSeq = lcs(oldWords, newWords);
-
- const render = (words, added) => {
- const spans = [];
- let run = [];
- let ci = 0;
- words.forEach((w, i) => {
- if (ci < commonSeq.length && w === commonSeq[ci]) {
- ci++;
- if (run.length) {
- spans.push(
- <span key={`${i}r`} className={added ? 'bg-green-900/50 text-green-300' : 'bg-red-900/50 text-red-300'}>
- {run.join('')}
- </span>,
- );
- run = [];
- }
- spans.push(w);
- } else {
- run.push(w);
- }
- });
- if (run.length) {
- spans.push(
- <span key="last" className={added ? 'bg-green-900/50 text-green-300' : 'bg-red-900/50 text-red-300'}>
- {run.join('')}
- </span>,
- );
- }
- return spans;
- };
return (
<div className="font-mono text-xs p-4 space-y-2 bg-port-bg">
- <div className="text-red-400 leading-relaxed whitespace-pre-wrap">{render(oldWords, false)}</div>
- <div className="text-green-400 leading-relaxed whitespace-pre-wrap">{render(newWords, true)}</div>
+ <div className="text-red-400 leading-relaxed whitespace-pre-wrap">{renderRuns(oldRuns, false)}</div>
+ <div className="text-green-400 leading-relaxed whitespace-pre-wrap">{renderRuns(newRuns, true)}</div>
</div>
);
});
diff --git a/client/src/components/ui/SideBySideDiff.jsx b/client/src/components/ui/SideBySideDiff.jsx
new file mode 100644
index 0000000000..4aad2220d4
--- /dev/null
+++ b/client/src/components/ui/SideBySideDiff.jsx
@@ -0,0 +1,63 @@
+/**
+ * Columnar word-level diff — OLD on the left (removed words red), NEW on the
+ * right (added words green), so an edit reads as a before/after comparison.
+ * Companion to the stacked `InlineDiff`; both share the LCS/tokenize/cap core in
+ * `client/src/lib/diffWords.js`. Pure / memoized.
+ *
+ * Each column flows independently (whitespace-pre-wrap) rather than aligning
+ * line-for-line — alignment of arbitrary prose rewrites is ambiguous, and the
+ * red/green run highlighting already shows what changed within each side.
+ */
+
+import { memo } from 'react';
+import { diffWords } from '../../lib/diffWords';
+import { renderRuns } from './diffRuns';
+
+const Column = ({ label, children }) => (
+ <div className="min-w-0 flex-1">
+ <div className="text-[10px] uppercase tracking-wider text-gray-500 mb-1">{label}</div>
+ <div className="leading-relaxed whitespace-pre-wrap break-words">{children}</div>
+ </div>
+);
+
+const SideBySideDiff = memo(function SideBySideDiff({
+ oldText, newText, oldLabel = 'Before', newLabel = 'After', emptyLabel = 'No changes.',
+}) {
+ const oldStr = oldText || '';
+ const newStr = newText || '';
+
+ if (oldStr === newStr) {
+ return (
+ <div className="font-mono text-xs p-4 bg-port-bg">
+ <div className="text-gray-500">{emptyLabel}</div>
+ </div>
+ );
+ }
+
+ const { tooLarge, oldRuns, newRuns } = diffWords(oldStr, newStr);
+
+ if (tooLarge) {
+ return (
+ <div className="font-mono text-xs p-4 space-y-2 bg-port-bg">
+ <div className="text-gray-500 text-[11px] uppercase tracking-wider">
+ Diff too large for word highlighting — both versions shown in full
+ </div>
+ <div className="flex gap-4">
+ <Column label={oldLabel}><span className="text-red-400">{oldStr}</span></Column>
+ <Column label={newLabel}><span className="text-green-400">{newStr}</span></Column>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="font-mono text-xs p-4 bg-port-bg">
+ <div className="flex gap-4">
+ <Column label={oldLabel}><span className="text-red-200">{renderRuns(oldRuns, false)}</span></Column>
+ <Column label={newLabel}><span className="text-green-200">{renderRuns(newRuns, true)}</span></Column>
+ </div>
+ </div>
+ );
+});
+
+export default SideBySideDiff;
diff --git a/client/src/components/ui/SideBySideDiff.test.jsx b/client/src/components/ui/SideBySideDiff.test.jsx
new file mode 100644
index 0000000000..dfdba3ff8a
--- /dev/null
+++ b/client/src/components/ui/SideBySideDiff.test.jsx
@@ -0,0 +1,40 @@
+import { describe, it, expect } from 'vitest';
+import { render, screen } from '@testing-library/react';
+
+import SideBySideDiff from './SideBySideDiff';
+
+describe('SideBySideDiff', () => {
+ it('shows the empty-label when the two texts are identical', () => {
+ render(<SideBySideDiff oldText="Hello world" newText="Hello world" />);
+ expect(screen.getByText('No changes.')).toBeInTheDocument();
+ });
+
+ it('renders both columns with their labels when the texts differ', () => {
+ render(<SideBySideDiff oldText="The cat sat" newText="The dog sat" oldLabel="Old" newLabel="New" />);
+ expect(screen.getByText('Old')).toBeInTheDocument();
+ expect(screen.getByText('New')).toBeInTheDocument();
+ expect(screen.queryByText('No changes.')).not.toBeInTheDocument();
+ });
+
+ it('highlights removed words on the left and added words on the right', () => {
+ const { container } = render(<SideBySideDiff oldText="The cat sat" newText="The dog sat" />);
+ 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');
+ });
+
+ it('falls back to both-versions-in-full past the diff cell cap', () => {
+ const build = (p) => Array.from({ length: 2500 }, (_, i) => `${p}${i}`).join(' ');
+ const { container } = render(<SideBySideDiff oldText={build('a')} newText={build('b')} />);
+ expect(screen.getByText(/Diff too large/i)).toBeInTheDocument();
+ expect(container.querySelectorAll('.bg-red-900\\/50, .bg-green-900\\/50')).toHaveLength(0);
+ });
+
+ it('treats null/undefined as empty (identical → empty label)', () => {
+ render(<SideBySideDiff oldText={null} newText={undefined} />);
+ expect(screen.getByText('No changes.')).toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/ui/diffRuns.jsx b/client/src/components/ui/diffRuns.jsx
new file mode 100644
index 0000000000..83774b46d3
--- /dev/null
+++ b/client/src/components/ui/diffRuns.jsx
@@ -0,0 +1,15 @@
+/**
+ * Render the `{ text, changed }` runs from `diffWords` into React nodes —
+ * changed runs get a red (removed) or green (added) highlight span, unchanged
+ * runs render as bare text. Shared by `InlineDiff` (stacked) and
+ * `SideBySideDiff` (columnar) so the highlight markup stays in one place.
+ */
+
+export const renderRuns = (runs, added) =>
+ runs.map((run, i) => (run.changed ? (
+ <span key={i} className={added ? 'bg-green-900/50 text-green-300' : 'bg-red-900/50 text-red-300'}>
+ {run.text}
+ </span>
+ ) : (
+ run.text
+ )));
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 4db7079a90..76228c2825 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -61,17 +61,20 @@ grep -i "what you want to do" client/src/lib/README.md
| Module | Purpose |
|---|---|
+| `applyManuscriptEdits.js` | `applyEditsToContent(content, edits, anchorQuote)` — PREVIEW-ONLY client mirror of the server's accept splice (`server/services/pipeline/manuscriptFix.js`): locate each `find` (nearest the anchor when recurring), drop overlaps, replace bottom-up. Powers the Manuscript editor's whole-manuscript impact preview. |
| `audioRecorder.js` | `startMemoRecording()` → `{ stop, cancel }` handle whose `stop()` resolves to `{ audioBase64, mimeType, peak, durationMs }` (16 kHz mono WAV, base64). Plus `blobToWav16k`, `encodePcmToWav`, `pickRecordingMimeType`, `arrayBufferToBase64`. Standalone one-shot memo capture for catalog voice ingest — NOT the live voice-agent recorder in `services/voiceClient.js`. |
| `clientErrorReporter.js` | `reportClientError({ type, error?, message?, ... })` — POSTs window.onerror + unhandledrejection events to `/api/client-errors` with throttle + dedup. Wired from `main.jsx`; never call directly from React components. |
| `clinicianReport.js` | Pure builders for the MeatSpace clinician-export view (`/meatspace/export`). `buildClinicianReport({ tests, config })` → structured report model (blood panels grouped by category with reference ranges + out-of-range flags, plus a lifestyle summary); `reportToMarkdown(report)` → copy-paste markdown. Reuses the Blood tab's `REFERENCE_RANGES` / `getBloodValueStatus` so printed flags match the UI. Also exports `buildBloodTestModel`, `buildLifestyleModel`, `getCategoryForKey`, `formatRange`. |
| `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). |
| `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. |
| `localLlmTargetKey.js` | `localLlmTargetKey({ backend, modelId })` — stable string key for a local-LLM compare target. Shared by the LocalLlmTab checkbox grid and the LocalLlmPlayground compare URL so a delimiter change can't desync the round-trip. |
| `loopbackHost.js` | `isLoopbackHost(host)` / `isLoopbackOrigin()` / `describeMicAvailability()` — Secure Context / loopback-origin heuristics. Use these in any new mic, clipboard, or `getUserMedia`-gated surface; matches the full `127.0.0.0/8` range, IPv6 `::1`, and the browser-bracketed `[::1]` form. |
+| `manuscriptAnchors.js` | `locateFind` / `locateAnchors` / `buildHighlightSegments` — resolve editorial-comment `anchorQuote`s to spans in manuscript text and tile the text into plain + highlighted (severity-toned) segments for the Manuscript editor's in-context feedback. Mirrors the nearest-occurrence `locateFind` in `server/services/pipeline/manuscriptFix.js`. |
| `mediaNavigation.js` | `getAdjacentMedia(items, item)` — prev/next computation for lightboxes. |
| `mediaSearch.js` | `buildMediaHaystack`, `tokenizeQuery`, `matchHaystack`, `filterByQuery` — client-side AND-token search over normalized media items (prompt/model/seed/LoRA/universe tags). Shared by MediaHistory + the Image Gen gallery picker. |
| `sameJsonShape.js` | `sameJsonShape(prev, next)` — JSON.stringify-based equality for `useAutoRefetch`'s `compare` option on small, deterministically-shaped poll payloads. |
diff --git a/client/src/lib/applyManuscriptEdits.js b/client/src/lib/applyManuscriptEdits.js
new file mode 100644
index 0000000000..2e92b8d46c
--- /dev/null
+++ b/client/src/lib/applyManuscriptEdits.js
@@ -0,0 +1,40 @@
+/**
+ * Client-side preview of applying editorial fix edits to a manuscript section.
+ * Mirrors the server splice in `server/services/pipeline/manuscriptFix.js`
+ * (`acceptManuscriptFix`): locate each `find` (nearest the anchor when it
+ * recurs), then replace from the bottom up so earlier offsets stay valid.
+ *
+ * PREVIEW ONLY — the server route remains authoritative for the real accept.
+ * This exists so the impact-preview modal can show before/after without
+ * mutating anything. Shares `locateFind` with `manuscriptAnchors.js`.
+ */
+
+import { locateFind } from './manuscriptAnchors.js';
+
+// Apply `edits` (each { find, replace, anchorQuote? }) to `content`. Edits whose
+// `find` isn't present are skipped; overlapping edits keep the earlier one.
+export function applyEditsToContent(content, edits, anchorQuote) {
+ const text = content || '';
+ const located = [];
+ (edits || []).forEach((e) => {
+ const find = e?.find || '';
+ if (!find) return;
+ const start = locateFind(text, find, e.anchorQuote ?? anchorQuote);
+ if (start === -1) return;
+ located.push({ start, end: start + find.length, replace: e.replace ?? '' });
+ });
+
+ // Drop overlaps (keep the earlier span), then splice high-to-low.
+ located.sort((a, b) => a.start - b.start);
+ const kept = [];
+ let lastEnd = -1;
+ located.forEach((l) => {
+ if (l.start >= lastEnd) { kept.push(l); lastEnd = l.end; }
+ });
+
+ let out = text;
+ kept.sort((a, b) => b.start - a.start).forEach((l) => {
+ out = out.slice(0, l.start) + l.replace + out.slice(l.end);
+ });
+ return out;
+}
diff --git a/client/src/lib/applyManuscriptEdits.test.js b/client/src/lib/applyManuscriptEdits.test.js
new file mode 100644
index 0000000000..540cfd6ff0
--- /dev/null
+++ b/client/src/lib/applyManuscriptEdits.test.js
@@ -0,0 +1,41 @@
+import { describe, it, expect } from 'vitest';
+import { applyEditsToContent } from './applyManuscriptEdits.js';
+
+describe('applyEditsToContent', () => {
+ it('applies a single find/replace', () => {
+ expect(applyEditsToContent('the door slammed shut', [{ find: 'slammed', replace: 'creaked' }]))
+ .toBe('the door creaked shut');
+ });
+
+ it('applies multiple non-overlapping edits without offset drift', () => {
+ const out = applyEditsToContent('alpha beta gamma', [
+ { find: 'alpha', replace: 'ALPHA' },
+ { find: 'gamma', replace: 'GAMMA' },
+ ]);
+ expect(out).toBe('ALPHA beta GAMMA');
+ });
+
+ it('skips an edit whose find is absent', () => {
+ expect(applyEditsToContent('hello world', [{ find: 'xyz', replace: 'q' }])).toBe('hello world');
+ });
+
+ it('drops a later edit that overlaps an earlier one', () => {
+ // Both target overlapping ranges of "abcdef"; keep the earlier (lower-start).
+ const out = applyEditsToContent('abcdef', [
+ { find: 'abc', replace: 'X' },
+ { find: 'bcd', replace: 'Y' },
+ ]);
+ expect(out).toBe('Xdef');
+ });
+
+ it('disambiguates a recurring find by the anchorQuote', () => {
+ const text = 'run ... [here] run ... done';
+ const out = applyEditsToContent(text, [{ find: 'run', replace: 'WALK', anchorQuote: '[here]' }]);
+ // Replaces the second "run" (nearest the anchor), not the first.
+ expect(out).toBe('run ... [here] WALK ... done');
+ });
+
+ it('returns content unchanged for empty edit list', () => {
+ expect(applyEditsToContent('text', [])).toBe('text');
+ });
+});
diff --git a/client/src/lib/diffWords.js b/client/src/lib/diffWords.js
new file mode 100644
index 0000000000..198ccf1821
--- /dev/null
+++ b/client/src/lib/diffWords.js
@@ -0,0 +1,91 @@
+/**
+ * Word-level diff core (Myers LCS) — the shared computation behind both the
+ * stacked `InlineDiff` and the columnar `SideBySideDiff`. Pure / no React.
+ *
+ * `diffWords(oldText, newText)` tokenizes each side on whitespace (each word and
+ * its trailing whitespace is its own token), finds the longest common
+ * subsequence, and returns the two sides already collapsed into renderable runs:
+ *
+ * { tooLarge, oldRuns, newRuns }
+ * 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.
+ */
+
+export const DIFF_CELL_CAP = 4_000_000;
+
+function lcs(a, b) {
+ const m = a.length, n = b.length;
+ // Single Int32Array — exactly 4 bytes/cell, no per-element boxing the way a
+ // nested JS Array would. Indexed as dp[i*(n+1)+j] to keep the (m+1)×(n+1)
+ // shape backtracking expects.
+ 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 seq = [];
+ let i = m, j = n;
+ while (i > 0 && j > 0) {
+ if (a[i - 1] === b[j - 1]) { seq.unshift(a[i - 1]); i--; j--; }
+ else if (dp[(i - 1) * stride + j] >= dp[i * stride + j - 1]) i--;
+ else j--;
+ }
+ return seq;
+}
+
+// Collapse a token list into runs, marking tokens absent from the common
+// subsequence as changed and merging consecutive same-state tokens into one run.
+function toRuns(words, commonSeq) {
+ const runs = [];
+ let buf = '';
+ let bufChanged = null;
+ let ci = 0;
+ const flush = () => {
+ if (buf) runs.push({ text: buf, changed: bufChanged });
+ buf = '';
+ bufChanged = null;
+ };
+ words.forEach((w) => {
+ const common = ci < commonSeq.length && w === commonSeq[ci];
+ if (common) ci++;
+ const changed = !common;
+ if (bufChanged !== null && bufChanged !== changed) flush();
+ buf += w;
+ bufChanged = changed;
+ });
+ flush();
+ return runs;
+}
+
+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) {
+ return {
+ tooLarge: true,
+ oldRuns: oldStr ? [{ text: oldStr, changed: true }] : [],
+ newRuns: newStr ? [{ text: newStr, changed: true }] : [],
+ };
+ }
+
+ const commonSeq = lcs(oldWords, newWords);
+ return {
+ tooLarge: false,
+ oldRuns: toRuns(oldWords, commonSeq),
+ newRuns: toRuns(newWords, commonSeq),
+ };
+}
diff --git a/client/src/lib/diffWords.test.js b/client/src/lib/diffWords.test.js
new file mode 100644
index 0000000000..922b5c06e8
--- /dev/null
+++ b/client/src/lib/diffWords.test.js
@@ -0,0 +1,54 @@
+import { describe, it, expect } from 'vitest';
+import { diffWords, DIFF_CELL_CAP } from './diffWords.js';
+
+describe('diffWords', () => {
+ it('marks only the changed word on each side, leaving shared words unchanged', () => {
+ const { tooLarge, oldRuns, newRuns } = diffWords('The cat sat', 'The dog sat');
+ expect(tooLarge).toBe(false);
+ const oldChanged = oldRuns.filter((r) => r.changed).map((r) => r.text.trim());
+ const newChanged = newRuns.filter((r) => r.changed).map((r) => r.text.trim());
+ expect(oldChanged).toEqual(['cat']);
+ expect(newChanged).toEqual(['dog']);
+ // Reassembling the runs reproduces each side verbatim.
+ expect(oldRuns.map((r) => r.text).join('')).toBe('The cat sat');
+ expect(newRuns.map((r) => r.text).join('')).toBe('The dog sat');
+ });
+
+ it('treats null/undefined as empty strings', () => {
+ const { oldRuns, newRuns } = diffWords(null, undefined);
+ expect(oldRuns.map((r) => r.text).join('')).toBe('');
+ expect(newRuns.map((r) => r.text).join('')).toBe('');
+ });
+
+ it('merges consecutive changed words into a single run', () => {
+ const { newRuns } = diffWords('a d', 'a b c d');
+ // "b c " inserted between the shared "a " and "d" → one changed run.
+ const changed = newRuns.filter((r) => r.changed);
+ expect(changed).toHaveLength(1);
+ expect(changed[0].text.trim()).toBe('b c');
+ });
+
+ it('reports every word as changed when there is no overlap', () => {
+ const { oldRuns, newRuns } = diffWords('alpha', 'omega');
+ expect(oldRuns.every((r) => r.changed)).toBe(true);
+ expect(newRuns.every((r) => r.changed)).toBe(true);
+ });
+
+ it('bails to tooLarge when the DP cell product exceeds the cap', () => {
+ const build = (p) => Array.from({ length: 2500 }, (_, i) => `${p}${i}`).join(' ');
+ const { tooLarge, oldRuns, newRuns } = diffWords(build('a'), build('b'));
+ expect(tooLarge).toBe(true);
+ // Fallback collapses each side to one changed run (no per-word LCS work).
+ expect(oldRuns).toHaveLength(1);
+ expect(newRuns).toHaveLength(1);
+ });
+
+ 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);
+ });
+
+ it('exports the documented cap', () => {
+ expect(DIFF_CELL_CAP).toBe(4_000_000);
+ });
+});
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 495c648696..c76d730f25 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -32,17 +32,20 @@ export * from './wrImageDefaults.js';
export * from './graphSimulation.js';
// === Generic UI / collection utilities ===
+export * from './applyManuscriptEdits.js';
export * from './audioRecorder.js';
export * from './clientErrorReporter.js';
export * from './clinicianReport.js';
export * from './clipboard.js';
export * from './compareHelpers.js';
export * from './consoleFilters.js';
+export * from './diffWords.js';
export * from './genUtils.js';
export * from './healthProvenance.js';
export * from './joinInfluenceList.js';
export * from './localLlmTargetKey.js';
export * from './loopbackHost.js';
+export * from './manuscriptAnchors.js';
export * from './mediaNavigation.js';
export * from './mediaSearch.js';
export * from './sameJsonShape.js';
diff --git a/client/src/lib/manuscriptAnchors.js b/client/src/lib/manuscriptAnchors.js
new file mode 100644
index 0000000000..6ab9ede89b
--- /dev/null
+++ b/client/src/lib/manuscriptAnchors.js
@@ -0,0 +1,89 @@
+/**
+ * Manuscript anchor location + highlight segmentation for the in-context
+ * editorial-feedback editor. Pure / no React.
+ *
+ * Editorial comments anchor to manuscript text by VERBATIM substring
+ * (`anchorQuote`), not character offsets — mirroring the server. `locateFind`
+ * here mirrors `locateFind` in `server/services/pipeline/manuscriptFix.js`
+ * (nearest-occurrence disambiguation) so a highlight lands where an accepted fix
+ * would actually splice. It is also reused by `applyManuscriptEdits.js` for the
+ * client-side impact preview.
+ *
+ * locateAnchors(content, comments) → [{ commentId, severity, start, end }]
+ * buildHighlightSegments(content, spans) → [{ text, commentIds, topSeverity }]
+ *
+ * `buildHighlightSegments` flattens possibly-overlapping/recurring spans into an
+ * ordered list of non-overlapping segments that tile the whole content: a
+ * segment with an empty `commentIds` is plain text; otherwise it's a highlight
+ * carrying every comment covering it, toned by the highest severity present.
+ */
+
+const SEVERITY_RANK = { high: 3, medium: 2, low: 1 };
+
+// Locate the `find` span to highlight/replace. `indexOf` alone targets the FIRST
+// match, which is the wrong spot when `find` recurs. When ambiguous, pick the
+// occurrence nearest the `anchorQuote`. Returns the start index, or -1 if absent.
+export function locateFind(text, find, anchorQuote) {
+ if (!find) return -1;
+ const first = text.indexOf(find);
+ if (first === -1) return -1;
+ if (text.indexOf(find, first + 1) === -1) return first; // unique
+ const anchorIdx = anchorQuote ? text.indexOf(anchorQuote) : -1;
+ if (anchorIdx === -1) return first; // can't disambiguate — first match
+ let best = first;
+ let bestDist = Math.abs(first - anchorIdx);
+ for (let i = text.indexOf(find, first + 1); i !== -1; i = text.indexOf(find, i + 1)) {
+ const dist = Math.abs(i - anchorIdx);
+ if (dist < bestDist) { best = i; bestDist = dist; }
+ }
+ return best;
+}
+
+// Resolve each comment's anchorQuote to a [start, end) span in `content`.
+// Comments whose anchor isn't present (edited since review, or fuzzy) are
+// dropped — they stay listed in the sidebar but show no in-text highlight.
+export function locateAnchors(content, comments) {
+ const text = content || '';
+ const spans = [];
+ (comments || []).forEach((c) => {
+ const quote = c?.anchorQuote || '';
+ if (!quote) return;
+ const start = text.indexOf(quote);
+ if (start === -1) return;
+ spans.push({ commentId: c.id, severity: c.severity || 'low', start, end: start + quote.length });
+ });
+ return spans;
+}
+
+// Flatten spans into ordered, non-overlapping segments tiling the whole content.
+export function buildHighlightSegments(content, spans) {
+ const text = content || '';
+ const valid = (spans || [])
+ .map((s) => ({ ...s, start: Math.max(0, s.start), end: Math.min(text.length, s.end) }))
+ .filter((s) => s.end > s.start);
+ if (valid.length === 0) {
+ return text ? [{ text, commentIds: [], topSeverity: null }] : [];
+ }
+
+ // Boundary sweep: every span edge plus the document ends.
+ const bounds = new Set([0, text.length]);
+ valid.forEach((s) => { bounds.add(s.start); bounds.add(s.end); });
+ const points = [...bounds].sort((a, b) => a - b);
+
+ const segments = [];
+ for (let i = 0; i < points.length - 1; i++) {
+ const from = points[i];
+ const to = points[i + 1];
+ if (to <= from) continue;
+ const covering = valid.filter((s) => s.start <= from && s.end >= to);
+ const commentIds = covering.map((s) => s.commentId);
+ let topSeverity = null;
+ covering.forEach((s) => {
+ if (!topSeverity || (SEVERITY_RANK[s.severity] || 0) > (SEVERITY_RANK[topSeverity] || 0)) {
+ topSeverity = s.severity;
+ }
+ });
+ segments.push({ text: text.slice(from, to), commentIds, topSeverity });
+ }
+ return segments;
+}
diff --git a/client/src/lib/manuscriptAnchors.test.js b/client/src/lib/manuscriptAnchors.test.js
new file mode 100644
index 0000000000..ce207019db
--- /dev/null
+++ b/client/src/lib/manuscriptAnchors.test.js
@@ -0,0 +1,78 @@
+import { describe, it, expect } from 'vitest';
+import { locateFind, locateAnchors, buildHighlightSegments } from './manuscriptAnchors.js';
+
+describe('locateFind', () => {
+ it('returns the only occurrence when unique', () => {
+ expect(locateFind('the quick brown fox', 'brown')).toBe(10);
+ });
+
+ it('returns -1 when absent', () => {
+ expect(locateFind('hello world', 'xyz')).toBe(-1);
+ });
+
+ it('disambiguates a recurring find by nearest anchorQuote', () => {
+ const text = 'door alpha beta gamma delta [marker] door omega';
+ const second = text.indexOf('door', 1);
+ // The "[marker]" anchor sits right before the second "door", so that's the
+ // occurrence chosen — not the first.
+ expect(locateFind(text, 'door', '[marker]')).toBe(second);
+ expect(second).toBeGreaterThan(0);
+ });
+
+ it('falls back to the first match when no anchor is given', () => {
+ const text = 'door ... door';
+ expect(locateFind(text, 'door')).toBe(0);
+ });
+});
+
+describe('locateAnchors', () => {
+ const content = 'She crept down the hall. The door slammed shut.';
+ it('resolves present anchors to spans and drops absent ones', () => {
+ const spans = locateAnchors(content, [
+ { id: 'a', severity: 'high', anchorQuote: 'door slammed' },
+ { id: 'b', severity: 'low', anchorQuote: 'not in the text' },
+ { id: 'c', severity: 'medium', anchorQuote: '' },
+ ]);
+ expect(spans).toEqual([
+ { commentId: 'a', severity: 'high', start: content.indexOf('door slammed'), end: content.indexOf('door slammed') + 'door slammed'.length },
+ ]);
+ });
+});
+
+describe('buildHighlightSegments', () => {
+ it('returns one plain segment when there are no spans', () => {
+ expect(buildHighlightSegments('hello', [])).toEqual([{ text: 'hello', commentIds: [], topSeverity: null }]);
+ });
+
+ it('tiles content into plain + highlighted segments', () => {
+ const text = 'abcdef';
+ const segs = buildHighlightSegments(text, [{ commentId: 'x', severity: 'medium', start: 2, end: 4 }]);
+ expect(segs.map((s) => s.text).join('')).toBe(text);
+ expect(segs).toEqual([
+ { text: 'ab', commentIds: [], topSeverity: null },
+ { text: 'cd', commentIds: ['x'], topSeverity: 'medium' },
+ { text: 'ef', commentIds: [], topSeverity: null },
+ ]);
+ });
+
+ it('merges overlapping spans into a segment carrying both, toned by top severity', () => {
+ const text = 'abcdefgh';
+ const segs = buildHighlightSegments(text, [
+ { commentId: 'x', severity: 'low', start: 1, end: 5 },
+ { commentId: 'y', severity: 'high', start: 3, end: 7 },
+ ]);
+ expect(segs.map((s) => s.text).join('')).toBe(text);
+ const overlap = segs.find((s) => s.commentIds.length === 2);
+ expect(overlap.text).toBe('de');
+ expect(overlap.topSeverity).toBe('high');
+ });
+
+ it('clamps out-of-range spans and drops empty ones', () => {
+ const segs = buildHighlightSegments('abc', [
+ { commentId: 'x', severity: 'low', start: -5, end: 2 },
+ { commentId: 'y', severity: 'low', start: 2, end: 2 },
+ ]);
+ expect(segs.map((s) => s.text).join('')).toBe('abc');
+ expect(segs[0]).toEqual({ text: 'ab', commentIds: ['x'], topSeverity: 'low' });
+ });
+});
diff --git a/client/src/pages/PipelineManuscriptEditor.jsx b/client/src/pages/PipelineManuscriptEditor.jsx
index d6be61df5e..8bcade2bf3 100644
--- a/client/src/pages/PipelineManuscriptEditor.jsx
+++ b/client/src/pages/PipelineManuscriptEditor.jsx
@@ -2,121 +2,101 @@
* Pipeline — Manuscript Editor.
*
* Full-bleed two-pane workspace (`/pipeline/series/:seriesId/manuscript`) that
- * makes the "Finish the draft" pass actionable:
- * - Left : the whole series manuscript, one editable section per issue in
- * story order. The series "manuscript" is virtual — one chosen
- * stage per issue (comicScript ▸ teleplay ▸ prose). Each section is
- * a free-text editor that saves back to that issue's stage on blur.
- * - Right : Word-style editorial comments from the completeness pass. Click a
- * comment to jump to (and select) its anchor in the manuscript,
- * generate AI edit suggestions, review diffs, edit/skip individual
- * suggestions, and accept them into the manuscript — or dismiss it.
+ * makes the "Finish the draft" pass actionable, with editorial feedback shown
+ * IN CONTEXT inside the manuscript instead of read out of a disconnected list:
+ * - Left : the whole series manuscript, one section per issue in story order.
+ * The series "manuscript" is virtual — one chosen stage per issue
+ * (comicScript ▸ teleplay ▸ prose). Two viewing modes (toggle in the
+ * header, persisted): "Live" keeps each section editable with
+ * Grammarly-style underlines under anchored notes (click → popover);
+ * "Review" shows read-only annotated prose with click-to-expand
+ * 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.
*
* Data: GET /pipeline/series/:id/manuscript (sections) + .../manuscript/review
* (comments). Section saves reuse PATCH /pipeline/issues/:id; fixes go through
- * the manuscript-review fix/accept routes.
+ * the manuscript-review fix/accept routes. See the design record at
+ * docs/plans/2026-06-06-manuscript-editor-inline-feedback.md.
*/
import { useEffect, useMemo, useRef, useState } from 'react';
import { Link, useParams, useNavigate } from 'react-router-dom';
import {
- ArrowLeft, Loader2, Sparkles, Check, X, CornerDownRight, FileText, ChevronDown, ChevronRight, Star, History, RotateCcw, ClipboardCheck, Layers,
+ ArrowLeft, Loader2, Sparkles, FileText, Star, ClipboardCheck, Layers, PencilLine, BookOpen, GitCompare,
} from 'lucide-react';
-import InlineDiff from '../components/ui/InlineDiff';
import toast from '../components/ui/Toast';
import { useAsyncAction } from '../hooks/useAsyncAction';
-import { timeAgo } from '../utils/formatters';
import { filterGenerationModels, mergeModelLists, localBackendForProvider, modelOptionLabel } from '../utils/providers';
import useLocalModels from '../hooks/useLocalModels';
+import { locateAnchors } from '../lib/manuscriptAnchors';
+import ManuscriptLiveSection from '../components/pipeline/manuscript/ManuscriptLiveSection';
+import AnnotatedManuscriptSection from '../components/pipeline/manuscript/AnnotatedManuscriptSection';
+import ManuscriptCommentIndex from '../components/pipeline/manuscript/ManuscriptCommentIndex';
+import ManuscriptImpactPreview from '../components/pipeline/manuscript/ManuscriptImpactPreview';
+import { MANUSCRIPT_TYPES, STAGE_LABEL } from '../components/pipeline/manuscript/constants';
import {
getPipelineSeries, updatePipelineSeries, getPipelineManuscript, getPipelineManuscriptReview,
- patchPipelineManuscriptComment, savePipelineManuscriptSection, restorePipelineStageVersion,
- generatePipelineManuscriptFix, acceptPipelineManuscriptFix,
+ savePipelineManuscriptSection, restorePipelineStageVersion,
analyzePipelineManuscriptCompleteness, getProviders,
} from '../services/api';
-const STAGE_LABEL = { comicScript: 'comic script', teleplay: 'teleplay', prose: 'prose', idea: 'outline' };
-// Format switcher: the three manuscript formats the editor can span the full
-// story in. Order mirrors the server's MANUSCRIPT_STAGES precedence.
-const MANUSCRIPT_TYPES = [
- { id: 'comicScript', label: 'Comic' },
- { id: 'teleplay', label: 'Teleplay' },
- { id: 'prose', label: 'Prose' },
-];
-
-const SEVERITY_TONE = {
- high: 'bg-port-error/15 text-port-error border-port-error/40',
- medium: 'bg-port-warning/15 text-port-warning border-port-warning/40',
- low: 'bg-gray-600/20 text-gray-300 border-port-border',
-};
+// Stable empty array so sections that gain no comments/spans don't get a fresh
+// `[]` identity every render.
+const EMPTY = [];
-const CATEGORY_LABEL = {
- 'missing-content': 'Missing content',
- 'arc-gap': 'Arc gap',
- 'character-gap': 'Character gap',
- pacing: 'Pacing',
- continuity: 'Continuity',
- other: 'Note',
+const VIEW_MODE_KEY = 'portos.manuscript.viewMode';
+const initialViewMode = () => {
+ if (typeof window === 'undefined') return 'live';
+ return window.localStorage.getItem(VIEW_MODE_KEY) === 'review' ? 'review' : 'live';
};
-// Approximate the textarea height to its content so the manuscript reads as one
-// continuous scroll (lets jump-to-anchor scroll the page, not an inner box).
-const rowsFor = (text) => Math.min(400, Math.max(8, (text || '').split('\n').length + 1));
-
export default function PipelineManuscriptEditor() {
const { seriesId } = useParams();
const navigate = useNavigate();
const [series, setSeries] = useState(null);
const [sections, setSections] = useState([]);
const [viewType, setViewType] = useState(null); // format currently shown
- const [pinnedPrimary, setPinnedPrimary] = useState(null); // explicit bible value (may be null)
- const [availableTypes, setAvailableTypes] = useState([]); // formats with ≥1 drafted issue
+ const [pinnedPrimary, setPinnedPrimary] = useState(null);
+ const [availableTypes, setAvailableTypes] = useState([]);
const [comments, setComments] = useState([]);
- // Coverage shape of the last completeness run: { chunked, chunkCount }. A
- // chunked run means the model couldn't hold the whole manuscript at once
- // (small context window) — surfaced so the review's coverage isn't ambiguous.
const [reviewMeta, setReviewMeta] = useState(null);
- // Re-run mode for the editorial pass: false = merge (leave prior notes as-is),
- // true = fresh (reconcile: auto-dismiss open notes this pass no longer finds;
- // accepted/dismissed left untouched). See the route's seedReviewFromFindings.
const [freshReview, setFreshReview] = useState(false);
const [loading, setLoading] = useState(true);
const [switching, setSwitching] = useState(false);
const [pinning, setPinning] = useState(false);
- // AI provider override for Generate-fix + Editorial-review actions.
- // '' means "System default" (no override sent to server). Intentionally NOT
- // auto-selected — useProviderModels always picks the first provider, but here
- // "no selection" is the correct default so we manage this state directly.
const [providers, setProviders] = useState([]);
const [overrideProviderId, setOverrideProviderId] = useState('');
const [overrideModel, setOverrideModel] = useState('');
- // Per-issue free-text save state: 'saving' | 'saved' | undefined.
const [saveState, setSaveState] = useState({});
- // The comment last jumped to — pinned as a floating overlay so its editorial
- // context (and its Generate/Accept/Dismiss actions) stay on screen after the
- // manuscript scrolls away from the sidebar card. null = no overlay.
- const [activeCommentId, setActiveCommentId] = useState(null);
- // Per-comment fix-edit drafts (replacement text + which edits are checked),
- // lifted out of CommentCard and keyed by comment id so the sidebar card and
- // the pinned overlay card of the same comment share one editing state —
- // editing a fix in one and accepting from the other no longer loses the
- // in-progress edit. Each entry stamps the fixKey it was derived from.
+ // 'live' (Grammarly editable + underlines) | 'review' (annotated read-then-edit).
+ const [viewMode, setViewMode] = useState(initialViewMode);
+ // The comment whose card is open in-context (popover in Live, inline in Review).
+ const [openCommentId, setOpenCommentId] = useState(null);
+ // Which section (issueId) is in textarea edit mode in Review.
+ const [editingIssueId, setEditingIssueId] = useState(null);
+ const [showImpact, setShowImpact] = useState(false);
+ // Per-comment fix-edit drafts, keyed by comment id and shared across every
+ // place the card renders (sidebar reveal, in-context card, impact preview).
const [fixDrafts, setFixDrafts] = useState({});
const setCommentDraft = (commentId, entry) =>
setFixDrafts((prev) => ({ ...prev, [commentId]: entry }));
- // textarea elements keyed by issue number, for jump-to-anchor.
+ // textarea elements keyed by issue number, for reveal-to-section scroll/focus.
const sectionRefs = useRef(new Map());
- // Last-saved content per `${issueId}:${stageId}`, so a blur with no change
- // doesn't create a spurious version.
const baselineRef = useRef(new Map());
const seedBaselines = (list) => {
baselineRef.current = new Map((list || []).map((s) => [`${s.issueId}:${s.stageId}`, s.content]));
};
- // Patch one section's fields (content/versions) in place after a save/revert.
const patchSection = (issueId, fields) =>
setSections((prev) => prev.map((s) => (s.issueId === issueId ? { ...s, ...fields } : s)));
+ useEffect(() => {
+ if (typeof window !== 'undefined') window.localStorage.setItem(VIEW_MODE_KEY, viewMode);
+ }, [viewMode]);
+
useEffect(() => {
let canceled = false;
Promise.all([
@@ -144,7 +124,6 @@ export default function PipelineManuscriptEditor() {
return () => { canceled = true; };
}, [seriesId, navigate]);
- // Load the enabled provider list once for the override selector.
useEffect(() => {
let canceled = false;
getProviders()
@@ -154,12 +133,8 @@ export default function PipelineManuscriptEditor() {
}, []);
const overrideProvider = providers.find((p) => p.id === overrideProviderId) || null;
- // Live installed local-LLM models, so a local provider's picker shows what's
- // actually installed in Ollama/LM Studio — not just its stale stored `models`.
const localModels = useLocalModels();
const overrideBackend = localBackendForProvider(overrideProvider);
- // Memoized so the array identity is stable across renders — it's a dependency
- // of the auto-select effect below, which would otherwise re-run every render.
const overrideModels = useMemo(
() => filterGenerationModels(
mergeModelLists(
@@ -169,19 +144,11 @@ export default function PipelineManuscriptEditor() {
),
[overrideProvider, overrideBackend, localModels],
);
- // Best installed model for editorial review/editing (Ollama/LM Studio only).
const editorialPick = overrideBackend ? localModels.recommendations?.[overrideBackend] : null;
const showEditorialPick = Boolean(
editorialPick?.id && overrideModels.includes(editorialPick.id) && overrideModel !== editorialPick.id,
);
- // Keep the model selection honest. A controlled <select> whose value isn't one
- // of its options shows the first option but holds an empty value — so a
- // provider with no defaultModel (Ollama: defaultModel null) looked like a real
- // model was picked while the override sent to the server was empty, and the
- // server fell through to models[0] (the embedding model). Once a provider is
- // chosen, pin a concrete in-list model (the editorial recommendation when
- // available, else the first) so what the user sees is what actually runs.
useEffect(() => {
if (!overrideProviderId || overrideModels.length === 0) return;
if (overrideModel && overrideModels.includes(overrideModel)) return;
@@ -191,23 +158,15 @@ export default function PipelineManuscriptEditor() {
setOverrideModel(pick);
}, [overrideProviderId, overrideModels, editorialPick, overrideModel]);
- // undefined (not '') so the server treats it as "no override" → system default.
const providerOverride = overrideProviderId || undefined;
const modelOverride = overrideModel || undefined;
const changeOverrideProvider = (id) => {
setOverrideProviderId(id);
const p = providers.find((pr) => pr.id === id);
- // Provisional; the effect above pins a valid in-list model once the
- // (possibly async) live model list resolves.
setOverrideModel(p?.defaultModel || '');
};
- // Re-run the editorial completeness pass over the manuscript with the chosen
- // provider. The route persists findings as the review comment set, so we just
- // swap in the returned comments. `mode`: 'merge' (default) leaves prior notes
- // as-is and appends new findings; 'fresh' also auto-dismisses open notes this
- // pass no longer finds (accepted/dismissed untouched).
const [runEditorialReview, reviewing] = useAsyncAction(
async (mode = 'merge') => {
const result = await analyzePipelineManuscriptCompleteness(seriesId, { providerOverride, modelOverride, mode });
@@ -222,8 +181,6 @@ export default function PipelineManuscriptEditor() {
{ errorMessage: 'Failed to run editorial review' },
);
- // Switch which format the editor spans. Refetches that format's full-story
- // sections (every issue, empty where undrafted).
const changeView = async (type) => {
if (type === viewType || switching) return;
setSwitching(true);
@@ -239,9 +196,10 @@ export default function PipelineManuscriptEditor() {
setViewType(manuscript.viewType || type);
setAvailableTypes(Array.isArray(manuscript.availableTypes) ? manuscript.availableTypes : availableTypes);
setSaveState({});
+ setOpenCommentId(null);
+ setEditingIssueId(null);
};
- // Pin the format currently being viewed as the series' source of truth.
const pinPrimary = async () => {
if (!viewType || pinning) return;
setPinning(true);
@@ -255,13 +213,9 @@ export default function PipelineManuscriptEditor() {
const setSectionContent = (issueId, content) => patchSection(issueId, { content });
- // Save a section's edited text back to its issue stage (versioned — snapshots
- // the prior text so the edit is revertible). Skips no-op blurs so we don't
- // mint a version for an unchanged section. Server serializes the write, so a
- // blur-save can't clobber a concurrent accept on the same stage.
const saveSection = async (section) => {
const key = `${section.issueId}:${section.stageId}`;
- if (baselineRef.current.get(key) === section.content) return; // unchanged — nothing to version
+ if (baselineRef.current.get(key) === section.content) return;
setSaveState((prev) => ({ ...prev, [section.issueId]: 'saving' }));
const result = await savePipelineManuscriptSection(
seriesId,
@@ -279,9 +233,6 @@ export default function PipelineManuscriptEditor() {
setSaveState((prev) => ({ ...prev, [section.issueId]: result ? 'saved' : undefined }));
};
- // Revert a section to a prior version (runId from its history). The restore
- // route snapshots the now-displaced text first, so revert is itself
- // reversible. Updates content + versions in place.
const revertSection = async (section, runId) => {
const result = await restorePipelineStageVersion(section.issueId, section.stageId, runId, { silent: true })
.catch((err) => { toast.error(err.message || 'Failed to revert'); return null; });
@@ -295,35 +246,26 @@ export default function PipelineManuscriptEditor() {
return result;
};
- // Jump to a comment's anchor: focus the issue's textarea, select the verbatim
- // quote (native selection highlights it), and scroll it into view.
- const jumpToComment = (comment) => {
- // Pin the comment to the overlay first, so even an unanchored note keeps its
- // context (and actions) visible while the user works in the manuscript.
- setActiveCommentId(comment.id);
+ // Reveal a comment in context: open its card and scroll its section into view
+ // (focusing the textarea if that section is being edited).
+ const revealComment = (comment) => {
+ setOpenCommentId(comment.id);
const ta = comment.issueNumber != null ? sectionRefs.current.get(comment.issueNumber) : null;
if (!ta) {
toast('This comment is not anchored to a specific issue');
return;
}
ta.scrollIntoView?.({ behavior: 'smooth', block: 'start' });
- const quote = comment.anchorQuote || '';
- const idx = quote ? ta.value.indexOf(quote) : -1;
- ta.focus();
- if (idx !== -1) ta.setSelectionRange(idx, idx + quote.length);
- else ta.setSelectionRange(0, 0);
+ if (document.activeElement === ta || editingIssueId) {
+ const quote = comment.anchorQuote || '';
+ const idx = quote ? ta.value.indexOf(quote) : -1;
+ if (idx !== -1) { ta.focus(); ta.setSelectionRange(idx, idx + quote.length); }
+ }
};
const updateCommentLocal = (next) =>
setComments((prev) => prev.map((c) => (c.id === next.id ? next : c)));
- // After an accepted fix the server returns the rewritten section — reflect it
- // in the manuscript pane so the edit shows without a reload. A comment can
- // target a format other than the one on screen (the sidebar shows all
- // comments); only patch the visible textarea when the edited stage matches
- // the current view, or we'd paint (and later blur-save) the wrong format's
- // text into this section. The edit still persisted server-side — it shows on
- // switching to that format.
const applyAccepted = ({ comment, section, sections: changedSections }) => {
const list = Array.isArray(changedSections) && changedSections.length ? changedSections : [section].filter(Boolean);
list.forEach((changed) => {
@@ -336,18 +278,54 @@ export default function PipelineManuscriptEditor() {
if (comment) updateCommentLocal(comment);
};
- const grouped = useMemo(() => ({
- open: comments.filter((c) => c.status === 'open'),
- accepted: comments.filter((c) => c.status === 'accepted'),
- dismissed: comments.filter((c) => c.status === 'dismissed'),
- }), [comments]);
+ // Open editorial comments anchorable to the on-screen format, grouped by issue
+ // number. Comments targeting a different stage stay index-only (no highlight).
+ const openCommentsByNumber = useMemo(() => {
+ const map = new Map();
+ comments.forEach((c) => {
+ if (c.status !== 'open') return;
+ if (c.stageId && viewType && c.stageId !== viewType) return;
+ if (c.issueNumber == null) return;
+ if (!map.has(c.issueNumber)) map.set(c.issueNumber, []);
+ map.get(c.issueNumber).push(c);
+ });
+ return map;
+ }, [comments, viewType]);
+
+ // Locate every open comment's anchor span per section once, here — the
+ // sections render from these rather than recomputing locateAnchors each.
+ const sectionSpans = useMemo(() => {
+ const map = new Map();
+ sections.forEach((s) => {
+ map.set(s.issueId, locateAnchors(s.content || '', openCommentsByNumber.get(s.number) || []));
+ });
+ return map;
+ }, [sections, openCommentsByNumber]);
+
+ // Which comments actually located their anchor in the current draft.
+ const locatedCommentIds = useMemo(() => {
+ const set = new Set();
+ sectionSpans.forEach((spans) => spans.forEach((span) => set.add(span.commentId)));
+ return set;
+ }, [sectionSpans]);
+
+ // Plain object (not memoized): its handlers close over viewType/sections, so a
+ // stale memo would apply accepts against the wrong format. Children read
+ // individual fields rather than the object identity, so there's nothing to gain.
+ const commentCardProps = {
+ seriesId,
+ providerOverride,
+ modelOverride,
+ onCommentChange: updateCommentLocal,
+ onAccepted: applyAccepted,
+ fixDrafts,
+ setCommentDraft,
+ };
- // Only pin still-open comments — accepting/dismissing flips the status, which
- // resolves this to null and closes the overlay automatically (resolved
- // comments are navigational only, with no actions to keep on screen).
- const activeComment = activeCommentId
- ? comments.find((c) => c.id === activeCommentId && c.status === 'open')
- : null;
+ const registerSectionRef = (number) => (el) => {
+ if (el) sectionRefs.current.set(number, el);
+ else sectionRefs.current.delete(number);
+ };
if (loading) return <div className="p-6 text-gray-500 text-sm">Loading manuscript…</div>;
@@ -364,6 +342,35 @@ export default function PipelineManuscriptEditor() {
<h1 className="text-xl font-bold text-white truncate">{series?.name || 'Manuscript'}</h1>
<div className="ml-auto flex items-center gap-2 flex-wrap">
+ {/* View-mode toggle: Live (Grammarly) vs Review (annotated). */}
+ <div className="inline-flex rounded-lg border border-port-border overflow-hidden">
+ <button
+ type="button"
+ onClick={() => setViewMode('live')}
+ title="Live editing with inline underlines (Grammarly-style)"
+ className={`px-2.5 py-1.5 text-sm font-medium inline-flex items-center gap-1 ${viewMode === 'live' ? 'bg-port-accent text-white' : 'bg-port-bg text-gray-400 hover:text-white'}`}
+ >
+ <PencilLine size={13} /> Live
+ </button>
+ <button
+ type="button"
+ onClick={() => { setViewMode('review'); setEditingIssueId(null); }}
+ title="Annotated read-through with click-to-expand notes"
+ className={`px-2.5 py-1.5 text-sm font-medium inline-flex items-center gap-1 ${viewMode === 'review' ? 'bg-port-accent text-white' : 'bg-port-bg text-gray-400 hover:text-white'}`}
+ >
+ <BookOpen size={13} /> Review
+ </button>
+ </div>
+
+ <button
+ type="button"
+ onClick={() => setShowImpact(true)}
+ title="Preview how the selected fixes change the whole manuscript"
+ className="inline-flex items-center gap-1 px-2.5 py-1.5 rounded text-xs font-medium border bg-port-bg text-gray-300 border-port-border hover:border-port-accent/40"
+ >
+ <GitCompare size={13} /> Impact preview
+ </button>
+
{/* Format switcher — span the full story in any of the three formats. */}
<div className="inline-flex rounded-lg border border-port-border overflow-hidden">
{MANUSCRIPT_TYPES.map((t) => {
@@ -388,7 +395,6 @@ export default function PipelineManuscriptEditor() {
})}
</div>
{switching ? <Loader2 size={14} className="animate-spin text-gray-500" /> : null}
- {/* Pin the viewed format as the source of truth (stored in the bible). */}
{viewType && viewType !== pinnedPrimary ? (
<button
type="button"
@@ -413,27 +419,38 @@ export default function PipelineManuscriptEditor() {
No drafted manuscript yet — write a comic script, prose, or teleplay on at least one issue, then run “Finish the draft” from the series arc.
</p>
) : (
- sections.map((section) => (
- <ManuscriptSection
- key={section.issueId}
- section={section}
- saveState={saveState[section.issueId]}
- onContentChange={(content) => setSectionContent(section.issueId, content)}
- onBlurSave={() => saveSection(section)}
- onRevert={(runId) => revertSection(section, runId)}
- registerRef={(el) => {
- if (el) sectionRefs.current.set(section.number, el);
- else sectionRefs.current.delete(section.number);
- }}
- />
- ))
+ sections.map((section) => {
+ const sectionComments = openCommentsByNumber.get(section.number) || EMPTY;
+ const common = {
+ key: section.issueId,
+ section,
+ comments: sectionComments,
+ spans: sectionSpans.get(section.issueId) || EMPTY,
+ saveState: saveState[section.issueId],
+ openCommentId,
+ onOpenComment: setOpenCommentId,
+ onCloseComment: () => setOpenCommentId(null),
+ onContentChange: (content) => setSectionContent(section.issueId, content),
+ onBlurSave: () => saveSection(section),
+ onRevert: (runId) => revertSection(section, runId),
+ registerRef: registerSectionRef(section.number),
+ commentCardProps,
+ };
+ return viewMode === 'live' ? (
+ <ManuscriptLiveSection {...common} />
+ ) : (
+ <AnnotatedManuscriptSection
+ {...common}
+ editing={editingIssueId === section.issueId}
+ onToggleEdit={() => setEditingIssueId((cur) => (cur === section.issueId ? null : section.issueId))}
+ />
+ );
+ })
)}
</section>
- {/* Comments sidebar */}
+ {/* Comments sidebar — provider override, review trigger, and the index. */}
<aside className="border-t lg:border-t-0 lg:border-l border-port-border bg-port-card/40 lg:overflow-y-auto p-3 space-y-3">
- {/* AI provider override + editorial-review trigger. The chosen provider
- feeds both the per-comment "Generate fix" and the review re-run. */}
<div className="border border-port-border rounded-lg bg-port-bg/40 p-2.5 space-y-2">
<label htmlFor="ms-provider-override" className="block text-[10px] uppercase tracking-wider text-gray-500">
AI provider — Generate fix &amp; Editorial review
@@ -462,9 +479,6 @@ export default function PipelineManuscriptEditor() {
</select>
) : null}
</div>
- {/* One-tap suggestion of the best installed local model for editorial
- work — only when a local provider is selected and the pick isn't
- already chosen. */}
{showEditorialPick ? (
<button
type="button"
@@ -487,9 +501,6 @@ export default function PipelineManuscriptEditor() {
{reviewing ? <Loader2 size={12} className="animate-spin" /> : <ClipboardCheck size={12} />}
{reviewing ? 'Running editorial review…' : 'Run editorial review'}
</button>
- {/* Re-run mode. Merge keeps every prior note as-is; fresh reconciles
- the open list against this run — open notes it no longer finds
- are auto-dismissed (accepted & dismissed are left untouched). */}
<label htmlFor="ms-fresh-review" className="flex items-start gap-1.5 text-[11px] text-gray-400 cursor-pointer">
<input
id="ms-fresh-review"
@@ -509,11 +520,6 @@ export default function PipelineManuscriptEditor() {
</label>
</div>
- <h2 className="text-xs uppercase tracking-wider text-gray-500 flex items-center justify-between">
- <span>Editorial comments</span>
- <span className="text-gray-600">{grouped.open.length} open</span>
- </h2>
-
{reviewMeta?.chunked ? (
<p
className="flex items-center gap-1.5 text-[11px] text-port-warning"
@@ -524,384 +530,22 @@ export default function PipelineManuscriptEditor() {
</p>
) : null}
- {comments.length === 0 ? (
- <p className="text-xs text-gray-500 italic">
- No comments yet. Run “Finish the draft” from the series arc to generate editorial feedback here.
- </p>
- ) : null}
-
- {grouped.open.map((comment) => (
- <CommentCard
- key={comment.id}
- comment={comment}
- seriesId={seriesId}
- providerOverride={providerOverride}
- modelOverride={modelOverride}
- onJump={jumpToComment}
- onCommentChange={updateCommentLocal}
- onAccepted={applyAccepted}
- draft={fixDrafts[comment.id]}
- onDraftChange={(entry) => setCommentDraft(comment.id, entry)}
- />
- ))}
-
- <ResolvedGroup label="Accepted" icon={Check} items={grouped.accepted} onJump={jumpToComment} />
- <ResolvedGroup label="Dismissed" icon={X} items={grouped.dismissed} onJump={jumpToComment} />
+ <ManuscriptCommentIndex
+ comments={comments}
+ locatedCommentIds={locatedCommentIds}
+ openCommentId={openCommentId}
+ onReveal={revealComment}
+ />
</aside>
</div>
- {/* Pinned overlay: the just-jumped-to comment, kept on screen over the
- manuscript so its context and actions travel with the scroll. */}
- {activeComment ? (
- <ActiveCommentOverlay
- comment={activeComment}
- seriesId={seriesId}
- providerOverride={providerOverride}
- modelOverride={modelOverride}
- onJump={jumpToComment}
- onCommentChange={updateCommentLocal}
- onAccepted={applyAccepted}
- draft={fixDrafts[activeComment.id]}
- onDraftChange={(entry) => setCommentDraft(activeComment.id, entry)}
- onClose={() => setActiveCommentId(null)}
- />
- ) : null}
- </div>
- );
-}
-
-// Floating, dismissable restatement of the comment the user just jumped to.
-// Anchored over the manuscript pane (bottom-left) — away from the right sidebar
-// and below the section that scrolled to the top — so the user can read/edit
-// the manuscript and act on the comment without losing either. Reuses
-// CommentCard with a distinct idScope so its form ids don't collide with the
-// sidebar's copy of the same open comment.
-function ActiveCommentOverlay({ comment, onClose, ...cardProps }) {
- // Esc closes the pinned card — matches the dismiss convention of the app's
- // other non-modal floating panels. (No click-outside: the overlay is meant to
- // stay open while the user clicks into the manuscript to edit.)
- useEffect(() => {
- const onKey = (e) => { if (e.key === 'Escape') onClose(); };
- window.addEventListener('keydown', onKey);
- return () => window.removeEventListener('keydown', onKey);
- }, [onClose]);
-
- return (
- <div
- role="dialog"
- aria-modal="false"
- aria-label="Editorial comment"
- className="fixed bottom-4 left-4 z-40 w-[min(440px,calc(100vw-2rem))] max-h-[70vh] overflow-y-auto rounded-lg border border-port-accent/40 bg-port-card shadow-2xl shadow-black/60"
- >
- <div className="sticky top-0 flex items-center justify-between gap-2 px-3 py-2 border-b border-port-border bg-port-bg/90 backdrop-blur">
- <span className="text-[11px] uppercase tracking-wider text-gray-400 inline-flex items-center gap-1.5">
- <CornerDownRight size={12} className="text-port-accent" /> Editorial comment
- </span>
- <button type="button" onClick={onClose} className="text-gray-500 hover:text-white" aria-label="Close pinned comment" title="Close pinned comment">
- <X size={14} />
- </button>
- </div>
- <div className="p-2.5">
- <CommentCard comment={comment} idScope={`overlay-${comment.id}`} {...cardProps} />
- </div>
- </div>
- );
-}
-
-// One issue's manuscript section: an auto-sized free-text editor plus a
-// collapsible version history with one-click revert.
-function ManuscriptSection({ section, saveState, onContentChange, onBlurSave, onRevert, registerRef }) {
- const [showVersions, setShowVersions] = useState(false);
- const [revertingId, setRevertingId] = useState(null);
- const versions = section.versions || [];
-
- const revert = async (runId) => {
- setRevertingId(runId);
- await onRevert(runId);
- setRevertingId(null);
- };
-
- return (
- <article className="space-y-1.5">
- <div className="flex items-center justify-between gap-2 sticky top-0 bg-port-bg/95 backdrop-blur py-1 z-10">
- <h2 className="text-sm font-semibold text-gray-200">
- Issue {section.number}{section.title ? ` — ${section.title}` : ''}
- <span className="ml-2 text-[10px] uppercase tracking-wider text-gray-500">{STAGE_LABEL[section.stageId] || section.stageId}</span>
- </h2>
- <div className="flex items-center gap-2">
- <SaveBadge state={saveState} />
- {versions.length > 0 ? (
- <button
- type="button"
- onClick={() => setShowVersions((v) => !v)}
- className="inline-flex items-center gap-1 text-[11px] text-gray-400 hover:text-white"
- title="Show prior saved versions"
- >
- <History size={12} /> {versions.length}
- </button>
- ) : null}
- </div>
- </div>
-
- {showVersions && versions.length > 0 ? (
- <div className="border border-port-border rounded bg-port-bg/40 p-2 space-y-1">
- <p className="text-[10px] uppercase tracking-wider text-gray-500">Version history (newest first)</p>
- {versions.map((v) => (
- <div key={v.runId} className="flex items-center justify-between gap-2 text-[11px]">
- <span className="text-gray-400">{v.createdAt ? timeAgo(v.createdAt) : v.runId}</span>
- <button
- type="button"
- onClick={() => revert(v.runId)}
- disabled={revertingId === v.runId}
- className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-gray-300 hover:text-white border border-port-border hover:border-port-accent/40 disabled:opacity-40"
- title="Revert this section to that version (reversible)"
- >
- {revertingId === v.runId ? <Loader2 size={11} className="animate-spin" /> : <RotateCcw size={11} />}
- Revert
- </button>
- </div>
- ))}
- </div>
- ) : null}
-
- <textarea
- ref={registerRef}
- value={section.content}
- onChange={(e) => onContentChange(e.target.value)}
- onBlur={onBlurSave}
- rows={rowsFor(section.content)}
- spellCheck
- className="w-full px-3 py-2 bg-port-card border border-port-border rounded text-sm text-gray-100 font-mono leading-relaxed resize-y focus:border-port-accent/50 focus:outline-none"
+ <ManuscriptImpactPreview
+ open={showImpact}
+ onClose={() => setShowImpact(false)}
+ sections={sections}
+ comments={comments.filter((c) => c.status === 'open' && c.fix)}
+ fixDrafts={fixDrafts}
/>
- </article>
- );
-}
-
-function SaveBadge({ state }) {
- if (state === 'saving') return <span className="text-[10px] text-gray-500 inline-flex items-center gap-1"><Loader2 size={10} className="animate-spin" /> saving</span>;
- if (state === 'saved') return <span className="text-[10px] text-port-success">saved</span>;
- return null;
-}
-
-function Badge({ comment }) {
- return (
- <span className="flex items-center gap-1.5">
- <span className={`text-[10px] px-1.5 py-0.5 rounded border ${SEVERITY_TONE[comment.severity] || SEVERITY_TONE.low}`}>
- {comment.severity}
- </span>
- <span className="text-[10px] uppercase tracking-wider text-gray-500">{CATEGORY_LABEL[comment.category] || comment.category}</span>
- </span>
- );
-}
-
-function CommentCard({ comment, seriesId, providerOverride, modelOverride, onJump, onCommentChange, onAccepted, idScope, draft, onDraftChange }) {
- // Namespace form ids so the overlay's copy of an open comment doesn't collide
- // with the sidebar's (duplicate ids break label/htmlFor association).
- const scope = idScope || comment.id;
- const hasFix = !!comment.fix;
- const fixEdits = useMemo(() => {
- if (Array.isArray(comment.fix?.edits) && comment.fix.edits.length) return comment.fix.edits;
- if (comment.fix?.find || comment.fix?.replace) {
- return [{
- issueNumber: comment.issueNumber,
- issueId: comment.issueId,
- stageId: comment.stageId,
- find: comment.fix.find || '',
- replace: comment.fix.replace || '',
- fuzzy: comment.fix.fuzzy,
- }];
- }
- return [];
- }, [comment.fix, comment.issueId, comment.issueNumber, comment.stageId]);
- const fixKey = useMemo(
- () => fixEdits.map((e, i) => `${i}:${e.issueId || ''}:${e.stageId || ''}:${e.find}:${e.replace}`).join('\n---\n'),
- [fixEdits],
- );
- // Draft state is owned by the parent (keyed by comment id) and shared with the
- // overlay copy of this comment. Use the stored entry only when it was derived
- // from the current fix; a (re)generated fix has a new fixKey, so stale drafts
- // fall back to fresh defaults (every edit checked, replacement prefilled).
- const stored = draft && draft.fixKey === fixKey ? draft : null;
- const editDrafts = stored ? stored.drafts : Object.fromEntries(fixEdits.map((e, i) => [i, e.replace || '']));
- const selectedEdits = stored ? stored.selected : Object.fromEntries(fixEdits.map((_, i) => [i, true]));
- const setEditDrafts = (updater) =>
- onDraftChange({ fixKey, drafts: typeof updater === 'function' ? updater(editDrafts) : updater, selected: selectedEdits });
- const setSelectedEdits = (updater) =>
- onDraftChange({ fixKey, drafts: editDrafts, selected: typeof updater === 'function' ? updater(selectedEdits) : updater });
-
- const [runGenerate, generating] = useAsyncAction(
- () => generatePipelineManuscriptFix(seriesId, comment.id, { providerOverride, modelOverride }),
- { errorMessage: 'Failed to generate fix' },
- );
- const [runAccept, accepting] = useAsyncAction(
- (selected) => acceptPipelineManuscriptFix(seriesId, comment.id, { edits: selected }),
- { errorMessage: 'Failed to apply fix' },
- );
-
- const generate = async () => {
- const result = await runGenerate();
- if (!result) return;
- // The regenerated fix flows in via onCommentChange → comment.fix → a new
- // fixKey, so the drafts above auto-reset to the new fix's defaults; no need
- // to set them here.
- if (result.comment) onCommentChange(result.comment);
- if (result.fix?.fuzzy) toast('The suggested anchor was not found verbatim — edit the manuscript directly, or adjust the replacement.');
- };
-
- const accept = async () => {
- if (!comment.fix) return;
- const selected = fixEdits
- .map((edit, i) => ({ ...edit, replace: editDrafts[i] ?? edit.replace ?? '' }))
- .filter((_, i) => selectedEdits[i]);
- if (selected.length === 0) {
- toast('Select at least one suggested edit to apply');
- return;
- }
- const result = await runAccept(selected);
- if (!result) return;
- onAccepted(result);
- toast.success(selected.length === 1 ? 'Fix applied to the manuscript' : `${selected.length} fixes applied to the manuscript`);
- };
-
- const dismiss = async () => {
- const result = await patchPipelineManuscriptComment(seriesId, comment.id, { status: 'dismissed' }, { silent: true })
- .catch((err) => { toast.error(err.message || 'Failed to dismiss'); return null; });
- if (result?.comment) onCommentChange(result.comment);
- };
-
- const fuzzy = comment.fix?.fuzzy || fixEdits.some((e) => e.fuzzy);
-
- return (
- <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} />
- <button
- type="button"
- onClick={() => onJump(comment)}
- className="text-[11px] text-port-accent hover:underline inline-flex items-center gap-1"
- title="Jump to this spot in the manuscript"
- >
- <CornerDownRight size={11} />
- {comment.issueNumber != null ? `Issue ${comment.issueNumber}` : 'Jump'}
- </button>
- </div>
-
- <p className="text-xs text-gray-200">{comment.problem}</p>
- {comment.suggestion ? <p className="text-[11px] text-gray-400"><span className="text-gray-500">Fix: </span>{comment.suggestion}</p> : null}
- {comment.anchorQuote ? <p className="text-[11px] text-gray-500 italic line-clamp-2">“{comment.anchorQuote}”</p> : null}
-
- {hasFix ? (
- <div className="space-y-1.5">
- <p className="text-[10px] uppercase tracking-wider text-gray-500">
- Suggested {fixEdits.length === 1 ? 'edit' : `${fixEdits.length} edits`}
- </p>
- {fixEdits.map((edit, i) => {
- const draft = editDrafts[i] ?? edit.replace ?? '';
- const checked = selectedEdits[i] !== false;
- const label = edit.issueNumber != null ? `Issue ${edit.issueNumber}` : 'Manuscript';
- return (
- <div key={`${i}-${edit.issueId || ''}-${edit.find}`} className="border border-port-border rounded bg-port-card/60 overflow-hidden">
- <label className="flex items-center gap-2 px-2 py-1.5 border-b border-port-border text-[11px] text-gray-300">
- <input
- type="checkbox"
- checked={checked}
- onChange={(e) => setSelectedEdits((prev) => ({ ...prev, [i]: e.target.checked }))}
- className="accent-port-accent"
- />
- <span className="font-medium">{label}{edit.title ? ` — ${edit.title}` : ''}</span>
- {edit.fuzzy ? <span className="ml-auto text-port-warning">fuzzy</span> : null}
- </label>
- {edit.note ? <p className="px-2 pt-1.5 text-[11px] text-gray-500">{edit.note}</p> : null}
- <InlineDiff oldText={edit.find || ''} newText={draft} emptyLabel="No replacement changes." />
- <label htmlFor={`fix-replace-${scope}-${i}`} className="block px-2 pt-1.5 text-[10px] uppercase tracking-wider text-gray-500">Replacement (editable)</label>
- <textarea
- id={`fix-replace-${scope}-${i}`}
- value={draft}
- onChange={(e) => setEditDrafts((prev) => ({ ...prev, [i]: e.target.value }))}
- rows={Math.min(14, Math.max(3, draft.split('\n').length + 1))}
- className="m-2 mt-1 w-[calc(100%-1rem)] px-2 py-1.5 bg-port-bg border border-port-border rounded text-[12px] text-gray-100 font-mono resize-y focus:border-port-accent/50 focus:outline-none"
- />
- </div>
- );
- })}
- {fuzzy ? (
- <p className="text-[10px] text-port-warning">Anchor not found verbatim — accepting may fail; edit the manuscript directly if so.</p>
- ) : null}
- </div>
- ) : null}
-
- <div className="flex items-center gap-2 pt-0.5">
- {!hasFix ? (
- <button
- type="button"
- onClick={generate}
- disabled={generating}
- className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded text-[12px] font-medium border bg-port-bg text-port-accent border-port-border hover:border-port-accent/40 disabled:opacity-40"
- >
- {generating ? <Loader2 size={12} className="animate-spin" /> : <Sparkles size={12} />}
- Generate fix
- </button>
- ) : (
- <>
- <button
- type="button"
- onClick={accept}
- disabled={accepting || !fixEdits.some((_, i) => selectedEdits[i] && (editDrafts[i] || '').trim())}
- className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded text-[12px] font-medium bg-port-success/20 text-port-success border border-port-success/40 hover:bg-port-success/30 disabled:opacity-40"
- >
- {accepting ? <Loader2 size={12} className="animate-spin" /> : <Check size={12} />}
- Accept
- </button>
- <button
- type="button"
- onClick={generate}
- disabled={generating || accepting}
- className="inline-flex items-center gap-1 px-2 py-1 rounded text-[12px] text-gray-400 hover:text-white disabled:opacity-40"
- title="Regenerate the suggested fix"
- >
- {generating ? <Loader2 size={12} className="animate-spin" /> : <Sparkles size={12} />}
- </button>
- </>
- )}
- <button
- type="button"
- onClick={dismiss}
- className="ml-auto inline-flex items-center gap-1 px-2 py-1 rounded text-[12px] text-gray-500 hover:text-white"
- >
- <X size={12} /> Dismiss
- </button>
- </div>
- </div>
- );
-}
-
-function ResolvedGroup({ label, icon: Icon, items, onJump }) {
- const [open, setOpen] = useState(false);
- if (items.length === 0) return null;
- return (
- <div className="pt-1">
- <button
- type="button"
- onClick={() => setOpen((o) => !o)}
- className="w-full flex items-center gap-1.5 text-[11px] uppercase tracking-wider text-gray-500 hover:text-gray-300"
- >
- {open ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
- <Icon size={12} /> {label} ({items.length})
- </button>
- {open ? (
- <div className="mt-1.5 space-y-1.5">
- {items.map((c) => (
- <button
- key={c.id}
- type="button"
- onClick={() => onJump(c)}
- className="block w-full text-left border border-port-border rounded p-2 bg-port-bg/30 hover:border-port-accent/30"
- >
- <span className="text-[11px] text-gray-400 line-clamp-2">{c.problem}</span>
- </button>
- ))}
- </div>
- ) : null}
</div>
);
}
diff --git a/client/src/pages/PipelineManuscriptEditor.test.jsx b/client/src/pages/PipelineManuscriptEditor.test.jsx
index b329a2c47f..5f41d8de3e 100644
--- a/client/src/pages/PipelineManuscriptEditor.test.jsx
+++ b/client/src/pages/PipelineManuscriptEditor.test.jsx
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { render, screen, waitFor, fireEvent, within } from '@testing-library/react';
+import { render, screen, waitFor, fireEvent } from '@testing-library/react';
import { MemoryRouter, Routes, Route } from 'react-router-dom';
const api = vi.hoisted(() => ({
@@ -36,8 +36,12 @@ const renderEditor = () => render(
</MemoryRouter>,
);
+// Reveal a comment in context by clicking its sidebar index row.
+const revealFromIndex = (problem) => fireEvent.click(screen.getByText(problem));
+
beforeEach(() => {
vi.clearAllMocks();
+ window.localStorage.clear(); // default to Live mode
api.getPipelineSeries.mockResolvedValue({ id: 'ser-1', name: 'My Series', primaryManuscriptType: 'prose' });
api.getPipelineManuscript.mockResolvedValue({
sections: [{ issueId: 'iss-1', number: 1, title: 'One', stageId: 'prose', content: 'The hero walked in. She left.' }],
@@ -55,7 +59,7 @@ beforeEach(() => {
});
describe('PipelineManuscriptEditor', () => {
- it('renders the manuscript section and an open editorial comment', async () => {
+ it('renders the manuscript section and an open editorial comment in the index', async () => {
renderEditor();
expect(await screen.findByText('My Series')).toBeInTheDocument();
expect(screen.getByText('The ending is abrupt')).toBeInTheDocument();
@@ -63,68 +67,32 @@ describe('PipelineManuscriptEditor', () => {
expect(screen.getByText(/1 open/)).toBeInTheDocument();
});
- it('pins the clicked comment in a dismissable overlay so its context survives the jump', async () => {
+ it('reveals a comment in-context (Live mode) when its index row is clicked, and closes it', async () => {
renderEditor();
await screen.findByText('My Series');
- // Initially only the sidebar card exists.
- expect(screen.getByText('The ending is abrupt')).toBeInTheDocument();
- expect(screen.queryByRole('dialog', { name: 'Editorial comment' })).not.toBeInTheDocument();
+ // Initially only the sidebar index row references the comment.
+ expect(screen.getAllByText('The ending is abrupt')).toHaveLength(1);
- // Clicking Jump pins it as a floating overlay (problem text now appears twice).
- fireEvent.click(screen.getByTitle('Jump to this spot in the manuscript'));
- const overlay = await screen.findByRole('dialog', { name: 'Editorial comment' });
- expect(overlay).toBeInTheDocument();
- expect(screen.getAllByText('The ending is abrupt').length).toBe(2);
+ revealFromIndex('The ending is abrupt');
+ // Now an in-context note card also shows the problem text → two instances.
+ await waitFor(() => expect(screen.getAllByText('The ending is abrupt')).toHaveLength(2));
- // Closing the overlay leaves the sidebar card intact.
- fireEvent.click(screen.getByTitle('Close pinned comment'));
- await waitFor(() => expect(screen.queryByRole('dialog', { name: 'Editorial comment' })).not.toBeInTheDocument());
- expect(screen.getByText('The ending is abrupt')).toBeInTheDocument();
+ // Closing the in-context note leaves the sidebar index intact.
+ fireEvent.click(screen.getByLabelText('Close note'));
+ await waitFor(() => expect(screen.getAllByText('The ending is abrupt')).toHaveLength(1));
});
- it('dismisses the pinned overlay on Escape', async () => {
+ it('closes the in-context note on Escape', async () => {
renderEditor();
await screen.findByText('My Series');
-
- fireEvent.click(screen.getByTitle('Jump to this spot in the manuscript'));
- await screen.findByRole('dialog', { name: 'Editorial comment' });
-
+ revealFromIndex('The ending is abrupt');
+ await waitFor(() => expect(screen.getAllByText('The ending is abrupt')).toHaveLength(2));
fireEvent.keyDown(window, { key: 'Escape' });
- await waitFor(() => expect(screen.queryByRole('dialog', { name: 'Editorial comment' })).not.toBeInTheDocument());
+ await waitFor(() => expect(screen.getAllByText('The ending is abrupt')).toHaveLength(1));
});
- it('preserves an in-progress fix edit made in the sidebar when accepting from the pinned overlay', async () => {
- api.generatePipelineManuscriptFix.mockResolvedValue({
- fix: { find: 'She left.', replace: 'She left, but paused.' },
- comment: { ...comment, fix: { find: 'She left.', replace: 'She left, but paused.' } },
- });
- api.acceptPipelineManuscriptFix.mockResolvedValue({
- comment: { ...comment, status: 'accepted', fix: { find: 'She left.', replace: 'edited in sidebar.' } },
- section: { issueId: 'iss-1', number: 1, title: 'One', stageId: 'prose', content: 'The hero walked in. edited in sidebar.' },
- });
-
- renderEditor();
- await screen.findByText('My Series');
-
- // Generate a fix, then edit the replacement text in the sidebar card.
- fireEvent.click(screen.getByText('Generate fix'));
- const sidebarReplace = await screen.findByDisplayValue('She left, but paused.');
- fireEvent.change(sidebarReplace, { target: { value: 'edited in sidebar.' } });
-
- // Now jump → the overlay mounts a second card; it must carry the edit.
- fireEvent.click(screen.getByTitle('Jump to this spot in the manuscript'));
- const overlay = await screen.findByRole('dialog', { name: 'Editorial comment' });
- expect(within(overlay).getByDisplayValue('edited in sidebar.')).toBeInTheDocument();
-
- // Accept from the overlay applies the edited replacement, not the original.
- fireEvent.click(within(overlay).getByText('Accept'));
- await waitFor(() => expect(api.acceptPipelineManuscriptFix).toHaveBeenCalledWith('ser-1', 'mrc-1', {
- edits: [{ issueNumber: 1, issueId: 'iss-1', stageId: 'prose', find: 'She left.', replace: 'edited in sidebar.', fuzzy: undefined }],
- }));
- });
-
- it('closes the pinned overlay automatically when its comment is accepted', async () => {
+ it('generates a fix, then accepts it — moving the comment to Accepted and updating the section', async () => {
api.generatePipelineManuscriptFix.mockResolvedValue({
fix: { find: 'She left.', replace: 'She left, but paused.' },
comment: { ...comment, fix: { find: 'She left.', replace: 'She left, but paused.' } },
@@ -136,39 +104,14 @@ describe('PipelineManuscriptEditor', () => {
renderEditor();
await screen.findByText('My Series');
+ revealFromIndex('The ending is abrupt');
- fireEvent.click(screen.getByTitle('Jump to this spot in the manuscript'));
- const overlay = await screen.findByRole('dialog', { name: 'Editorial comment' });
-
- // Act on the comment from inside the overlay.
- fireEvent.click(within(overlay).getByText('Generate fix'));
- fireEvent.click(await within(overlay).findByText('Accept'));
-
- // Accepting flips status → the overlay vanishes on its own.
- await waitFor(() => expect(screen.queryByRole('dialog', { name: 'Editorial comment' })).not.toBeInTheDocument());
- await waitFor(() => expect(screen.getByText(/0 open/)).toBeInTheDocument());
- });
-
- it('generates a fix, then accepts it — moving the comment to Accepted and updating the section', async () => {
- api.generatePipelineManuscriptFix.mockResolvedValue({
- fix: { find: 'She left.', replace: 'She left, but paused.' },
- comment: { ...comment, fix: { find: 'She left.', replace: 'She left, but paused.' } },
- });
- api.acceptPipelineManuscriptFix.mockResolvedValue({
- comment: { ...comment, status: 'accepted', fix: { find: 'She left.', replace: 'She left, but paused.' } },
- section: { issueId: 'iss-1', number: 1, title: 'One', stageId: 'prose', content: 'The hero walked in. She left, but paused.' },
- });
-
- renderEditor();
fireEvent.click(await screen.findByText('Generate fix'));
-
- // The editable replacement appears.
expect(await screen.findByDisplayValue('She left, but paused.')).toBeInTheDocument();
expect(api.generatePipelineManuscriptFix).toHaveBeenCalledWith('ser-1', 'mrc-1', expect.any(Object));
fireEvent.click(screen.getByText('Accept'));
- // Section text updates and the open count drops to 0.
expect(await screen.findByDisplayValue('The hero walked in. She left, but paused.')).toBeInTheDocument();
await waitFor(() => expect(screen.getByText(/0 open/)).toBeInTheDocument());
expect(api.acceptPipelineManuscriptFix).toHaveBeenCalledWith('ser-1', 'mrc-1', {
@@ -201,11 +144,9 @@ describe('PipelineManuscriptEditor', () => {
renderEditor();
const ta = await screen.findByDisplayValue('The hero walked in. She left.');
- // No-op blur (unchanged) must not save.
fireEvent.blur(ta);
expect(api.savePipelineManuscriptSection).not.toHaveBeenCalled();
- // Changed blur saves with the versioned section endpoint.
fireEvent.change(ta, { target: { value: 'The hero walked in. She stayed.' } });
fireEvent.blur(ta);
await waitFor(() => expect(api.savePipelineManuscriptSection).toHaveBeenCalledWith(
@@ -214,10 +155,30 @@ describe('PipelineManuscriptEditor', () => {
{ stageId: 'prose', output: 'The hero walked in. She stayed.' },
{ silent: true },
));
- // Version history surfaces after the save.
expect(await screen.findByTitle('Show prior saved versions')).toBeInTheDocument();
});
+ it('Review mode renders annotated prose with an Edit toggle that swaps in the textarea', async () => {
+ renderEditor();
+ await screen.findByText('My Series');
+
+ fireEvent.click(screen.getByRole('button', { name: /Review/ }));
+ // Read-only prose: the section textarea is gone, the anchor is a highlight.
+ await waitFor(() => expect(screen.queryByDisplayValue('The hero walked in. She left.')).not.toBeInTheDocument());
+ expect(screen.getByTitle('Open editorial note')).toBeInTheDocument();
+
+ // Edit toggle brings back the editable textarea.
+ fireEvent.click(screen.getByRole('button', { name: /Edit/ }));
+ expect(await screen.findByDisplayValue('The hero walked in. She left.')).toBeInTheDocument();
+ });
+
+ it('opens the whole-manuscript impact preview modal', async () => {
+ renderEditor();
+ await screen.findByText('My Series');
+ fireEvent.click(screen.getByText('Impact preview'));
+ expect(await screen.findByRole('dialog', { name: 'Manuscript impact preview' })).toBeInTheDocument();
+ });
+
it('routes Generate fix through the selected provider/model override', async () => {
api.generatePipelineManuscriptFix.mockResolvedValue({
fix: { find: 'She left.', replace: 'She left, but paused.' },
@@ -226,14 +187,13 @@ describe('PipelineManuscriptEditor', () => {
renderEditor();
await screen.findByText('My Series');
- // Only enabled providers populate the selector.
const providerSelect = screen.getByLabelText(/AI provider/i);
expect(screen.queryByRole('option', { name: 'Disabled' })).not.toBeInTheDocument();
fireEvent.change(providerSelect, { target: { value: 'anthropic' } });
- // Model defaults to the provider's defaultModel; switch it explicitly.
fireEvent.change(screen.getByLabelText('Model'), { target: { value: 'claude-haiku' } });
- fireEvent.click(screen.getByText('Generate fix'));
+ revealFromIndex('The ending is abrupt');
+ fireEvent.click(await screen.findByText('Generate fix'));
await waitFor(() => expect(api.generatePipelineManuscriptFix).toHaveBeenCalledWith(
'ser-1', 'mrc-1', { providerOverride: 'anthropic', modelOverride: 'claude-haiku' },
));
diff --git a/docs/plans/2026-06-06-manuscript-editor-inline-feedback.md b/docs/plans/2026-06-06-manuscript-editor-inline-feedback.md
new file mode 100644
index 0000000000..85442b8535
--- /dev/null
+++ b/docs/plans/2026-06-06-manuscript-editor-inline-feedback.md
@@ -0,0 +1,196 @@
+# Re-imagine the Manuscript Editor — in-context editorial feedback
+
+## Context
+
+The Manuscript editor (`/pipeline/series/:seriesId/manuscript`) makes the "Finish the
+draft" editorial pass actionable. Today it's a two-pane layout: the manuscript on the
+left (one plain `<textarea>` per issue) and a 380px sidebar on the right holding every
+editorial comment, plus a floating overlay when you jump to one. The user's complaint:
+**all the feedback lives in the sidebar, you scroll a lot, and you read each note out of
+context.** They want feedback **integrated into the text itself, Grammarly-style** —
+inline highlighted/underlined spans with helpful hints, expandable info beside the text,
+a clear **side-by-side diff** for reviewing an edit, and a way to see **how accepted edits
+change the whole manuscript** (per-card diffs don't convey cumulative impact).
+
+Decisions from the user:
+- **Grammarly-style inline hints** are the target feel: text stays editable, anchored
+ feedback shows as colored underlines, clicking one pops a small card with the
+ suggestion + actions.
+- Unsure between "always-editable" and "read-then-edit" — **wants a toggle to try both.**
+- **Diff:** side-by-side (old | new columns) is the default; keep today's stacked inline
+ diff as a compact toggle.
+- **Impact preview:** a full-screen modal showing before/after for the changed sections.
+
+## What exists today (reuse, don't rebuild)
+
+- `client/src/pages/PipelineManuscriptEditor.jsx` — the whole page (sections, sidebar,
+ `CommentCard`, `ManuscriptSection`, `ActiveCommentOverlay`, generate/accept/dismiss,
+ `fixDrafts` state lifted to the page, version history/revert).
+- Comments anchor to text by **verbatim substring** (`anchorQuote`), not offsets.
+ `jumpToComment` does `textarea.value.indexOf(anchorQuote)`. Server `locateFind`
+ (`server/services/pipeline/manuscriptFix.js:153`) disambiguates recurring matches by
+ picking the occurrence nearest the anchor — we mirror this client-side.
+- `client/src/components/ui/InlineDiff.jsx` — word-level Myers LCS, stacked old/new rows,
+ 4M-cell cap with a both-versions fallback. **The only diff component.**
+- Generate (`POST …/fix`), accept (`POST …/accept`, returns rewritten sections), save
+ (`PUT …/sections/:issueId`), revert — all work. **No server changes needed.**
+- Section auto-grows to fit content (`rowsFor`, cap 400 rows) → for typical sections
+ there's no internal textarea scroll, which makes a highlight overlay tractable.
+
+## Approach: two viewing modes behind a header toggle
+
+A persisted (localStorage) **mode toggle** in the editor header lets the user try both
+editing models the user was torn between. Both modes share one anchor-location lib, one
+comment card, and one diff component — only the manuscript surface differs.
+
+### Mode 1 — "Live" (Grammarly, default)
+Each section is the **existing editable `<textarea>`** with a **backdrop highlight layer**
+behind it (the established react-highlight-within-textarea technique):
+- A backdrop `<div>` is absolutely positioned over the textarea with **identical** box
+ metrics (font, line-height, padding, `white-space: pre-wrap`, `word-break`, width). Its
+ text is `color: transparent`; anchored spans render as `<mark>` with a severity-toned
+ **wavy/solid `border-bottom`** (the Grammarly underline). The textarea sits on top with
+ a transparent background, so its real text + caret show over the backdrop's underlines —
+ and because layout is identical, each underline sits exactly under its words.
+- Sections auto-grow to content, so no scroll-sync in the common case; if a section
+ exceeds the 400-row cap, sync `backdrop.scrollTop = textarea.scrollTop`.
+- **Click-to-open without pointer-event juggling:** on textarea click, read
+ `selectionStart`, find which anchor span covers that index, and open that comment's
+ **popover** anchored to the corresponding backdrop `<mark>`'s `getBoundingClientRect()`.
+ The popover is a compact `ManuscriptCommentCard` (problem + suggestion + side-by-side
+ diff + Generate/Accept/Dismiss). `Esc` closes it.
+- A subtle gutter/inline **hint chip** ("3 notes") per section gives a non-click way in
+ and a count, and keeps discoverability for touch.
+
+### Mode 2 — "Review" (read-then-edit)
+Default to a **read-only annotated prose `<div>`** (highlights painted directly as
+`<mark>`s + a margin pin rail aligned to each highlight); click a highlight/pin to expand
+the same card inline beneath the paragraph; an **Edit** affordance (or clicking into the
+prose) swaps that one section to the textarea, blur saves and re-annotates. Best for a
+focused, whole-page editorial sweep and as the **safe fallback** if Live-mode overlay
+alignment proves fiddly on some fonts.
+
+Both modes: the **sidebar becomes a navigable index/filter** (severity / category /
+open|accepted|dismissed chips + counts) rather than the reading surface. A row click
+scrolls to the section and opens that comment's popover/card. The old
+`ActiveCommentOverlay` is removed — the in-context card supersedes it.
+
+## New pure helpers — `client/src/lib/` (barrel + README rows + colocated tests required)
+
+Per the module-organization rule, each is added to `client/src/lib/index.js`, gets a row
+in `client/src/lib/README.md`, and has a `*.test.js`.
+
+1. **`diffWords.js`** — extract the `lcs` + tokenization + `DIFF_CELL_CAP` core out of
+ `InlineDiff.jsx`. `diffWords(oldText, newText) → { tooLarge, oldRuns, newRuns }`
+ (runs = `[{ text, changed }]`). Both `InlineDiff` and the new `SideBySideDiff` consume
+ it — removes duplication of the LCS core.
+2. **`manuscriptAnchors.js`** — `locateAnchors(content, comments)` → `[{ commentId,
+ severity, start, end }]` for comments whose `anchorQuote` is found, reusing the
+ **nearest-occurrence** disambiguation from server `locateFind` (header notes the
+ mirror). `buildHighlightSegments(content, spans)` → flatten overlapping/recurring spans
+ into ordered non-overlapping segments `[{ text, commentIds[], topSeverity }]`.
+3. **`applyManuscriptEdits.js`** — `applyEditsToContent(content, edits, anchorQuote)`:
+ client mirror of the server splice (locate each `find`, replace in descending order,
+ skip overlaps) for the **preview only** (server stays authoritative). Shares one
+ `locateFind` copy with `manuscriptAnchors.js`.
+
+## New components — `client/src/components/`
+
+- `ui/SideBySideDiff.jsx` — two-column old|new diff built on `diffWords`; respects
+ `tooLarge` with the same fallback as `InlineDiff`. `+ SideBySideDiff.test.jsx`.
+- `pipeline/manuscript/ManuscriptCommentCard.jsx` — **lift the existing `CommentCard`
+ out of the page unchanged in logic** (it already takes `idScope` + lifted
+ `draft`/`onDraftChange`, so the sidebar row, the inline popover, and the impact list can
+ all share one edit state). Add a diff-style toggle (side-by-side default ⇄ stacked
+ inline). `idScope` of `live-…`/`review-…` avoids `htmlFor` collisions.
+- `pipeline/manuscript/ManuscriptLiveSection.jsx` — Mode 1: textarea + backdrop overlay +
+ click→popover. Keeps `registerRef` so sidebar jump-to still focuses the textarea.
+- `pipeline/manuscript/ManuscriptHighlightedProse.jsx` + `AnnotatedManuscriptSection.jsx`
+ — Mode 2: read-only `<mark>` prose + pin rail + click-to-expand + edit toggle.
+- `pipeline/manuscript/ManuscriptImpactPreview.jsx` — full-screen `Modal`
+ (reuse `client/src/components/ui/Modal.jsx`) that runs `applyEditsToContent` per
+ **changed** section, renders a `SideBySideDiff` per section (per-section, not one giant
+ diff, so the cap isn't tripped), header summarizing "N edits · M issues". Toggle:
+ changed-only ⇄ whole manuscript.
+
+## Changes to `PipelineManuscriptEditor.jsx`
+
+- Refactor: move `CommentCard` → `ManuscriptCommentCard.jsx`; remove `ManuscriptSection`
+ + `ActiveCommentOverlay` (replaced by the two mode components + inline popover).
+- State: add `viewMode` ('live'|'review', persisted), `openCommentId` (popover/inline),
+ `editingIssueId` (review-mode textarea). Keep `fixDrafts`/`setCommentDraft` (now shared
+ by sidebar + popover + preview). Remove `activeCommentId`.
+- Memo grouping comments by issue, gated on `stageId === viewType` for anchoring (mirrors
+ the existing `applyAccepted` cross-stage guard — comments targeting an off-screen format
+ stay index-only).
+- `jumpToComment` → "reveal in context": scroll section into view + open its
+ popover/card (keep `setSelectionRange` when a section is already in edit mode).
+- Header: mode toggle + an **"Impact preview"** button (opens the modal with open
+ comments that have generated fixes and their selected edits from `fixDrafts`).
+- `applyAccepted` unchanged — after accept the comment flips to `accepted`, its highlight
+ drops, anchors recompute.
+
+## Server
+
+**None.** Anchoring, generate, accept (returns rewritten sections), save, revert all
+exist. Impact preview computes from data already on the page. (A future
+`POST …/review/preview` for server-authoritative preview is explicitly out of scope.)
+
+## Phasing
+
+1. **Diff core + side-by-side** — extract `diffWords.js`, refactor `InlineDiff` onto it
+ (output identical), add `SideBySideDiff`. Independently shippable.
+2. **Live mode** — `manuscriptAnchors.js`, `ManuscriptLiveSection`, lift
+ `ManuscriptCommentCard`, click→popover; wire the mode toggle (Live default).
+3. **Review mode** — `ManuscriptHighlightedProse` + `AnnotatedManuscriptSection`; the
+ sidebar becomes index/filter; remove `ActiveCommentOverlay`.
+4. **Impact preview** — `applyManuscriptEdits.js` + `ManuscriptImpactPreview` + button.
+
+## Risks & mitigations
+
+- **Overlay alignment (Live mode):** backdrop and textarea must share exact typography;
+ any drift desyncs underlines. Mitigate by deriving both from one shared className and
+ testing serif (prose) + mono (script) stages. Review mode is the fallback if a font
+ refuses to align.
+- **Anchor not found / fuzzy:** `anchorQuote` may not match verbatim (edited since review,
+ or server flagged `fuzzy`). `locateAnchors` yields no highlight; the comment still lists
+ in the sidebar with the existing "anchor not found" warning. Surface a "X of Y notes
+ located in text" count so the divergence is explicit, not silent.
+- **Overlapping / recurring anchors:** `buildHighlightSegments` flattens to non-overlapping
+ segments carrying a `commentIds` set; a multi-comment span opens a chooser or the
+ highest-severity card. Recurring quotes resolve to the single nearest-anchor occurrence
+ (matches where accept lands).
+- **Performance / diff cap:** segmentation is O(content) per section, memoized. Impact
+ preview diffs **per changed section**, never one concatenation, so `DIFF_CELL_CAP` isn't
+ tripped; keep `<mark>`s to open comments only.
+- **Mobile (<640px):** sidebar already collapses below `lg`. Pins collapse to inline
+ badges, popover becomes a bottom sheet, impact modal goes full-screen; verify no
+ horizontal overflow with `resize-y`.
+- **Accessibility:** marks/pins are real `<button>`s with `aria-expanded`/`aria-controls`
+ → card id and a severity/category `aria-label`; `Esc` closes and returns focus; don't
+ rely on underline color alone (keep the text severity label). Edit toggle is a real
+ button, not click-anywhere only.
+
+## Verification
+
+- `npm run dev` (client `:5554`, API `:5555`). Open
+ `/pipeline/series/:seriesId/manuscript` for a series with generated editorial comments.
+- **Live mode:** anchored notes show severity-toned underlines under the right words;
+ clicking text on an underline opens the popover at that spot; Generate/Accept/Dismiss
+ work and the underline updates after accept; typing still saves on blur
+ (`PUT …/sections/:issueId` in the Network tab); an un-findable anchor shows no underline
+ but still lists in the sidebar.
+- **Review mode:** toggle modes; highlights + aligned pins render; expand card inline;
+ Edit toggle → textarea → blur saves → re-annotates; version history/revert still work.
+- **Diff:** card defaults to side-by-side, toggles to stacked inline, identical word-level
+ changes; force the `tooLarge` fallback with a large edit.
+- **Impact preview:** with several fixes selected, open the modal; before/after spans the
+ changed sections and matches what accept produces (accept one, reopen, it drops out).
+- **Sidebar index:** severity/category/status filters; row click scrolls + opens the card.
+- **Mobile:** below 640px — sidebar collapses, pins inline, popover bottom-sheet, modal
+ full-screen, no horizontal scroll.
+- **Unit tests:** `diffWords.test.js`, `manuscriptAnchors.test.js` (not-found / recurring
+ / overlapping), `applyManuscriptEdits.test.js` (descending-splice + overlap rejection vs
+ server `planEditsBySection` expectations), `SideBySideDiff.test.jsx`; run the existing
+ `InlineDiff.test.jsx` to confirm the core extraction is behavior-preserving.
+- After the feature lands, run `/simplify` on the diff, then commit + push.