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

add a Format button that cleans up pasted-PDF artifacts in the manuscript editor

[._.]/ Adam Eivy5976e0c049ab
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 956916b0cb..8166afad01 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -4,6 +4,8 @@
- **Video LoRAs now fuse on the bf16 LTX-2.3 Unified Beta (mlx_video runtime), not just dgrauet** — Previously a video LoRA like `ltx2.3-audio-reactive-lora` only worked on the dgrauet `ltx2` runtime; selecting the higher-quality **LTX-2.3 Unified Beta** (notapalindrome's `mlx_video` runtime) silently hid the LoRA picker. The stock `mlx_video.generate_av` CLI has no `--lora` flag, but the `mlx-video-with-audio` package ships an LTX-aware LoRA subsystem (`mlx_video.lora`) that's simply never called from the AV generator. A new wrapper (`scripts/generate_av_lora.py`) closes that gap without reimplementing the ~1000-line generation loop: it loads the user LoRAs, monkeypatches generate_av's two transformer-weight load seams to merge the LoRA deltas into the transformer (bf16, `quantization_bits=0`), then runs generate_av's own `main()` — so the SSE progress protocol is byte-for-byte identical to the non-LoRA path. The VideoGen picker now appears for non-quantized LTX-2.x `mlx_video` models too (gated by `isMlxVideoLtxLoraCapable`); if a LoRA's keys don't match the model the render fails loudly rather than silently producing a base video. Scoped to bf16 — the quantized Distilled Q4/Q8 variants stay on the dgrauet path for now and show an inline hint pointing at the supported models. (`scripts/generate_av_lora.py`, `server/lib/runners.js`, `server/services/videoGen/local.js`, `server/routes/videoGen.js`, `client/src/lib/runnerFamilies.js`, `client/src/pages/VideoGen.jsx`)
+- **"Format" button on each manuscript section cleans up pasted-PDF artifacts.** Text pasted out of a PDF export arrives hard-wrapped at the page margin (every visual line a real `\n`), with stylized drop-caps split onto their own line ("T\nhe dawn …") and words hyphenated across the wrap ("approxi-\nmating") — so a paragraph reads as a column of ragged lines. A new **Format** button in each section's header (both Live and Review modes) normalizes the section: it rejoins drop-caps, repairs hyphen splits, strips trailing whitespace, and collapses runaway blank lines for every stage, and — for **prose** only — reflows the soft-wrapped lines back into paragraphs (comic/teleplay keep their structural line breaks). The reflow heuristic keys on lowercase line continuations (a real sentence never starts lowercase) and falls back to measured wrap width for the ambiguous capital-start case, so short headings/attributions stay on their own line. The prior text is snapshotted server-side, so History ▸ Revert undoes a format in one click. (`client/src/lib/manuscriptFormat.js`, `client/src/components/pipeline/manuscript/ManuscriptSectionFrame.jsx`, `client/src/pages/PipelineManuscriptEditor.jsx`)
+
## Changed
- **Share the `--user-loras` JSON parser between the two video LoRA runners.** `parse_user_loras` (the strict `[{path, strength}]` validator that surfaces a Node-side bug before any model load) was duplicated verbatim in `scripts/generate_ltx2.py` (dgrauet `ltx2` runtime) and `scripts/generate_av_lora.py` (mlx_video runtime); it now lives once in `scripts/_runner_common.py` (stdlib-only at import, so it's safe to import from either MLX venv — verified in both) and both runners import it, so a future fix to the validation contract can't drift between them. (`scripts/_runner_common.py`, `scripts/generate_ltx2.py`, `scripts/generate_av_lora.py`)
diff --git a/client/src/components/pipeline/manuscript/AnnotatedManuscriptSection.jsx b/client/src/components/pipeline/manuscript/AnnotatedManuscriptSection.jsx
index 8b4e59237f..8e84523cfa 100644
--- a/client/src/components/pipeline/manuscript/AnnotatedManuscriptSection.jsx
+++ b/client/src/components/pipeline/manuscript/AnnotatedManuscriptSection.jsx
@@ -20,7 +20,7 @@ import { rowsFor } from './constants';
export default function AnnotatedManuscriptSection({
section, comments, spans, saveState, editing, onToggleEdit,
openCommentId, onOpenComment, onCloseComment,
- onContentChange, onBlurSave, onRevert, registerRef, commentCardProps,
+ onContentChange, onBlurSave, onFormat, onRevert, registerRef, commentCardProps,
}) {
const content = section.content || '';
const byId = useMemo(() => new Map(comments.map((c) => [c.id, c])), [comments]);
@@ -65,7 +65,7 @@ export default function AnnotatedManuscriptSection({
);
return (
- <ManuscriptSectionFrame section={section} saveState={saveState} onRevert={onRevert} headerExtra={editToggle} registerRef={registerRef}>
+ <ManuscriptSectionFrame section={section} saveState={saveState} onRevert={onRevert} onFormat={onFormat} headerExtra={editToggle} registerRef={registerRef}>
{editing ? (
<textarea
value={content}
diff --git a/client/src/components/pipeline/manuscript/ManuscriptLiveSection.jsx b/client/src/components/pipeline/manuscript/ManuscriptLiveSection.jsx
index eaf8015ec4..4ddb7eeb37 100644
--- a/client/src/components/pipeline/manuscript/ManuscriptLiveSection.jsx
+++ b/client/src/components/pipeline/manuscript/ManuscriptLiveSection.jsx
@@ -26,7 +26,7 @@ const EDITOR_TYPO = 'px-3 py-2 text-sm font-mono leading-relaxed whitespace-pre-
export default function ManuscriptLiveSection({
section, comments, spans, saveState, openCommentId, onOpenComment, onCloseComment,
- onContentChange, onBlurSave, onRevert, registerRef, commentCardProps,
+ onContentChange, onBlurSave, onFormat, onRevert, registerRef, commentCardProps,
}) {
const content = section.content || '';
const taRef = useRef(null);
@@ -72,7 +72,7 @@ export default function ManuscriptLiveSection({
useEscapeKey(openComment, onCloseComment);
return (
- <ManuscriptSectionFrame section={section} saveState={saveState} onRevert={onRevert} registerRef={registerRef}>
+ <ManuscriptSectionFrame section={section} saveState={saveState} onRevert={onRevert} onFormat={onFormat} registerRef={registerRef}>
{/* 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">
diff --git a/client/src/components/pipeline/manuscript/ManuscriptSectionFrame.jsx b/client/src/components/pipeline/manuscript/ManuscriptSectionFrame.jsx
index a4ca104548..1f3124eea0 100644
--- a/client/src/components/pipeline/manuscript/ManuscriptSectionFrame.jsx
+++ b/client/src/components/pipeline/manuscript/ManuscriptSectionFrame.jsx
@@ -7,8 +7,9 @@
*/
import { useState } from 'react';
-import { Loader2, History, RotateCcw } from 'lucide-react';
+import { Loader2, History, RotateCcw, WandSparkles } from 'lucide-react';
import { timeAgo } from '../../../utils/formatters';
+import { REFLOW_STAGES } from '../../../lib/manuscriptFormat';
import { STAGE_LABEL } from './constants';
function SaveBadge({ state }) {
@@ -17,9 +18,10 @@ function SaveBadge({ state }) {
return null;
}
-export default function ManuscriptSectionFrame({ section, saveState, onRevert, headerExtra, registerRef, children }) {
+export default function ManuscriptSectionFrame({ section, saveState, onRevert, onFormat, headerExtra, registerRef, children }) {
const [showVersions, setShowVersions] = useState(false);
const [revertingId, setRevertingId] = useState(null);
+ const [formatting, setFormatting] = useState(false);
const versions = section.versions || [];
const revert = async (runId) => {
@@ -28,6 +30,17 @@ export default function ManuscriptSectionFrame({ section, saveState, onRevert, h
setRevertingId(null);
};
+ const format = async () => {
+ setFormatting(true);
+ await onFormat();
+ setFormatting(false);
+ };
+
+ // Prose reflows into paragraphs; scripts only get safe artifact cleanup.
+ const formatTitle = REFLOW_STAGES.has(section.stageId)
+ ? 'Clean up formatting — fix pasted-PDF artifacts (drop-caps, hyphen splits) and reflow hard-wrapped lines into paragraphs'
+ : 'Clean up formatting — fix pasted-PDF artifacts (drop-caps, hyphen splits, stray blank lines) while keeping the script\'s line breaks';
+
return (
<article ref={registerRef} 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">
@@ -36,6 +49,18 @@ export default function ManuscriptSectionFrame({ section, saveState, onRevert, h
<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">
+ {onFormat ? (
+ <button
+ type="button"
+ onClick={format}
+ disabled={formatting}
+ 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 disabled:opacity-40"
+ title={formatTitle}
+ >
+ {formatting ? <Loader2 size={11} className="animate-spin" /> : <WandSparkles size={11} />}
+ Format
+ </button>
+ ) : null}
{headerExtra}
<SaveBadge state={saveState} />
{versions.length > 0 ? (
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index f267b9f43d..cea1a08b5d 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -77,6 +77,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `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`. |
+| `manuscriptFormat.js` | `formatManuscript(text, stageId)` / `REFLOW_STAGES` — normalize a manuscript section's text for the editor's "Format" button: undo PDF-paste artifacts (stylized drop-cap split onto its own line, hyphen-split words, trailing whitespace, runaway blank lines) for every stage, and additionally reflow soft-wrapped lines back into paragraphs for `prose` only (scripts keep their structural line breaks). Pure/DOM-free. |
| `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/index.js b/client/src/lib/index.js
index 3e6500cbc2..c70f783b89 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -48,6 +48,7 @@ export * from './joinInfluenceList.js';
export * from './localLlmTargetKey.js';
export * from './loopbackHost.js';
export * from './manuscriptAnchors.js';
+export * from './manuscriptFormat.js';
export * from './mediaNavigation.js';
export * from './mediaSearch.js';
export * from './sameJsonShape.js';
diff --git a/client/src/lib/manuscriptFormat.js b/client/src/lib/manuscriptFormat.js
new file mode 100644
index 0000000000..45dd8b97a9
--- /dev/null
+++ b/client/src/lib/manuscriptFormat.js
@@ -0,0 +1,109 @@
+/**
+ * Pure manuscript text normalizer for the Manuscript editor's "Format" button.
+ *
+ * The motivating mess: text pasted out of a PDF export arrives hard-wrapped at
+ * the page margin (every visual line is a real `\n`), with stylized drop-caps
+ * split onto their own line ("T\nhe dawn …") and words hyphenated across the
+ * wrap ("approxi-\nmating"). `formatManuscript(text, stageId)` undoes those
+ * paste artifacts so a paragraph reads as one logical line again.
+ *
+ * Two altitudes, chosen by stage:
+ * - prose → full reflow: join soft-wrapped lines back into paragraphs.
+ * - comic / teleplay / anything else → conservative cleanup ONLY. Scripts
+ * carry meaning in their line breaks (scene headings, panel descriptions,
+ * character cues), so we never reflow them — we only fix the unambiguous
+ * artifacts (drop-caps, hyphen splits, trailing whitespace, blank-line runs).
+ *
+ * Reflow heuristic (the hard part — PDF paste usually has NO blank lines between
+ * paragraphs, so we can't key on those alone):
+ * A newline between `prev` and `cur` is a SOFT WRAP (join the lines) when —
+ * 1. `cur` begins with a lowercase letter. A real sentence/paragraph never
+ * starts lowercase, so this is the high-confidence signal and does the
+ * bulk of the work.
+ * 2. `cur` begins with a capital/quote/dash (ambiguous: could be a new
+ * sentence OR a wrapped proper noun). Fall back to width: if `prev`
+ * reached near the measured wrap margin it was wrapped → join; if `prev`
+ * is short it ended deliberately (paragraph end, heading, dialogue) → keep.
+ * Blank lines always separate paragraphs and are never crossed.
+ *
+ * Pure + dependency-free (no DOM) so it runs in node test env too.
+ */
+
+// Stages whose line breaks are prose-structural and safe to reflow. Everything
+// else (comicScript, teleplay, …) gets the conservative pass only.
+export const REFLOW_STAGES = new Set(['prose']);
+
+// A line at least this fraction of the measured wrap width is treated as "full"
+// (i.e. it hit the margin and was wrapped). Only consulted when the NEXT line
+// starts with a capital/quote/dash (ambiguous) — lowercase continuations join
+// outright. Kept high so short heading/attribution lines stay below it and are
+// not swallowed into the paragraph that follows; a wrapped line that ends a
+// little early before a capitalized word just keeps its break (the safe miss).
+const FULL_LINE_RATIO = 0.8;
+
+const stripTrailingWs = (text) => text.split('\n').map((l) => l.replace(/[ \t]+$/, '')).join('\n');
+
+// Join a syllable hyphenated across a wrap: "approxi-\nmating" → "approximating".
+// Only letter-hyphen-newline-lowercase, so real line-final hyphens before a
+// capitalized word or number are left alone.
+const dehyphenate = (text) => text.replace(/([A-Za-z])-\n([a-z])/g, '$1$2');
+
+// Re-attach a stylized drop-cap that landed on its own line: a line that is a
+// single uppercase letter immediately followed by a line starting lowercase.
+// "T\nhe dawn" → "The dawn". Lookahead keeps the next line's first char.
+const rejoinDropCaps = (text) => text.replace(/^([A-Z])\n(?=[a-z])/gm, '$1');
+
+// Collapse 3+ consecutive newlines to a single blank line, then trim the ends.
+const tidyBlankLines = (text) => text.replace(/\n{3,}/g, '\n\n').trim();
+
+function reflowProse(text) {
+ const lines = text.split('\n');
+ // reduce (not Math.max(...spread)) so a manuscript with very many lines can't
+ // blow the argument-count limit and throw.
+ const maxLen = lines.reduce((max, l) => (l.trim() ? Math.max(max, l.length) : max), 0);
+ const fullThreshold = maxLen * FULL_LINE_RATIO;
+
+ const out = [];
+ let prevBlank = true; // start-of-text behaves like just after a paragraph break
+ let prevFull = false; // was the last consumed line near the wrap margin?
+
+ for (const raw of lines) {
+ const line = raw.trim();
+ if (line === '') {
+ out.push('');
+ prevBlank = true;
+ prevFull = false;
+ continue;
+ }
+ // A newline is a soft wrap when the next line continues lowercase, or — when
+ // ambiguous — when the previous line ran to the margin.
+ const continuesLower = /^[a-z]/.test(line);
+ const softWrap = !prevBlank && (continuesLower || prevFull);
+ if (softWrap) {
+ out[out.length - 1] = `${out[out.length - 1]} ${line}`;
+ } else {
+ out.push(line);
+ }
+ prevBlank = false;
+ prevFull = raw.length >= fullThreshold;
+ }
+ return out.join('\n');
+}
+
+/**
+ * Normalize a manuscript section's text.
+ * @param {string} text - raw section content
+ * @param {string} stageId - 'prose' | 'comicScript' | 'teleplay' | …
+ * @returns {string} formatted text (unchanged input → identical output)
+ */
+export function formatManuscript(text, stageId) {
+ if (typeof text !== 'string' || text === '') return text || '';
+
+ let out = text.replace(/\r\n?/g, '\n'); // CRLF / bare CR → LF
+ out = stripTrailingWs(out);
+ out = dehyphenate(out);
+ out = rejoinDropCaps(out);
+ if (REFLOW_STAGES.has(stageId)) out = reflowProse(out);
+ out = tidyBlankLines(out);
+ return out;
+}
diff --git a/client/src/lib/manuscriptFormat.test.js b/client/src/lib/manuscriptFormat.test.js
new file mode 100644
index 0000000000..db7f072fa4
--- /dev/null
+++ b/client/src/lib/manuscriptFormat.test.js
@@ -0,0 +1,113 @@
+import { describe, it, expect } from 'vitest';
+import { formatManuscript } from './manuscriptFormat.js';
+
+describe('formatManuscript — prose reflow', () => {
+ it('rejoins a stylized drop-cap split onto its own line', () => {
+ const out = formatManuscript('T\nhe dawn cycle hums to life.', 'prose');
+ expect(out).toBe('The dawn cycle hums to life.');
+ });
+
+ it('de-hyphenates a word split across a wrap', () => {
+ const out = formatManuscript('something approxi-\nmating daylight.', 'prose');
+ expect(out).toBe('something approximating daylight.');
+ });
+
+ it('joins soft-wrapped lines back into one paragraph', () => {
+ const input = [
+ 'The dawn cycle hums to life the way it',
+ 'always does — fluorescents warming from',
+ 'bruise-purple to something approximating',
+ 'daylight, the sublevel\'s cooling vents.',
+ ].join('\n');
+ expect(formatManuscript(input, 'prose')).toBe(
+ "The dawn cycle hums to life the way it always does — fluorescents warming from "
+ + "bruise-purple to something approximating daylight, the sublevel's cooling vents.",
+ );
+ });
+
+ it('keeps a short heading line separate from the paragraph that follows', () => {
+ const input = [
+ 'Chapter 12: Natural Frequency',
+ 'The dawn cycle hums to life the way it',
+ 'always does, warming the cold sublevel air.',
+ ].join('\n');
+ const out = formatManuscript(input, 'prose');
+ expect(out.split('\n')[0]).toBe('Chapter 12: Natural Frequency');
+ expect(out.split('\n')[1]).toBe(
+ 'The dawn cycle hums to life the way it always does, warming the cold sublevel air.',
+ );
+ });
+
+ it('reproduces the pasted-PDF epigraph artifact end to end', () => {
+ const input = [
+ 'Chapter 12: Natural Frequency',
+ '— JUNO, novel manuscript,',
+ 'final line',
+ 'T',
+ 'he dawn cycle hums to life the way it',
+ 'always does, fluorescents warming the room.',
+ ].join('\n');
+ expect(formatManuscript(input, 'prose')).toBe([
+ 'Chapter 12: Natural Frequency',
+ '— JUNO, novel manuscript, final line',
+ 'The dawn cycle hums to life the way it always does, fluorescents warming the room.',
+ ].join('\n'));
+ });
+
+ it('does not cross a blank-line paragraph break', () => {
+ const input = 'First paragraph line one\nline two of it.\n\nSecond paragraph here.';
+ expect(formatManuscript(input, 'prose')).toBe(
+ 'First paragraph line one line two of it.\n\nSecond paragraph here.',
+ );
+ });
+
+ it('is idempotent — formatting clean prose is a no-op', () => {
+ const clean = 'A tidy paragraph that needs no changes at all.';
+ const once = formatManuscript(clean, 'prose');
+ expect(once).toBe(clean);
+ expect(formatManuscript(once, 'prose')).toBe(once);
+ });
+});
+
+describe('formatManuscript — conservative (non-prose) stages', () => {
+ it('does NOT reflow a comic script — line breaks are structural', () => {
+ const input = [
+ 'PAGE 1',
+ 'PANEL 1',
+ 'A wide shot of the plasma pool, steam rising.',
+ 'JUNO: We shouldn\'t be here.',
+ ].join('\n');
+ expect(formatManuscript(input, 'comicScript')).toBe(input);
+ });
+
+ it('does NOT reflow a teleplay', () => {
+ const input = 'INT. SUBLEVEL - DAWN\n\nJUNO crosses to the diagnostic array.';
+ expect(formatManuscript(input, 'teleplay')).toBe(input);
+ });
+
+ it('still fixes drop-caps and hyphen splits in a comic script', () => {
+ const input = 'CAPTION: T\nhe morning of the over-\nride.';
+ expect(formatManuscript(input, 'comicScript')).toBe('CAPTION: T\nhe morning of the override.');
+ // (drop-cap rejoin is anchored to line start, so the inline "T" above is
+ // untouched; the hyphen split is repaired.)
+ });
+
+ it('repairs a true line-start drop-cap in a script', () => {
+ expect(formatManuscript('T\nhe end.', 'comicScript')).toBe('The end.');
+ });
+});
+
+describe('formatManuscript — whitespace hygiene (all stages)', () => {
+ it('normalizes CRLF and strips trailing whitespace', () => {
+ expect(formatManuscript('line one \r\nline two\t', 'comicScript')).toBe('line one\nline two');
+ });
+
+ it('collapses runs of 3+ blank lines to a single blank line', () => {
+ expect(formatManuscript('a\n\n\n\nb', 'teleplay')).toBe('a\n\nb');
+ });
+
+ it('returns empty input untouched', () => {
+ expect(formatManuscript('', 'prose')).toBe('');
+ expect(formatManuscript(null, 'prose')).toBe('');
+ });
+});
diff --git a/client/src/pages/PipelineManuscriptEditor.jsx b/client/src/pages/PipelineManuscriptEditor.jsx
index 0ff0a7fb82..fba3d0cb0b 100644
--- a/client/src/pages/PipelineManuscriptEditor.jsx
+++ b/client/src/pages/PipelineManuscriptEditor.jsx
@@ -32,6 +32,7 @@ import { Link, useParams, useNavigate } from 'react-router-dom';
import {
ArrowLeft, Loader2, Sparkles, FileText, Star, ClipboardCheck, Layers, PencilLine, BookOpen, GitCompare, X,
} from 'lucide-react';
+import { formatManuscript } from '../lib/manuscriptFormat';
import toast from '../components/ui/Toast';
import { useAsyncAction } from '../hooks/useAsyncAction';
import { usePipelineProgress } from '../hooks/usePipelineProgress';
@@ -355,14 +356,14 @@ export default function PipelineManuscriptEditor() {
const setSectionContent = (issueId, content) => patchSection(issueId, { content });
- const saveSection = async (section) => {
+ const saveSectionContent = async (section, content) => {
const key = `${section.issueId}:${section.stageId}`;
- if (baselineRef.current.get(key) === section.content) return;
+ if (baselineRef.current.get(key) === content) return;
setSaveState((prev) => ({ ...prev, [section.issueId]: 'saving' }));
const result = await savePipelineManuscriptSection(
seriesId,
section.issueId,
- { stageId: section.stageId, output: section.content },
+ { stageId: section.stageId, output: content },
{ silent: true },
).catch((err) => {
toast.error(err.message || 'Failed to save manuscript edit');
@@ -375,6 +376,24 @@ export default function PipelineManuscriptEditor() {
setSaveState((prev) => ({ ...prev, [section.issueId]: result ? 'saved' : undefined }));
};
+ const saveSection = (section) => saveSectionContent(section, section.content);
+
+ // Clean up paste artifacts (PDF drop-caps, hyphen splits, hard-wrapped lines)
+ // and persist. Prose reflows into paragraphs; comic/teleplay keep their
+ // structural line breaks. The prior text is snapshotted server-side, so the
+ // History ▸ Revert affordance undoes it — no confirm needed.
+ const formatSection = async (section) => {
+ const current = section.content || '';
+ const formatted = formatManuscript(current, section.stageId);
+ if (formatted === current) {
+ toast('Already well-formatted — nothing to clean up');
+ return;
+ }
+ setSectionContent(section.issueId, formatted);
+ await saveSectionContent(section, formatted);
+ toast.success('Formatting cleaned up');
+ };
+
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; });
@@ -647,6 +666,7 @@ export default function PipelineManuscriptEditor() {
onCloseComment: () => setOpenCommentId(null),
onContentChange: (content) => setSectionContent(section.issueId, content),
onBlurSave: () => saveSection(section),
+ onFormat: () => formatSection(section),
onRevert: (runId) => revertSection(section, runId),
registerRef: registerSectionRef(section.number),
commentCardProps,