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

feat: stream text-stage generation progress over SSE (#3393)

[._.]/ Adam Eivy9c6813beaedb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 3dfb0bc091..9a8ba2e2ed 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -27,6 +27,7 @@
- **The Round editor is a composition, not a 1,326-line component.** `RoundEditor.jsx` drops to 164 lines of page shell — header chrome plus the pick between its three body surfaces — with the state split into four named hooks (`useRoundViewParams` for the `?mode`/`?stack`/`?analyze` views, `useRoundDraft` for load/save/refresh-from-template/AI-merge and the `baseDirty` saved-state gate, `useRoundRows` for section/layer/reference/proposed-part edits, `useRoundPartners` for the quodlibet pick list) and the markup into five components in `client/src/components/songs/` (`RoundEditForm`, `RoundReadView`, `RoundSheetMusic`, `RoundReferenceCard`, `RoundBuiltInBanner`). The draft rules the page, hooks, and form all shared — server caps, the temp-id contract, the tempo band, and the save patch builder — are now `client/src/lib/roundDraft.js`, and the host-anchored TikTok embed-id helpers moved to `utils/urlNormalize.js` with tests. Behavior is unchanged. (#3389)
- `agentLifecycle.js` imported `getAgent` aliased as `getAgentRecord`, shadowing the real transcript-free reader that was split out in #3368 for exactly this purpose. Both call sites read only `.status`/`.metadata`, but the alias made them hydrate the record: reading and line-splitting a completed run's whole `output.txt` (megabytes on a long TUI run) and potentially rewriting `metadata.json` via `repairCodexTaskSummary`. Now imports the real `getAgentRecord`, read once and shared.
- **Universe Builder is a composition shell again.** `UniverseBuilderPage.jsx` drops from 778 to ~530 lines: the URL-backed tab/sub-bucket state (plus the two effects that strip a `?tab=`/`?bucket=` the current categories no longer support) is now `useUniverseTabs`, and generate-in-bucket / promote-to-canon / auto-sort — each with its own in-flight gate and stale-snapshot merge rules — is now `useUniverseBucketActions`. The render-completion handler that was copy-pasted between the trunk tabs and the Other tab is one shared callback. Expand/refine already lived in `useUniverseExpand`, so it stayed put. Behavior, markup, and API calls are unchanged; `useUniverseTabs` picks up 11 tests. (#3391)
+- **Text-stage generation streams its progress instead of spinning blind.** A draft-gated prose/script stage can run up to three generate+judge cycles — minutes with no signal — so `generateStage` now broadcasts phase frames (context build, drafting attempt N of M, judging, best-draft restore, canon extraction) and a per-attempt scorecard over a new SSE channel, and `TextStagePanel` renders them with PolishPanel's phase-label pattern. The channel is subscribe-first (attaching opens it, so the client can't race the POST it is about to send) and purely advisory: with no subscriber every emit is a no-op, and autoRunner, Series Autopilot, and the volume beat runner call generation exactly as before. (#3393)
## Better audit 2026-08-03 (UX, City scene, game/music/writing focus) — PRs #3401–#3404
diff --git a/client/src/components/pipeline/stages/TextStagePanel.jsx b/client/src/components/pipeline/stages/TextStagePanel.jsx
index 6ac7e79bc9..646597d6c7 100644
--- a/client/src/components/pipeline/stages/TextStagePanel.jsx
+++ b/client/src/components/pipeline/stages/TextStagePanel.jsx
@@ -6,11 +6,12 @@
*/
import { useEffect, useMemo, useState } from 'react';
-import { Loader2, Sparkles, Save, History } from 'lucide-react';
+import { Loader2, Sparkles, Save, History, Check, X } from 'lucide-react';
import toast from '../../ui/Toast';
import ProseEditor from '../../ui/ProseEditor';
import {
generatePipelineStage, updatePipelineIssue,
+ pipelineStageProgressUrl,
PIPELINE_STAGE_LABELS,
PIPELINE_TEXT_STAGES,
PIPELINE_DEFAULT_FORWARD_SOURCE as DEFAULT_FORWARD_SOURCE,
@@ -18,10 +19,29 @@ import {
PIPELINE_STAGE_STATUS_COLOR as STATUS_COLOR,
} from '../../../services/api';
import { useAsyncAction } from '../../../hooks/useAsyncAction';
+import { useSseProgress, isTerminalSseFrame } from '../../../hooks/useSseProgress';
+import { formatDurationMs } from '../../../utils/formatters';
import StageHistoryModal from './StageHistoryModal';
const stageHasContent = (stage) => Boolean(stage?.input?.trim() || stage?.output?.trim());
+// Human-readable labels for the live progress line, mirroring PolishPanel's
+// phase-label pattern. The server's own `label` is the fallback so a new phase
+// still reads sensibly before this map catches up.
+const PHASE_LABEL = {
+ context: 'Building prompt context…',
+ generate: 'Drafting…',
+ judge: 'Judging the draft…',
+ restore: 'Restoring the best draft…',
+ budget: 'Budget spent — keeping the best draft…',
+ canon: 'Extracting canon…',
+};
+
+// null/undefined = the judge never scored this attempt, which is NOT the same as
+// a legitimate score of 0 — render the two differently rather than gating on
+// truthiness.
+const fmtScore = (v) => (Number.isFinite(v) ? (Math.round(v * 10) / 10).toString() : '—');
+
export default function TextStagePanel({
issue,
series,
@@ -47,6 +67,17 @@ export default function TextStagePanel({
const [historyOpen, setHistoryOpen] = useState(false);
const runHistory = stage.runHistory || [];
+ // Live generation progress (#3393). The URL is set for the duration of one
+ // generate call; the server opens the channel when we attach, so subscribing
+ // just before the POST can't race it. Frames survive the teardown so the
+ // attempt scorecard stays on screen after the run finishes.
+ const [progressUrl, setProgressUrl] = useState(null);
+ // Which issue+stage the retained frames describe — the panel is reused across
+ // issues, and a stale scorecard from a different record must not linger.
+ const [progressFor, setProgressFor] = useState(null);
+ const { frames } = useSseProgress(progressUrl, { enabled: !!progressUrl });
+ const progressKey = `${issue.id}:${stageId}`;
+
// Other text stages that currently have content — the candidate source
// material for this generation. Excludes the target stage itself. Lets you
// generate any stage FROM any other populated stage (backport), e.g. prose
@@ -92,12 +123,42 @@ export default function TextStagePanel({
const generating = localGenerating || serverGenerating;
const handleGenerate = async () => {
+ // Subscribe to the progress stream first. It is purely advisory — an
+ // environment without EventSource (or a channel that never opens) just
+ // falls back to the spinner; generation itself is unaffected.
+ setProgressFor(progressKey);
+ if (typeof EventSource !== 'undefined') {
+ setProgressUrl(pipelineStageProgressUrl(issue.id, stageId));
+ }
const result = await runGenerate();
+ // Close the stream once the POST has settled — the terminal frame has
+ // already landed, and the frames stay rendered after the teardown.
+ setProgressUrl(null);
if (!result) return;
onStageUpdate?.(stageId, result.stage);
toast.success(`${PIPELINE_STAGE_LABELS[stageId]} generated`);
};
+ // Derived progress view. `activePhase` is the most recent phase frame that
+ // hasn't been superseded by a terminal frame — same walk PolishPanel does.
+ const showProgress = progressFor === progressKey;
+ const attemptFrames = useMemo(
+ () => (showProgress ? frames.filter((f) => f.type === 'attempt') : []),
+ [frames, showProgress],
+ );
+ const gateFrame = useMemo(
+ () => (showProgress ? frames.find((f) => f.type === 'gate') || null : null),
+ [frames, showProgress],
+ );
+ const activePhase = useMemo(() => {
+ if (!generating || !showProgress) return null;
+ for (let i = frames.length - 1; i >= 0; i -= 1) {
+ if (isTerminalSseFrame(frames[i])) return null;
+ if (frames[i].type === 'phase') return frames[i];
+ }
+ return null;
+ }, [frames, generating, showProgress]);
+
const dirty = draftOutput !== (stage.output || '') || draftInput !== (stage.input || '');
// Generate gates on OUTPUT drift only: the seed input is sent live with the
// request (seedInput: draftInput), so unsaved seed edits are consumed, not
@@ -194,6 +255,57 @@ export default function TextStagePanel({
</div>
) : null}
+ {(activePhase || attemptFrames.length > 0) ? (
+ <div className="border border-port-border rounded p-3 space-y-2 bg-port-bg/40">
+ <div className="flex items-center justify-between gap-2 text-[11px] flex-wrap">
+ <span className="uppercase tracking-wider text-gray-500">Generation progress</span>
+ {activePhase ? (
+ <span className="flex items-center gap-1.5 text-port-accent">
+ <Loader2 size={11} className="animate-spin" />
+ {PHASE_LABEL[activePhase.phase] || activePhase.label || activePhase.phase}
+ {activePhase.attempts > 1 ? (
+ <span className="text-gray-500">· attempt {activePhase.attempt} of {activePhase.attempts}</span>
+ ) : null}
+ </span>
+ ) : null}
+ </div>
+ {attemptFrames.length > 0 ? (
+ <ul className="space-y-1">
+ {attemptFrames.map((f) => {
+ // Before the gate frame lands nothing is decided yet — don't
+ // pre-label an attempt as rejected mid-run.
+ const decided = !!gateFrame;
+ const won = decided && f.runId === gateFrame.winner;
+ return (
+ <li key={f.runId || f.attempt} className="flex items-center gap-2 text-[12px]">
+ <span className="text-gray-500 w-20 shrink-0">Attempt {f.attempt}</span>
+ <span className="px-1.5 py-0.5 rounded border border-port-border bg-port-card text-[11px] tabular-nums shrink-0">
+ {fmtScore(f.qualityScore)}
+ </span>
+ {decided ? (
+ won ? (
+ <span className="flex items-center gap-1 text-port-success text-[11px]"><Check size={11} /> kept</span>
+ ) : (
+ <span className="flex items-center gap-1 text-gray-500 text-[11px]"><X size={11} /> rejected</span>
+ )
+ ) : null}
+ <span className="text-gray-600 text-[10px] tabular-nums ml-auto">
+ {Number.isFinite(f.outputLength) ? `${f.outputLength.toLocaleString()} chars · ` : ''}
+ {formatDurationMs(f.ms)}
+ </span>
+ </li>
+ );
+ })}
+ </ul>
+ ) : null}
+ {gateFrame?.stoppedEarly ? (
+ <div className="text-[11px] text-gray-500 italic">
+ Stopped early after {gateFrame.ran} of {gateFrame.attempts} attempts.
+ </div>
+ ) : null}
+ </div>
+ ) : null}
+
{stageId === 'idea' ? (
<label className="block">
<span className="block text-xs uppercase tracking-wider text-gray-500 mb-1">Seed idea</span>
diff --git a/client/src/components/pipeline/stages/TextStagePanel.test.jsx b/client/src/components/pipeline/stages/TextStagePanel.test.jsx
index 5c968193cf..bde5918df6 100644
--- a/client/src/components/pipeline/stages/TextStagePanel.test.jsx
+++ b/client/src/components/pipeline/stages/TextStagePanel.test.jsx
@@ -1,11 +1,13 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { render, screen, waitFor } from '@testing-library/react';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { render, screen, waitFor, act } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import { MockEventSource, lastEventSource } from '../../../test/mockEventSource';
vi.mock('../../../services/api', () => ({
generatePipelineStage: vi.fn(),
updatePipelineIssue: vi.fn(),
restorePipelineStageVersion: vi.fn(),
+ pipelineStageProgressUrl: (issueId, stageId) => `/api/pipeline/issues/${issueId}/stages/${stageId}/generate/progress`,
PIPELINE_STAGE_LABELS: { idea: 'Idea', prose: 'Prose', comicScript: 'Comic', teleplay: 'Teleplay' },
PIPELINE_TEXT_STAGES: ['idea', 'prose', 'comicScript', 'teleplay'],
PIPELINE_DEFAULT_FORWARD_SOURCE: { prose: ['idea'], comicScript: ['prose'], teleplay: ['prose'] },
@@ -181,4 +183,77 @@ describe('TextStagePanel', () => {
);
expect(generateBtn).not.toBeDisabled();
});
+
+ describe('live generation progress (#3393)', () => {
+ beforeEach(() => {
+ MockEventSource.reset();
+ global.EventSource = MockEventSource;
+ });
+ afterEach(() => { delete global.EventSource; });
+
+ // A generate call that stays pending so the stream is still "in flight".
+ const pendingGenerate = () => {
+ let resolve;
+ generatePipelineStage.mockReturnValue(new Promise((r) => { resolve = r; }));
+ return (stage) => resolve({ stage });
+ };
+
+ it('subscribes to the progress stream on Generate and renders the live phase + attempt scores', async () => {
+ const finish = pendingGenerate();
+ renderPanel(makeIssue());
+
+ await userEvent.click(screen.getByRole('button', { name: 'Generate' }));
+ await waitFor(() => expect(lastEventSource()).toBeTruthy());
+ expect(lastEventSource().url).toBe('/api/pipeline/issues/iss-1/stages/idea/generate/progress');
+
+ act(() => {
+ lastEventSource().emit({ type: 'start', stageId: 'idea' });
+ lastEventSource().emit({ type: 'phase', phase: 'generate', label: 'Drafting attempt 1 of 2', attempt: 1, attempts: 2 });
+ });
+ expect(await screen.findByText('Drafting…')).toBeInTheDocument();
+ expect(screen.getByText('· attempt 1 of 2')).toBeInTheDocument();
+
+ act(() => {
+ lastEventSource().emit({ type: 'attempt', attempt: 1, attempts: 2, runId: 'run-a', qualityScore: 5.2, outputLength: 1200, ms: 4000 });
+ lastEventSource().emit({ type: 'attempt', attempt: 2, attempts: 2, runId: 'run-b', qualityScore: 8, outputLength: 1400, ms: 3000 });
+ lastEventSource().emit({ type: 'gate', winner: 'run-b', keptScore: 8, ran: 2, attempts: 2, stoppedEarly: false });
+ });
+ expect(screen.getByText('Attempt 1')).toBeInTheDocument();
+ expect(screen.getByText('5.2')).toBeInTheDocument();
+ expect(screen.getByText('8')).toBeInTheDocument();
+ expect(screen.getByText('kept')).toBeInTheDocument();
+ expect(screen.getByText('rejected')).toBeInTheDocument();
+
+ await act(async () => { finish({ status: 'ready', input: '', output: 'ok', runHistory: [] }); });
+ // The stream is torn down once the POST settles, but the scorecard stays.
+ await waitFor(() => expect(lastEventSource().closed).toBe(true));
+ expect(screen.getByText('Attempt 1')).toBeInTheDocument();
+ });
+
+ it('renders an unscored attempt as — rather than 0', async () => {
+ pendingGenerate();
+ renderPanel(makeIssue());
+ await userEvent.click(screen.getByRole('button', { name: 'Generate' }));
+ await waitFor(() => expect(lastEventSource()).toBeTruthy());
+
+ act(() => {
+ lastEventSource().emit({ type: 'attempt', attempt: 1, attempts: 1, runId: 'run-a', qualityScore: null, outputLength: 10, ms: 1000 });
+ });
+ expect(await screen.findByText('—')).toBeInTheDocument();
+ });
+
+ it('still completes generation when the progress stream fails to connect', async () => {
+ const stage = { status: 'ready', input: '', output: 'Generated idea text.', runHistory: [] };
+ generatePipelineStage.mockResolvedValue({ stage });
+ const onStageUpdate = vi.fn();
+ renderPanel(makeIssue(), { onStageUpdate });
+
+ await userEvent.click(screen.getByRole('button', { name: 'Generate' }));
+ // The channel dies immediately — generation is unaffected.
+ act(() => lastEventSource()?.fail(MockEventSource.CLOSED));
+
+ await waitFor(() => expect(onStageUpdate).toHaveBeenCalledWith('idea', stage));
+ expect(toast.success).toHaveBeenCalledWith('Idea generated');
+ });
+ });
});
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index fdca71a467..4fdcbf4139 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -164,6 +164,12 @@ export const generatePipelineStage = (issueId, stageId, opts = {}, options = {})
...options,
});
+// SSE progress stream for the generate call above (#3393). Attaching OPENS the
+// channel server-side, so the caller can subscribe before (or alongside) the
+// POST without racing it. Path only — feed it to `useSseProgress`.
+export const pipelineStageProgressUrl = (issueId, stageId) =>
+ `/api/pipeline/issues/${encodeURIComponent(issueId)}/stages/${encodeURIComponent(stageId)}/generate/progress`;
+
export const generatePipelineVisualImage = (issueId, stageId, opts, options = {}) =>
request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/${encodeURIComponent(stageId)}/visual`, {
method: 'POST',
diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.js
index a7572706cf..3324e774a7 100644
--- a/server/routes/pipeline.test.js
+++ b/server/routes/pipeline.test.js
@@ -666,6 +666,15 @@ describe('pipeline routes', () => {
expect(r.body.code || r.body.error).toBeTruthy();
});
+ // The happy path holds the SSE response open by design, so assert the guard
+ // instead — the channel's own lifecycle is covered by
+ // services/pipeline/textStageProgress.test.js.
+ it('GET /issues/:id/stages/:stageId/generate/progress rejects a non-text stage', async () => {
+ const app = makeApp();
+ const r = await request(app).get('/api/pipeline/issues/iss-1/stages/comicPages/generate/progress');
+ expect(r.status).toBe(400);
+ });
+
describe('POST /issues/:id/stages/:stageId/restore', () => {
it('restores a prior runHistory snapshot and snapshots the displaced current state', async () => {
const app = makeApp();
diff --git a/server/routes/pipeline/index.js b/server/routes/pipeline/index.js
index f33b8d5e90..0f35be23e8 100644
--- a/server/routes/pipeline/index.js
+++ b/server/routes/pipeline/index.js
@@ -16,6 +16,7 @@
* PATCH /issues/:id → Issue
* DELETE /issues/:id → { id }
* POST /issues/:id/stages/:stageId/generate → { issue, stage, runId }
+ * GET /issues/:id/stages/:stageId/generate/progress → SSE (text/event-stream)
* POST /issues/:id/stages/:stageId/visual → { jobId, mode, prompt }
* POST /issues/:id/auto-run-text → { runId, alreadyRunning, sseUrl }
* GET /issues/:id/auto-run-text/progress → SSE (text/event-stream)
diff --git a/server/routes/pipeline/issues.js b/server/routes/pipeline/issues.js
index d4582f063b..5bf187a8ba 100644
--- a/server/routes/pipeline/issues.js
+++ b/server/routes/pipeline/issues.js
@@ -18,6 +18,7 @@ import {
import * as seriesSvc from '../../services/pipeline/series.js';
import * as issuesSvc from '../../services/pipeline/issues.js';
import { generateStage } from '../../services/pipeline/textStages.js';
+import * as textStageProgress from '../../services/pipeline/textStageProgress.js';
import * as autoRunner from '../../services/pipeline/autoRunner.js';
import {
enqueueVisualImage,
@@ -186,6 +187,13 @@ const generateSchema = z.object({
sourceStageIds: z.array(z.enum(issuesSvc.TEXT_STAGE_IDS)).optional(),
});
+// Path params for the text-stage progress stream. The stage must be a text
+// stage — a visual/audio stage has no text-generation channel to attach to.
+const stageProgressParamsSchema = z.object({
+ id: z.string().trim().min(1).max(200),
+ stageId: z.enum(issuesSvc.TEXT_STAGE_IDS),
+});
+
const visualGenerateSchema = z.object({
description: z.string().trim().min(1).max(8000),
// Matched against the series places bible when present.
@@ -433,6 +441,15 @@ router.post('/issues/:id/stages/:stageId/generate', asyncHandler(async (req, res
res.json(result);
}));
+// Live progress for the POST above (#3393). Subscribe-then-trigger: attaching
+// OPENS the channel, so the client can connect before (or concurrently with)
+// the generate POST without racing it — and generation runs unchanged when
+// nobody is listening. See services/pipeline/textStageProgress.js.
+router.get('/issues/:id/stages/:stageId/generate/progress', (req, res) => {
+ const { id, stageId } = validateRequest(stageProgressParamsSchema, req.params);
+ textStageProgress.attachClient(id, stageId, res);
+});
+
// Restore a prior text-stage version from history. See
// issuesSvc.restoreStageFromHistory for the reversibility semantics.
const restoreSchema = z.object({
diff --git a/server/services/pipeline/textStageProgress.js b/server/services/pipeline/textStageProgress.js
new file mode 100644
index 0000000000..3f80670e13
--- /dev/null
+++ b/server/services/pipeline/textStageProgress.js
@@ -0,0 +1,152 @@
+/**
+ * Pipeline — text-stage generation progress channel (#3393).
+ *
+ * `generateStage` can run up to three sequential generate+judge cycles (the
+ * #2169 draft gate), which is minutes of blind spinner in the UI. This module
+ * carries the phase frames for that work.
+ *
+ * Why not `createSseRunner` (the polish.js / autoRunner shape)? That factory
+ * OWNS the run: it mints the runId, fires the work in a detached coordinator,
+ * and the HTTP request that started it returns immediately. Text-stage
+ * generation is the opposite shape — `POST …/stages/:stageId/generate` awaits
+ * the result and returns the finished stage, and every non-route caller
+ * (autoRunner, Series Autopilot, volumeBeatsRunner, tests) calls
+ * `generateStage` directly as a plain promise. So this is the subscribe-first
+ * sibling of that runner: a pub/sub channel over the SAME `sseUtils` wire
+ * primitives (`broadcastSse` / `attachSseClient`) and the same
+ * `SSE_CLEANUP_DELAY_MS` replay window, so the frame format, the late-attach
+ * replay, and the teardown semantics stay identical.
+ *
+ * Lifecycle (the ordering is what removes the race):
+ * 1. The client opens `GET …/generate/progress`. `attachClient` OPENS the
+ * channel when it doesn't exist yet — so the subscriber never 404s on a
+ * run it is about to trigger, and it doesn't matter whether the GET or the
+ * POST reaches the server first.
+ * 2. The client POSTs `…/generate`. `generateStage` pushes frames through
+ * `emitStageProgress`, which is a NO-OP when nobody subscribed.
+ * 3. `finishStageProgress` broadcasts the terminal frame and lets the channel
+ * linger for `SSE_CLEANUP_DELAY_MS` so a late attach still replays it.
+ *
+ * The channel is purely advisory: generation never waits on it, never fails
+ * because of it, and a caller with no subscriber runs byte-for-byte the
+ * pre-#3393 path.
+ */
+
+import { broadcastSse, attachSseClient, SSE_CLEANUP_DELAY_MS } from '../../lib/sseUtils.js';
+
+// A channel opened by a subscriber that never sees a generation start is an
+// abandoned reservation (the POST failed validation, the user navigated away
+// between the GET and the POST, …). Reap it rather than holding the response
+// open forever. Only covers the pre-start window — once frames are flowing the
+// channel lives until its terminal frame, however long generation takes.
+export const CHANNEL_IDLE_MS = 60_000;
+
+// channels: Map<key, { clients[], lastPayload, started, finished, timer }>
+// `timer` is the single owned timeout for this channel — the idle reap before a
+// run starts, then the post-terminal replay eviction. Owning it (rather than
+// calling sseUtils' fire-and-forget closeJobAfterDelay) is what lets a fresh run
+// reclaim a channel that is still inside its replay window.
+const channels = new Map();
+
+/** Channel key for one issue's one text stage. */
+export const channelKey = (issueId, stageId) => `${issueId}::${stageId}`;
+
+const clearTimer = (channel) => {
+ if (channel.timer) {
+ clearTimeout(channel.timer);
+ channel.timer = null;
+ }
+};
+
+// End every attached response and evict the channel — but only when it is still
+// the mapped one, so a replacement opened in the meantime survives.
+const dropChannel = (key, channel) => {
+ clearTimer(channel);
+ for (const c of channel.clients) c.end();
+ if (channels.get(key) === channel) channels.delete(key);
+};
+
+/**
+ * Attach an SSE client, opening the channel when this is the first subscriber.
+ * Always succeeds — the subscribe-then-trigger ordering above depends on it.
+ */
+export function attachClient(issueId, stageId, res) {
+ const key = channelKey(issueId, stageId);
+ let channel = channels.get(key);
+ // A finished channel still inside its replay window belongs to the PREVIOUS
+ // run — a new subscriber is here for the next one, so replace it outright
+ // rather than binding them to a stream that will never emit again.
+ if (channel?.finished) {
+ dropChannel(key, channel);
+ channel = null;
+ }
+ if (!channel) {
+ channel = { clients: [], lastPayload: null, started: false, finished: false, timer: null };
+ channels.set(key, channel);
+ // setTimeout callback — runs outside the request lifecycle, so it must not throw.
+ channel.timer = setTimeout(() => {
+ if (channels.get(key) !== channel || channel.started) return;
+ console.log(`🧹 Text-stage progress — reaped idle channel stage=${stageId} issue=${String(issueId).slice(0, 8)}`);
+ dropChannel(key, channel);
+ }, CHANNEL_IDLE_MS);
+ channel.timer.unref?.();
+ }
+ attachSseClient(channels, key, res);
+ // A subscriber that disconnects before any generation started leaves nothing
+ // to stream — close the reservation instead of waiting out the idle timer.
+ res.req.on('close', () => {
+ if (channels.get(key) !== channel) return;
+ if (!channel.started && channel.clients.length === 0) dropChannel(key, channel);
+ });
+ return true;
+}
+
+/** True when a channel is open for this issue+stage. */
+export const isChannelOpen = (issueId, stageId) => channels.has(channelKey(issueId, stageId));
+
+/**
+ * Broadcast one progress frame. No-op when nothing is subscribed — this is the
+ * whole reason generation never depends on the channel.
+ */
+export function emitStageProgress(issueId, stageId, payload) {
+ const channel = channels.get(channelKey(issueId, stageId));
+ if (!channel) return;
+ // A `start` frame revives a channel still lingering after the previous run's
+ // terminal frame, so a client that stayed attached keeps streaming. Any other
+ // frame type on a finished channel is trailing noise and is dropped.
+ if (channel.finished) {
+ if (payload?.type !== 'start') return;
+ channel.finished = false;
+ clearTimer(channel);
+ }
+ if (!channel.started) {
+ channel.started = true;
+ clearTimer(channel);
+ }
+ broadcastSse(channel, payload);
+}
+
+/**
+ * Broadcast the terminal frame (`complete` / `error`) and schedule teardown.
+ * The channel lingers for the shared grace window so a client that attached
+ * just after the frame shipped still replays it from `lastPayload`.
+ */
+export function finishStageProgress(issueId, stageId, payload) {
+ const key = channelKey(issueId, stageId);
+ const channel = channels.get(key);
+ if (!channel || channel.finished) return;
+ clearTimer(channel);
+ broadcastSse(channel, payload);
+ channel.finished = true;
+ channel.timer = setTimeout(() => dropChannel(key, channel), SSE_CLEANUP_DELAY_MS);
+ channel.timer.unref?.();
+}
+
+// Exported for tests — lets a suite assert channel bookkeeping and reset state.
+export const __testing = {
+ channels,
+ reset: () => {
+ for (const [key, channel] of [...channels]) dropChannel(key, channel);
+ channels.clear();
+ },
+};
diff --git a/server/services/pipeline/textStageProgress.test.js b/server/services/pipeline/textStageProgress.test.js
new file mode 100644
index 0000000000..be3b4a30fb
--- /dev/null
+++ b/server/services/pipeline/textStageProgress.test.js
@@ -0,0 +1,150 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import {
+ attachClient,
+ emitStageProgress,
+ finishStageProgress,
+ isChannelOpen,
+ channelKey,
+ CHANNEL_IDLE_MS,
+ __testing,
+} from './textStageProgress.js';
+
+// Minimal Express `res` stand-in: records the SSE frames written to it and
+// exposes the `req` close hook the attach path registers against.
+function fakeRes() {
+ const closeHandlers = [];
+ return {
+ written: [],
+ ended: false,
+ headers: null,
+ writeHead(status, headers) { this.headers = { status, ...headers }; },
+ write(chunk) { this.written.push(chunk); },
+ end() { this.ended = true; },
+ req: { on: (evt, fn) => { if (evt === 'close') closeHandlers.push(fn); } },
+ fireClose: () => closeHandlers.forEach((fn) => fn()),
+ };
+}
+
+const framesOf = (res) => res.written.map((c) => JSON.parse(c.replace(/^data: /, '').trim()));
+
+describe('text-stage progress channel', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ __testing.reset();
+ });
+ afterEach(() => {
+ __testing.reset();
+ vi.useRealTimers();
+ });
+
+ it('emits are a no-op when nobody is subscribed', () => {
+ expect(isChannelOpen('issue-1', 'prose')).toBe(false);
+ expect(() => emitStageProgress('issue-1', 'prose', { type: 'phase' })).not.toThrow();
+ expect(() => finishStageProgress('issue-1', 'prose', { type: 'complete' })).not.toThrow();
+ expect(__testing.channels.size).toBe(0);
+ });
+
+ it('attaching opens the channel so the subscriber never races the POST', () => {
+ const res = fakeRes();
+ expect(attachClient('issue-1', 'prose', res)).toBe(true);
+ expect(isChannelOpen('issue-1', 'prose')).toBe(true);
+ expect(res.headers.status).toBe(200);
+ expect(res.headers['Content-Type']).toBe('text/event-stream');
+
+ emitStageProgress('issue-1', 'prose', { type: 'phase', phase: 'generate', attempt: 1 });
+ expect(framesOf(res)).toEqual([{ type: 'phase', phase: 'generate', attempt: 1 }]);
+ });
+
+ it('keeps channels separate per issue and per stage', () => {
+ const prose = fakeRes();
+ const script = fakeRes();
+ attachClient('issue-1', 'prose', prose);
+ attachClient('issue-1', 'comicScript', script);
+ emitStageProgress('issue-1', 'prose', { type: 'phase', phase: 'generate' });
+ expect(framesOf(prose)).toHaveLength(1);
+ expect(framesOf(script)).toHaveLength(0);
+ expect(channelKey('issue-1', 'prose')).not.toBe(channelKey('issue-1', 'comicScript'));
+ });
+
+ it('replays the last frame to a client that attaches late', () => {
+ const first = fakeRes();
+ attachClient('issue-1', 'prose', first);
+ emitStageProgress('issue-1', 'prose', { type: 'phase', phase: 'judge' });
+ const late = fakeRes();
+ attachClient('issue-1', 'prose', late);
+ expect(framesOf(late)).toEqual([{ type: 'phase', phase: 'judge' }]);
+ });
+
+ it('a terminal frame ends the stream after the replay grace window', () => {
+ const res = fakeRes();
+ attachClient('issue-1', 'prose', res);
+ emitStageProgress('issue-1', 'prose', { type: 'start' });
+ finishStageProgress('issue-1', 'prose', { type: 'complete', runId: 'run-1' });
+ expect(framesOf(res).at(-1)).toEqual({ type: 'complete', runId: 'run-1' });
+ expect(res.ended).toBe(false);
+ vi.advanceTimersByTime(10_000);
+ expect(res.ended).toBe(true);
+ expect(isChannelOpen('issue-1', 'prose')).toBe(false);
+ });
+
+ it('drops trailing frames after the terminal frame but revives on a new run', () => {
+ const res = fakeRes();
+ attachClient('issue-1', 'prose', res);
+ finishStageProgress('issue-1', 'prose', { type: 'complete' });
+ emitStageProgress('issue-1', 'prose', { type: 'phase', phase: 'canon' });
+ expect(framesOf(res)).toHaveLength(1);
+
+ // A fresh run's `start` reclaims the lingering channel instead of being
+ // swallowed by the previous run's terminal state.
+ emitStageProgress('issue-1', 'prose', { type: 'start' });
+ emitStageProgress('issue-1', 'prose', { type: 'phase', phase: 'generate' });
+ expect(framesOf(res)).toHaveLength(3);
+ vi.advanceTimersByTime(10_000);
+ expect(res.ended).toBe(false);
+ });
+
+ it('a new subscriber replaces a finished channel rather than binding to a dead one', () => {
+ const first = fakeRes();
+ attachClient('issue-1', 'prose', first);
+ finishStageProgress('issue-1', 'prose', { type: 'complete' });
+
+ const next = fakeRes();
+ attachClient('issue-1', 'prose', next);
+ expect(first.ended).toBe(true);
+ expect(framesOf(next)).toHaveLength(0);
+ emitStageProgress('issue-1', 'prose', { type: 'start' });
+ expect(framesOf(next)).toEqual([{ type: 'start' }]);
+ });
+
+ it('reaps a reservation that never sees a generation start', () => {
+ const res = fakeRes();
+ attachClient('issue-1', 'prose', res);
+ vi.advanceTimersByTime(CHANNEL_IDLE_MS + 1);
+ expect(isChannelOpen('issue-1', 'prose')).toBe(false);
+ expect(res.ended).toBe(true);
+ });
+
+ it('does not reap a channel once frames are flowing', () => {
+ const res = fakeRes();
+ attachClient('issue-1', 'prose', res);
+ emitStageProgress('issue-1', 'prose', { type: 'start' });
+ vi.advanceTimersByTime(CHANNEL_IDLE_MS * 3);
+ expect(isChannelOpen('issue-1', 'prose')).toBe(true);
+ expect(res.ended).toBe(false);
+ });
+
+ it('closes a reservation when its only subscriber disconnects before the run starts', () => {
+ const res = fakeRes();
+ attachClient('issue-1', 'prose', res);
+ res.fireClose();
+ expect(isChannelOpen('issue-1', 'prose')).toBe(false);
+ });
+
+ it('keeps the channel alive when a subscriber disconnects mid-run', () => {
+ const res = fakeRes();
+ attachClient('issue-1', 'prose', res);
+ emitStageProgress('issue-1', 'prose', { type: 'start' });
+ res.fireClose();
+ expect(isChannelOpen('issue-1', 'prose')).toBe(true);
+ });
+});
diff --git a/server/services/pipeline/textStages.js b/server/services/pipeline/textStages.js
index 340112db65..2814cc6bb0 100644
--- a/server/services/pipeline/textStages.js
+++ b/server/services/pipeline/textStages.js
@@ -12,10 +12,16 @@
*
* Errors bubble (per project convention — no try/catch) except at the SSE
* boundary in autoRunner.js, which routes failures through a finalizer.
+ *
+ * Progress (#3393): every phase of a run is broadcast through
+ * `textStageProgress.js` so the UI shows attempt/judge progress instead of a
+ * blind spinner. The channel is advisory — when nobody is subscribed every
+ * emit is a no-op and generation is byte-for-byte the un-streamed path.
*/
import { runStagedLLM, resolveStageContext } from '../../lib/stageRunner.js';
import { getStage } from '../promptService.js';
+import { emitStageProgress, finishStageProgress } from './textStageProgress.js';
import { getSeries } from './series.js';
import { extractCanonFromProse, summarizeCanonExtraction } from '../universeCanon.js';
import { getIssue, listIssues, updateStage, assertStageUnlocked, TEXT_STAGE_IDS } from './issues.js';
@@ -704,7 +710,7 @@ async function runStageLLMOnce(issueId, stageId, template, ctx, options) {
* budget exhausted) and keep the best attempt so far. Route callers pass no
* chargeAction, so a manual regenerate is never cos-billed.
*/
-async function runDraftGate({ issueId, stageId, template, ctx, options, gate }) {
+async function runDraftGate({ issueId, stageId, template, ctx, options, gate, emit = () => {} }) {
// Dynamic import breaks the textStages ↔ pipelineJudge require cycle (the judge
// imports scopeCharactersForIssue/stageContentOf from here) and keeps the judge
// out of the module-eval graph for callers that never gate.
@@ -720,16 +726,19 @@ async function runDraftGate({ issueId, stageId, template, ctx, options, gate })
const ok = await options.chargeAction({ attempt: i + 1 });
if (ok === false) {
console.log(`💸 Pipeline draft-gate — issue=${issueId.slice(0, 8)} stage=${stageId} budget exhausted after ${i} attempt(s)`);
+ emit({ type: 'phase', phase: 'budget', label: 'Budget spent — keeping the best draft so far', attempt: i + 1, attempts: gate.attempts });
break;
}
}
const started = Date.now();
+ emit({ type: 'phase', phase: 'generate', label: `Drafting attempt ${i + 1} of ${gate.attempts}`, attempt: i + 1, attempts: gate.attempts });
const res = await runStageLLMOnce(issueId, stageId, template, ctx, options);
last = res;
let qualityScore = null;
let overall = null;
let slopPenalty = null;
if (res.output) {
+ emit({ type: 'phase', phase: 'judge', label: `Judging attempt ${i + 1} of ${gate.attempts}`, attempt: i + 1, attempts: gate.attempts });
const snap = await judgeIssue(issueId, { stageId, force: true }).catch((err) => {
console.warn(`⚠️ Pipeline draft-gate judge failed — issue=${issueId.slice(0, 8)} attempt=${i + 1}: ${err.message}`);
return null;
@@ -742,6 +751,20 @@ async function runDraftGate({ issueId, stageId, template, ctx, options, gate })
}
attempts.push({ runId: res.runId, output: res.output, input: res.stage?.input || '', qualityScore, overall, slopPenalty });
console.log(`🎲 Pipeline draft-gate — issue=${issueId.slice(0, 8)} stage=${stageId} attempt=${i + 1}/${gate.attempts} quality=${qualityScore ?? 'n/a'} in ${Date.now() - started}ms`);
+ emit({
+ type: 'attempt',
+ attempt: i + 1,
+ attempts: gate.attempts,
+ runId: res.runId,
+ // null (not 0) when the judge was unavailable — an unscored attempt is not
+ // a zero-scoring one, and the UI renders the two differently.
+ qualityScore,
+ overall,
+ slopPenalty,
+ threshold: gate.threshold,
+ outputLength: res.output.length,
+ ms: Date.now() - started,
+ });
// Early-stop once a draft clears the configured bar — no point re-rolling.
if (gate.threshold != null && qualityScore != null && qualityScore >= gate.threshold) break;
}
@@ -756,6 +779,7 @@ async function runDraftGate({ issueId, stageId, template, ctx, options, gate })
// restoreStageFromHistory) survives a runHistory cap eviction and keeps the
// 'ready' status. The displaced last attempt is snapshotted back into history.
if (best && last && best.runId !== last.runId) {
+ emit({ type: 'phase', phase: 'restore', label: 'Restoring the best-scoring draft', attempt: attempts.length, attempts: gate.attempts });
const restored = await updateStage(issueId, stageId, {
status: best.output ? 'ready' : 'error',
input: best.input,
@@ -792,6 +816,15 @@ async function runDraftGate({ issueId, stageId, template, ctx, options, gate })
if (stamped && final) final = { issue: stamped.issue, stage: stamped.stage, runId: final.runId, output: final.output };
console.log(`🏁 Pipeline draft-gate — issue=${issueId.slice(0, 8)} stage=${stageId} kept=${best?.qualityScore ?? 'n/a'} from ${attempts.length} attempt(s)${stoppedEarly ? ' (stopped early)' : ''}`);
+ emit({
+ type: 'gate',
+ winner: winnerRunId,
+ keptScore: best?.qualityScore ?? null,
+ ran: attempts.length,
+ attempts: gate.attempts,
+ threshold: gate.threshold,
+ stoppedEarly,
+ });
return final;
}
@@ -800,8 +833,9 @@ async function runDraftGate({ issueId, stageId, template, ctx, options, gate })
// extract usefully. Non-fatal — prose succeeded, and a noisy extract shouldn't
// roll back the user's accepted draft. An orphan series (no universeId) skips
// extraction entirely. Returns the stamped { issue, stage } or null (unchanged).
-async function maybeExtractCanon(issueId, stageId, output, series, options) {
+async function maybeExtractCanon(issueId, stageId, output, series, options, emit = () => {}) {
if (stageId !== 'prose' || !output || !series.universeId) return null;
+ emit({ type: 'phase', phase: 'canon', label: 'Extracting canon from the draft' });
// Canon extraction follows whichever provider/model drove this prose stage —
// the manual route's hard `providerId`/`model` OR Series Autopilot's soft run
// defaults (#1514/#1558). Record only the provider actually forwarded so the
@@ -849,6 +883,37 @@ export async function generateStage(issueId, stageId, options = {}) {
if (!TEXT_STAGE_IDS.includes(stageId)) {
throw new Error(`generateStage: unsupported stageId "${stageId}"`);
}
+ const emit = (payload) => emitStageProgress(issueId, stageId, payload);
+ emit({ type: 'start', issueId, stageId, at: new Date().toISOString() });
+ // Settle to an outcome object rather than try/catch so the terminal frame
+ // ships on BOTH paths before the error resumes bubbling to the caller.
+ const outcome = await runTextStage(issueId, stageId, options, emit)
+ .then((result) => ({ result }), (error) => ({ error }));
+ if (outcome.error) {
+ finishStageProgress(issueId, stageId, {
+ type: 'error',
+ issueId,
+ stageId,
+ error: (outcome.error?.message || String(outcome.error)).slice(0, 1000),
+ failedAt: new Date().toISOString(),
+ });
+ throw outcome.error;
+ }
+ finishStageProgress(issueId, stageId, {
+ type: 'complete',
+ issueId,
+ stageId,
+ runId: outcome.result.runId,
+ outputLength: (outcome.result.stage?.output || '').length,
+ completedAt: new Date().toISOString(),
+ });
+ return outcome.result;
+}
+
+// The generation itself — everything between the `start` and terminal progress
+// frames. Split out of generateStage so the frames wrap the whole run (context
+// build included) without a try/catch around it.
+async function runTextStage(issueId, stageId, options, emit) {
const template = STAGE_TO_TEMPLATE[stageId];
const issue = await getIssue(issueId);
const series = await getSeries(issue.seriesId);
@@ -868,19 +933,24 @@ export async function generateStage(issueId, stageId, options = {}) {
await updateStage(issueId, stageId, { status: 'generating', errorMessage: '' });
+ emit({ type: 'phase', phase: 'context', label: 'Building the prompt context' });
const ctx = await buildGenerationContext({ series, canon, world, issue, stageId, options });
const gate = resolveDraftGate(stageId, template, options);
// Draft gate (opt-in, default off) vs the single-shot path. The single-shot
// path is byte-for-byte the pre-#2169 behavior so a stage with draftAttempts=1
// (the default) is unchanged.
- const result = gate.attempts > 1
- ? await runDraftGate({ issueId, stageId, template, ctx, options, gate })
- : await runStageLLMOnce(issueId, stageId, template, ctx, options);
+ let result;
+ if (gate.attempts > 1) {
+ result = await runDraftGate({ issueId, stageId, template, ctx, options, gate, emit });
+ } else {
+ emit({ type: 'phase', phase: 'generate', label: 'Drafting', attempt: 1, attempts: 1 });
+ result = await runStageLLMOnce(issueId, stageId, template, ctx, options);
+ }
let { issue: updatedIssue, stage } = result;
// Prose canon extraction on the FINAL (winning) output — once, not per attempt.
- const stamped = await maybeExtractCanon(issueId, stageId, result.output, series, options);
+ const stamped = await maybeExtractCanon(issueId, stageId, result.output, series, options, emit);
if (stamped) ({ issue: updatedIssue, stage } = stamped);
return { issue: updatedIssue, stage, runId: result.runId };
diff --git a/server/services/pipeline/textStages.test.js b/server/services/pipeline/textStages.test.js
index 3d8dcf9a2c..62855fcb67 100644
--- a/server/services/pipeline/textStages.test.js
+++ b/server/services/pipeline/textStages.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { readFileSync } from 'fs';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
@@ -83,6 +83,8 @@ const universeSvc = await import('../universeBuilder.js');
const promptSvc = await import('../promptService.js');
const pipelineJudge = await import('./pipelineJudge.js');
const textStages = await import('./textStages.js');
+const textStageProgress = await import('./textStageProgress.js');
+const runnerSvc = await import('../runner.js');
// Strip the `RENDERED:<stage>:` prefix that the mocked buildPrompt prepends
// so the asserted-against context is the bare JSON tree.
@@ -1259,3 +1261,107 @@ describe('multi-candidate draft gate (#2169, CWQE Phase 5)', () => {
expect(result.stage.draftGate).toBeNull();
});
});
+
+describe('text-stage generation progress frames (#3393)', () => {
+ // Minimal Express `res` stand-in for the SSE channel — see
+ // textStageProgress.test.js for the channel's own lifecycle coverage.
+ function fakeRes() {
+ return {
+ written: [],
+ writeHead() {},
+ write(chunk) { this.written.push(chunk); },
+ end() {},
+ req: { on: () => {} },
+ };
+ }
+ const framesOf = (res) => res.written.map((c) => JSON.parse(c.replace(/^data: /, '').trim()));
+
+ beforeEach(() => {
+ fileStore.clear();
+ uuidCounter = 0;
+ llmCalls.length = 0;
+ vi.clearAllMocks();
+ promptSvc.getStage.mockReturnValue(null);
+ pipelineJudge.judgeIssue.mockResolvedValue({ status: 'no-content' });
+ textStageProgress.__testing.reset();
+ });
+ afterEach(() => textStageProgress.__testing.reset());
+
+ async function seedProse() {
+ const series = await seriesSvc.createSeries({ name: 'Stream', logline: 'L', premise: 'P' });
+ const issue = await issuesSvc.createIssue({ seriesId: series.id, title: 'One' });
+ return { series, issue };
+ }
+
+ it('generates normally with nobody subscribed (the channel is never a dependency)', async () => {
+ const { issue } = await seedProse();
+ const result = await textStages.generateStage(issue.id, 'prose', {});
+ expect(result.stage.status).toBe('ready');
+ expect(textStageProgress.isChannelOpen(issue.id, 'prose')).toBe(false);
+ });
+
+ it('streams start → context → generate → complete on the single-shot path', async () => {
+ const { issue } = await seedProse();
+ const res = fakeRes();
+ textStageProgress.attachClient(issue.id, 'prose', res);
+ await textStages.generateStage(issue.id, 'prose', {});
+
+ const frames = framesOf(res);
+ expect(frames.map((f) => f.type)).toEqual(['start', 'phase', 'phase', 'complete']);
+ expect(frames[1].phase).toBe('context');
+ expect(frames[2]).toMatchObject({ phase: 'generate', attempt: 1, attempts: 1 });
+ expect(frames[3]).toMatchObject({ type: 'complete', stageId: 'prose' });
+ expect(frames[3].outputLength).toBeGreaterThan(0);
+ });
+
+ it('streams per-attempt draft-gate progress with the judge score', async () => {
+ promptSvc.getStage.mockReturnValue({ draftAttempts: 2 });
+ let i = 0;
+ pipelineJudge.judgeIssue.mockImplementation(async () => {
+ const q = [5, 8][Math.min(i++, 1)];
+ return { status: 'complete', qualityScore: q, overall: q, slopPenalty: 0 };
+ });
+ const { issue } = await seedProse();
+ const res = fakeRes();
+ textStageProgress.attachClient(issue.id, 'prose', res);
+ await textStages.generateStage(issue.id, 'prose', {});
+
+ const frames = framesOf(res);
+ const generatePhases = frames.filter((f) => f.type === 'phase' && f.phase === 'generate');
+ expect(generatePhases.map((f) => f.attempt)).toEqual([1, 2]);
+ expect(generatePhases.every((f) => f.attempts === 2)).toBe(true);
+ expect(frames.filter((f) => f.type === 'phase' && f.phase === 'judge')).toHaveLength(2);
+
+ const attempts = frames.filter((f) => f.type === 'attempt');
+ expect(attempts.map((f) => f.qualityScore)).toEqual([5, 8]);
+ const gate = frames.find((f) => f.type === 'gate');
+ expect(gate).toMatchObject({ keptScore: 8, ran: 2, attempts: 2, stoppedEarly: false });
+ expect(gate.winner).toBe(attempts[1].runId);
+ expect(frames.at(-1).type).toBe('complete');
+ });
+
+ it('reports an unscored attempt as null rather than 0', async () => {
+ promptSvc.getStage.mockReturnValue({ draftAttempts: 2 });
+ pipelineJudge.judgeIssue.mockResolvedValue({ status: 'no-content' });
+ const { issue } = await seedProse();
+ const res = fakeRes();
+ textStageProgress.attachClient(issue.id, 'prose', res);
+ await textStages.generateStage(issue.id, 'prose', {});
+
+ const attempts = framesOf(res).filter((f) => f.type === 'attempt');
+ expect(attempts).toHaveLength(2);
+ expect(attempts.every((f) => f.qualityScore === null)).toBe(true);
+ });
+
+ it('ships a terminal error frame when generation throws, then rethrows', async () => {
+ const { issue } = await seedProse();
+ const res = fakeRes();
+ textStageProgress.attachClient(issue.id, 'prose', res);
+ runnerSvc.executeApiRun.mockImplementationOnce(async ({ onComplete }) => { onComplete({ error: 'provider exploded' }); });
+
+ await expect(textStages.generateStage(issue.id, 'prose', {})).rejects.toThrow(/provider exploded/);
+ const frames = framesOf(res);
+ expect(frames.at(-1)).toMatchObject({ type: 'error', stageId: 'prose' });
+ expect(frames.at(-1).error).toMatch(/provider exploded/);
+ });
+});