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

refactor: /simplify pass — dedupe socket sub, share refine helper, trim noise

[._.]/ Adam Eivy23096ad39b01
diff --git a/client/src/components/pipeline/MediaJobThumb.jsx b/client/src/components/pipeline/MediaJobThumb.jsx
index 4d6606277c..e968c4176c 100644
--- a/client/src/components/pipeline/MediaJobThumb.jsx
+++ b/client/src/components/pipeline/MediaJobThumb.jsx
@@ -16,7 +16,10 @@ import useMediaJobProgress from '../../hooks/useMediaJobProgress';
* does — flips to a "missing" badge with a Retry button (re-arms the
* <video>/<img> via a cache-busting key) when the file 404s.
*/
-export default function MediaJobThumb({ jobId, label = 'Render', size = 'sm', kind = 'image', onPreview = null }) {
+export default function MediaJobThumb({
+ jobId, label = 'Render', size = 'sm', kind = 'image',
+ onPreview = null, onStatus = null, onFilename = null,
+}) {
const { status, progress, step, totalSteps, currentImage, filename, error } =
useMediaJobProgress(jobId, { kind });
// Local missing-media state. Reset when jobId changes so a fresh render
@@ -25,6 +28,12 @@ export default function MediaJobThumb({ jobId, label = 'Render', size = 'sm', ki
const [attempt, setAttempt] = useState(0);
useEffect(() => { setMissing(false); setAttempt(0); }, [jobId]);
+ // Forward subscription state to the parent so callers (e.g. PageRow's
+ // disable-while-rendering logic, lightbox nav builders) don't need a
+ // duplicate useMediaJobProgress subscription on the same jobId.
+ useEffect(() => { if (onStatus) onStatus(status); }, [status, onStatus]);
+ useEffect(() => { if (onFilename && filename) onFilename(filename); }, [filename, onFilename]);
+
if (!jobId) return null;
// `fill` fills the parent container's width with the image's natural
diff --git a/client/src/components/pipeline/stages/ComicScriptStage.jsx b/client/src/components/pipeline/stages/ComicScriptStage.jsx
index 5e888958c9..113cd0cc40 100644
--- a/client/src/components/pipeline/stages/ComicScriptStage.jsx
+++ b/client/src/components/pipeline/stages/ComicScriptStage.jsx
@@ -25,7 +25,6 @@ import { getSettings, updateSettings } from '../../../services/apiSystem';
import { listImageModels } from '../../../services/apiImageVideo';
import MediaJobThumb from '../MediaJobThumb';
import MediaPreview from '../../media/MediaPreview';
-import useMediaJobProgress from '../../../hooks/useMediaJobProgress';
import Drawer from '../../Drawer';
import ImageGenSettingsForm from '../../imageGen/ImageGenSettingsForm';
import { deriveAvailableBackends } from '../../../lib/imageGenBackends';
@@ -308,20 +307,18 @@ function PageRow({ issue, pageIndex, page, renderOpts = {}, onStageUpdate, onPre
useEffect(() => { setDraft(rawText); }, [rawText]);
const dirty = draft !== rawText;
- // Subscribe to the page's render job so we can (a) disable the Render
- // button while the job is queued/running and (b) bubble the resolved
- // filename up to the parent for lightbox nav.
- const { status: jobStatus, filename: jobFilename } = useMediaJobProgress(page.imageJobId);
- useEffect(() => {
- if (page.imageJobId && jobFilename) onFilenameKnown?.(page.imageJobId, jobFilename);
- }, [page.imageJobId, jobFilename, onFilenameKnown]);
- // Treat 'unknown' (pre-hydration) as in-flight when a jobId exists — avoids
- // a brief re-enable flash after page reload while the GET /media-jobs/:id
- // catches up.
+ // Job status comes from MediaJobThumb via callback so we don't double-
+ // subscribe to the same socket events. Treat 'unknown' (pre-hydration)
+ // as in-flight when a jobId exists — avoids a brief re-enable flash
+ // after page reload while the GET /media-jobs/:id catches up.
+ const [jobStatus, setJobStatus] = useState('unknown');
const jobInFlight = !!page.imageJobId
&& jobStatus !== 'completed'
&& jobStatus !== 'failed'
&& jobStatus !== 'canceled';
+ const onJobFilename = useCallback((filename) => {
+ if (page.imageJobId) onFilenameKnown?.(page.imageJobId, filename);
+ }, [page.imageJobId, onFilenameKnown]);
const handleSave = async () => {
setSaving(true);
@@ -415,6 +412,8 @@ function PageRow({ issue, pageIndex, page, renderOpts = {}, onStageUpdate, onPre
label={`Page ${pageIndex + 1}`}
size="fill"
onPreview={(filename) => onPreview?.(pageIndex, filename, page)}
+ onStatus={setJobStatus}
+ onFilename={onJobFilename}
/>
) : (
<span className="text-xs text-gray-500 italic">No render yet — click <em>Render</em>.</span>
diff --git a/server/services/pipeline/nounRefine.js b/server/services/pipeline/nounRefine.js
index 40c4b2d44c..d480b0735e 100644
--- a/server/services/pipeline/nounRefine.js
+++ b/server/services/pipeline/nounRefine.js
@@ -1,54 +1,28 @@
-/**
- * Refine a single character's `physicalDescription` so it renders visually
- * distinct from the rest of the cast. The LLM sees the target + every peer's
- * existing description and is asked to commit to specific differentiating
- * choices (ethnicity, age, hair, silhouette, wardrobe palette, ...).
- *
- * Reads/writes go through `getSeries` / `updateSeries` so the regular
- * sanitize-on-write pass still runs.
- */
+// Rewrite a character's `physicalDescription` so the rendered image differs
+// from every peer in the cast. Characters only (settings/objects need
+// different prompt fields — punt until there's a real need).
import { getSeries, updateSeries } from './series.js';
import { getUniverse } from '../universeBuilder.js';
-import { runStagedLLM } from '../../lib/stageRunner.js';
import { ServerError } from '../../lib/errorHandler.js';
+import { runPromptRefine } from './refineHelpers.js';
-const KIND_FIELD = Object.freeze({
- characters: 'physicalDescription',
+const peerForPrompt = (entry) => ({
+ name: entry.name,
+ aliases: Array.isArray(entry.aliases) ? entry.aliases : [],
+ role: entry.role || '',
+ physicalDescription: entry.physicalDescription || entry.description || '',
});
-// Slimmed-down peer shape sent to the prompt. Drops timestamps + ids the LLM
-// doesn't need so the prompt stays inside the context budget when the cast
-// grows past a few entries.
-function peerForPrompt(entry) {
- return {
- name: entry.name,
- aliases: Array.isArray(entry.aliases) ? entry.aliases : [],
- role: entry.role || '',
- physicalDescription: entry.physicalDescription || entry.description || '',
- };
-}
-
-function targetForPrompt(entry) {
- return {
- name: entry.name,
- aliases: Array.isArray(entry.aliases) ? entry.aliases : [],
- role: entry.role || '',
- physicalDescription: entry.physicalDescription || '',
- evidence: Array.isArray(entry.evidence) ? entry.evidence : [],
- firstAppearance: entry.firstAppearance || null,
- };
-}
+const targetForPrompt = (entry) => ({
+ ...peerForPrompt(entry),
+ evidence: Array.isArray(entry.evidence) ? entry.evidence : [],
+ firstAppearance: entry.firstAppearance || null,
+});
export async function refineCharacterDescription(seriesId, entryId, options = {}) {
- const kind = 'characters';
- const field = KIND_FIELD[kind];
- if (!field) {
- throw new ServerError(`Unsupported noun kind: ${kind}`, { status: 400, code: 'PIPELINE_NOUN_KIND' });
- }
-
const series = await getSeries(seriesId);
- const list = Array.isArray(series[kind]) ? series[kind] : [];
+ const list = Array.isArray(series.characters) ? series.characters : [];
const idx = list.findIndex((e) => e.id === entryId);
if (idx < 0) {
throw new ServerError(`Character ${entryId} not found in series`, {
@@ -58,9 +32,6 @@ export async function refineCharacterDescription(seriesId, entryId, options = {}
const target = list[idx];
const peers = list.filter((_, i) => i !== idx);
- // Style clause: universe stylePrompt (if linked) + series styleNotes, dropped
- // into the prompt as plain text. The LLM doesn't need the full universe JSON —
- // it only steers wardrobe/era cues toward the established aesthetic.
const universe = series.universeId ? await getUniverse(series.universeId).catch(() => null) : null;
const styleBits = [
universe?.stylePrompt ? `Universe aesthetic: ${universe.stylePrompt}` : null,
@@ -70,41 +41,24 @@ export async function refineCharacterDescription(seriesId, entryId, options = {}
? styleBits.join('\n')
: '(none provided — pick choices that fit the character\'s role and genre)';
- const result = await runStagedLLM('pipeline-character-refine', {
- targetJson: JSON.stringify(targetForPrompt(target), null, 2),
- peersJson: JSON.stringify(peers.map(peerForPrompt), null, 2),
- styleClause,
- }, {
- providerOverride: options.providerId,
- modelOverride: options.model,
- returnsJson: true,
+ const { refined, changes, rationale, runId, providerId, model } = await runPromptRefine({
+ templateName: 'pipeline-character-refine',
+ variables: {
+ targetJson: JSON.stringify(targetForPrompt(target), null, 2),
+ peersJson: JSON.stringify(peers.map(peerForPrompt), null, 2),
+ styleClause,
+ },
+ options,
source: 'pipeline-character-refine',
+ logTag: `Pipeline character refine — series=${seriesId.slice(0, 8)} entry=${entryId.slice(0, 8)}`,
+ resultField: 'physicalDescription',
+ emptyError: { code: 'PIPELINE_NOUN_REFINE_EMPTY', message: 'LLM returned an empty physicalDescription' },
+ changesLimit: 12,
});
- const refined = (result.content?.physicalDescription || '').trim();
- if (!refined) {
- throw new ServerError('LLM returned an empty physicalDescription', {
- status: 502, code: 'PIPELINE_NOUN_REFINE_EMPTY',
- });
- }
- const rationale = (result.content?.rationale || '').trim();
- const changes = Array.isArray(result.content?.changes)
- ? result.content.changes.map((c) => String(c).slice(0, 240)).filter(Boolean).slice(0, 12)
- : [];
-
- const nextList = list.map((e, i) => i === idx ? { ...e, [field]: refined } : e);
- const updated = await updateSeries(seriesId, { [kind]: nextList });
- const updatedEntry = (updated[kind] || []).find((e) => e.id === entryId) || null;
-
- console.log(`✨ Pipeline character refine — series=${seriesId.slice(0, 8)} entry=${entryId.slice(0, 8)} runId=${(result.runId || '').slice(0, 8)}`);
+ const nextList = list.map((e, i) => i === idx ? { ...e, physicalDescription: refined } : e);
+ const updated = await updateSeries(seriesId, { characters: nextList });
+ const updatedEntry = (updated.characters || []).find((e) => e.id === entryId) || null;
- return {
- series: updated,
- entry: updatedEntry,
- rationale,
- changes,
- runId: result.runId,
- providerId: result.providerId,
- model: result.model,
- };
+ return { series: updated, entry: updatedEntry, rationale, changes, runId, providerId, model };
}
diff --git a/server/services/pipeline/refineHelpers.js b/server/services/pipeline/refineHelpers.js
new file mode 100644
index 0000000000..26c5c485ef
--- /dev/null
+++ b/server/services/pipeline/refineHelpers.js
@@ -0,0 +1,37 @@
+import { runStagedLLM } from '../../lib/stageRunner.js';
+import { ServerError } from '../../lib/errorHandler.js';
+
+// Shared scaffolding for every pipeline LLM refine path (comic-panel,
+// storyboard-scene, character-physicalDescription). Owns the runStagedLLM call,
+// the empty-result guard, the changes-array shaping, and the runId log. Callers
+// pass `resultField` (e.g. 'prompt' or 'physicalDescription') so this helper
+// stays prompt-agnostic.
+export async function runPromptRefine({
+ templateName,
+ variables,
+ options = {},
+ source,
+ logTag,
+ resultField = 'prompt',
+ emptyError = { code: 'PIPELINE_PROMPT_REFINE_EMPTY', message: 'LLM returned an empty refined prompt' },
+ changesLimit = 8,
+}) {
+ const result = await runStagedLLM(templateName, variables, {
+ providerOverride: options.providerId,
+ modelOverride: options.model,
+ returnsJson: true,
+ source,
+ });
+ const refined = (result.content?.[resultField] || '').trim();
+ if (!refined) {
+ throw new ServerError(emptyError.message, { status: 502, code: emptyError.code });
+ }
+ const changes = Array.isArray(result.content?.changes)
+ ? result.content.changes.map((c) => String(c).slice(0, 240)).filter(Boolean).slice(0, changesLimit)
+ : [];
+ const rationale = typeof result.content?.rationale === 'string'
+ ? result.content.rationale.trim()
+ : '';
+ console.log(`✨ ${logTag} runId=${(result.runId || '').slice(0, 8)}`);
+ return { refined, changes, rationale, runId: result.runId, providerId: result.providerId, model: result.model };
+}
diff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.js
index ff29c3ff25..9599e77466 100644
--- a/server/services/pipeline/visualStages.js
+++ b/server/services/pipeline/visualStages.js
@@ -37,6 +37,7 @@ import {
import { composeStyledPrompt } from '../../lib/composeStyledPrompt.js';
import { getDefaultVideoModelId, getVideoModels } from '../../lib/mediaModels.js';
import { runStagedLLM } from '../../lib/stageRunner.js';
+import { runPromptRefine } from './refineHelpers.js';
import { ASPECT_PRESETS } from '../../lib/creativeDirectorPresets.js';
const SUPPORTED_MODES = new Set(['local', 'codex']);
@@ -465,29 +466,6 @@ async function loadRefineContext(issueId) {
return { issue, series };
}
-// Shared scaffolding for both the comic-panel and storyboard-scene refine
-// paths. The caller supplies the per-stage variables/persist details; this
-// helper owns the runStagedLLM call + result parsing + empty-prompt guard +
-// changes shaping.
-async function runPromptRefine({ templateName, variables, options, source, logTag }) {
- const result = await runStagedLLM(templateName, variables, {
- providerOverride: options.providerId,
- modelOverride: options.model,
- returnsJson: true,
- source,
- });
- const refined = (result.content?.prompt || '').trim();
- if (!refined) {
- throw new ServerError('LLM returned an empty refined prompt', {
- status: 502, code: 'PIPELINE_PROMPT_REFINE_EMPTY',
- });
- }
- const changes = Array.isArray(result.content?.changes)
- ? result.content.changes.map((c) => String(c).slice(0, 240)).filter(Boolean).slice(0, 8)
- : [];
- console.log(`✨ ${logTag} runId=${(result.runId || '').slice(0, 8)}`);
- return { refined, changes, runId: result.runId, providerId: result.providerId };
-}
/**
* Run the `pipeline-comic-panel-image-prompt` template against the current