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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: stream live progress while AI writes deck card prompts
Ilya Eivy18b4a16f35e8
diff --git a/client/src/components/decks/DeckRenderControls.jsx b/client/src/components/decks/DeckRenderControls.jsxindex 88116f79f6..29db1c4fcc 100644--- a/client/src/components/decks/DeckRenderControls.jsx+++ b/client/src/components/decks/DeckRenderControls.jsx@@ -35,7 +35,7 @@ const SIZE_BOUNDS = { min: DECK_CARD_SIZE_MIN, max: DECK_CARD_SIZE_MAX, step: 8*/export default function DeckRenderControls({deck, completion, renderTarget, onPatch, onGeneratePrompts, onRenderMissing, onRenderAll,- generating = false, rendering = false,+ generating = false, generatingStatus = null, rendering = false,}) {const { backends, size, summary: renderSummary, localRuntime, blocked: runtimeBlocked } = renderTarget;const total = completion?.total || 0;@@ -100,7 +100,7 @@ export default function DeckRenderControls({/><div className="grid grid-cols-1 gap-3 sm:grid-cols-2">- <Step step="1" title="Prompts" note={promptNote({ generating, unprompted, total })}>+ <Step step="1" title="Prompts" note={promptNote({ generating, generatingStatus, unprompted, total })}>{(noteId) => (<><buttontype="button"@@ -202,9 +202,11 @@ function CardSize({ kind, size, onPatch }) {);}-// What step 1's buttons will do, or why they can't.-const promptNote = ({ generating, unprompted, total }) => {- if (generating) return 'Writing prompts…';+// What step 1's buttons will do, or why they can't. While a run is in flight+// the note is the live progress line (phase + written/requested + batch), so+// a 79-card tarot run that takes minutes names where it is.+const promptNote = ({ generating, generatingStatus, unprompted, total }) => {+ if (generating) return generatingStatus || 'Writing prompts…';if (unprompted) return `${unprompted} of ${pluralize(total, 'card')} still need a prompt.`;return `All ${pluralize(total, 'card')} have a prompt — rewrite to replace them.`;};diff --git a/client/src/components/decks/DeckRenderControls.test.jsx b/client/src/components/decks/DeckRenderControls.test.jsxindex 788086aa50..0360f34615 100644--- a/client/src/components/decks/DeckRenderControls.test.jsx+++ b/client/src/components/decks/DeckRenderControls.test.jsx@@ -181,3 +181,27 @@ describe('DeckRenderControls local runtime', () => {expect(screen.getByRole('button', { name: /^Render all/ })).toBeEnabled();});});++// A prompt run over a 79-card tarot deck takes minutes across several LLM+// calls. The step-1 note is the live progress line while it runs — phase,+// written/requested, and which batch just landed — instead of a bare spinner.+describe('DeckRenderControls prompt progress', () => {+ it('shows the live written/requested counts and batch while a run is in flight', async () => {+ await renderControls({+ generating: true,+ generatingStatus: 'Writing prompts… 24 of 79 · batch 2 of 7',+ });+ expect(screen.getByText('Writing prompts… 24 of 79 · batch 2 of 7')).toBeInTheDocument();+ });++ it('names the casting phase before the first prompt chunk lands', async () => {+ await renderControls({ generating: true, generatingStatus: 'Casting the universe onto the cards…' });+ expect(screen.getByText('Casting the universe onto the cards…')).toBeInTheDocument();+ });++ it('falls back to the spinner copy with no status line', async () => {+ await renderControls({ generating: true, generatingStatus: null });+ // The button carries the same copy — pin the step note paragraph.+ expect(screen.getByText('Writing prompts…', { selector: 'p' })).toBeInTheDocument();+ });+});diff --git a/client/src/pages/DeckDetail.jsx b/client/src/pages/DeckDetail.jsxindex 98be40ceab..38b01ac3d9 100644--- a/client/src/pages/DeckDetail.jsx+++ b/client/src/pages/DeckDetail.jsx@@ -36,10 +36,11 @@ import useMounted from '../hooks/useMounted';import useUrlParams from '../hooks/useUrlParams';import useHydratedPreviewRoute from '../hooks/useHydratedPreviewRoute';import useFieldDraft from '../hooks/useFieldDraft';+import { useSseProgress } from '../hooks/useSseProgress';import { DECK_KIND_LABELS, cardInFlightJobId, composeCardRenderPrompt, deckCompletion } from '../lib/decks';import {deleteDeck, generateDeckPrompts, getDeck, listUniverseSummaries, removeDeckSample,- renderDeckCard, renderDeckCards, updateDeck, updateDeckCard,+ renderDeckCard, renderDeckCards, updateDeck, updateDeckCard, deckPromptsProgressUrl,} from '../services/api';const TABS = [{ id: 'cards', label: 'Cards' }, { id: 'style', label: 'Style & samples' }];@@ -65,6 +66,14 @@ function DeckEditor({ id }) {const [generating, setGenerating] = useState(false);const [rendering, setRendering] = useState(false);const [savingCard, setSavingCard] = useState(false);+ // Live prompt-writing progress. The URL is set for the duration of one+ // generate call and subscribes CONCURRENTLY with the POST (setting state+ // commits after the POST leaves) — the server opens the channel on attach,+ // so no frame is lost to the race, and with no EventSource the page falls+ // back to the spinner. Frames survive the teardown; the status line below+ // only reads them while `generating` is true.+ const [promptProgressUrl, setPromptProgressUrl] = useState(null);+ const { frames: promptFrames } = useSseProgress(promptProgressUrl, { enabled: !!promptProgressUrl });const loadSeqRef = useRef(0);// Resolved once for the page: the render bar names these options, the grid's// per-card re-render button renders on them, and both stand down together on@@ -169,17 +178,70 @@ function DeckEditor({ id }) {const generatePrompts = async ({ overwrite }) => {setGenerating(true);+ // Subscribe to the progress stream first. Purely advisory — an+ // environment without EventSource just falls back to the spinner.+ setPromptProgressUrl(null);+ if (typeof EventSource !== 'undefined') setPromptProgressUrl(deckPromptsProgressUrl(id));const result = await generateDeckPrompts(id, { overwrite }, { silent: true }).catch((err) => {toast.error(`Prompt generation failed: ${err.message}`);return null;});if (!mountedRef.current) return;+ // Close the stream once the POST has settled — the terminal frame has+ // already landed, and the frames stay rendered until the next run.+ setPromptProgressUrl(null);setGenerating(false);if (!result) return;setDeck(result.deck);toast.success(`${result.written} prompt${result.written === 1 ? '' : 's'} written${result.cast ? `, ${result.cast} cards cast from the universe` : ''}`);};+ // Each persisted chunk refetches the deck so freshly written prompts land+ // in the grid while the run is still going — not just when the POST+ // settles. The server persists every chunk before emitting its frame, so a+ // refetch on that frame always has something new to show.+ const lastChunkSeen = useRef(0);+ useEffect(() => {+ if (!generating || !promptFrames.length) return undefined;+ const latest = promptFrames[promptFrames.length - 1];+ if (latest?.type !== 'chunk' || promptFrames.length <= lastChunkSeen.current) return undefined;+ lastChunkSeen.current = promptFrames.length;+ let active = true;+ getDeck(id, { silent: true }).then((data) => {+ if (active && mountedRef.current && data) setDeck(data);+ }).catch(() => {});+ return () => { active = false; };+ }, [promptFrames, generating, id, mountedRef]);++ // One live line for step 1 while a run is in flight: which phase, how many+ // prompts are written of how many requested, and which batch just landed.+ // Null when idle — the step note then falls back to the deck counts.+ const generatingStatus = useMemo(() => {+ if (!generating) return null;+ let phaseLabel = null;+ let written = null;+ let requested = null;+ let chunk = null;+ let chunks = null;+ for (const f of promptFrames) {+ if (f?.type === 'phase' && f.label) phaseLabel = f.label;+ else if (f?.type === 'start') {+ if (Number.isFinite(f.requested)) requested = f.requested;+ if (Number.isFinite(f.chunks)) chunks = f.chunks;+ } else if (f?.type === 'chunk') {+ if (Number.isFinite(f.written)) written = f.written;+ if (Number.isFinite(f.requested)) requested = f.requested;+ if (Number.isFinite(f.chunk)) chunk = f.chunk;+ if (Number.isFinite(f.chunks)) chunks = f.chunks;+ }+ }+ // Casting runs before the first prompt chunk — name the phase, not a 0/N.+ if (written === null && phaseLabel) return phaseLabel;+ if (written === null || requested === null) return 'Writing prompts…';+ const batch = chunk !== null && chunks !== null ? ` · batch ${chunk} of ${chunks}` : '';+ return `Writing prompts… ${written} of ${requested}${batch}`;+ }, [generating, promptFrames]);+const saveCard = async (patch) => {if (!selectedCard) return;setSavingCard(true);@@ -306,6 +368,7 @@ function DeckEditor({ id }) {onRenderMissing={() => renderBatch({ onlyMissing: true }, 'Render missing')}onRenderAll={() => renderBatch({}, 'Render whole deck')}generating={generating}+ generatingStatus={generatingStatus}rendering={rendering}/>diff --git a/client/src/services/README.md b/client/src/services/README.mdindex d785f74f6c..b17ec64b98 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -106,7 +106,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiLoraTraining.js` | Character LoRA training — datasets (CRUD, upload, generate, slice, caption), training runs (start/list/cancel + status), character→LoRA link lookup. || `apiMedia.js` | Screenshots + media assets. Also owns the multi-file upload orchestration — `processScreenshotUploads` / `processAttachmentUploads` — moved from `utils/fileUpload.js` since they perform network I/O, not pure transforms. `utils/fileUpload.js` keeps only the pure helpers/constants and no longer re-exports these. || `apiMediaJobs.js` | Media generation job tracking + `refineMediaPrompt` / `promptFromMedia` (vision reverse-prompt). |-| `apiDecks.js` | Decks (playing-card / tarot designer) — deck + card CRUD, sample-design style analysis, universe casting + prompt generation, single/batch card renders. |+| `apiDecks.js` | Decks (playing-card / tarot designer) — deck + card CRUD, sample-design style analysis, universe casting + prompt generation (plus its SSE progress URL), single/batch card renders. || `apiCreativeDirector.js` | Creative Director (video production). || `apiCreativeCommission.js` | Creative Commissions (Autonomous Creation Engine — standing recurring briefs). || `apiFableLoom.js` | FableLoom branching narratives — loom/episode/scene-node/transition CRUD, deterministic graph validation, AI authoring lanes, and the bounded editorial/playthrough autopilot lifecycle. |diff --git a/client/src/services/apiDecks.js b/client/src/services/apiDecks.jsindex fab8b4d50e..65258b9d32 100644--- a/client/src/services/apiDecks.js+++ b/client/src/services/apiDecks.js@@ -41,6 +41,12 @@ export const removeDeckSample = (id, sampleId, options) =>export const generateDeckPrompts = (id, body = {}, options) =>request(`/decks/${encodeURIComponent(id)}/generate-prompts`, { ...json('POST', body), ...options });+// SSE progress stream for the generate call above. 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 deckPromptsProgressUrl = (id) =>+ `/api/decks/${encodeURIComponent(id)}/generate-prompts/progress`;+// Batch render — `{ cardIds?, onlyMissing?, mode?, model?, seed? }` →// `{ mode, jobs: [{ cardId, key, jobId }], skipped }`.export const renderDeckCards = (id, body = {}, options) =>diff --git a/docs/API.md b/docs/API.mdindex 665a0c4e11..251f2bcbff 100644--- a/docs/API.md+++ b/docs/API.md@@ -668,6 +668,7 @@ Playing-card / tarot deck designer (Create → Decks). Decks are db-primary and| POST | `/decks/:id/samples` | Persist a reviewed sample; `adopt` applies the proposal in the same write || DELETE | `/decks/:id/samples/:sampleId` | Remove a sample || POST | `/decks/:id/generate-prompts` | Cast a linked universe onto the cards, then write subject prompts (`cardIds`, `overwrite`, `cast`, provider/model/effort) |+| GET | `/decks/:id/generate-prompts/progress` | SSE stream of the prompt run (`start` → per-chunk `written`/`requested` → `complete`/`error`); subscribe before the POST, no-op when nobody listens || POST | `/decks/:id/render` | Queue card renders through the media queue (`cardIds`, `onlyMissing`, `mode`, `model`, `seed`) || POST | `/decks/:id/cards/:cardId/render` | Queue one card |diff --git a/server/routes/decks.js b/server/routes/decks.jsindex 226e27f791..170900e522 100644--- a/server/routes/decks.js+++ b/server/routes/decks.js@@ -22,6 +22,7 @@ import {} from '../lib/deckValidation.js';import { resolveGalleryImageOrThrow } from './universeBuilder/shared.js';import { resolveLlmRoutePin } from '../lib/llmRoutePin.js';+import { attachClient as attachPromptProgressClient, emitPromptProgress, finishPromptProgress } from '../services/deckPromptProgress.js';// Services load on first request, not at route-module import: the deck graph// reaches the DB, the prompt runner and the media queue, none of which a@@ -109,7 +110,7 @@ router.delete('/:id/samples/:sampleId', asyncHandler(async (req, res) => {// re-shuffle an assignment the user already accepted.router.post('/:id/generate-prompts', asyncHandler(async (req, res) => {const body = validateRequest(deckGeneratePromptsSchema, req.body ?? {});- const [{ getDeck, applyCardGenerations }, { castDeckFromUniverse, generateDeckCardPrompts }] = await Promise.all([decks(), prompts()]);+ const [{ getDeck, applyCardGenerations }, { castDeckFromUniverse, generateDeckCardPrompts, PROMPTS_PER_CALL }] = await Promise.all([decks(), prompts()]);const deck = await getDeck(deckId(req));// Per-call choice over the deck's stored pin; a provider switch drops the// pinned model/effort rather than carrying them across providers.@@ -124,38 +125,77 @@ router.post('/:id/generate-prompts', asyncHandler(async (req, res) => {});}+ // Live progress for this run (see services/deckPromptProgress.js).+ // Subscribe-then-trigger: the client's GET opens the channel, so it can+ // connect before (or concurrently with) this POST without racing it — and+ // every emit below is an advisory no-op when nobody is listening. The+ // terminal frame ships on both the success and the error path.+ const emit = (payload) => emitPromptProgress(deck.id, payload);+ const finish = (payload) => finishPromptProgress(deck.id, payload);+let universe = null;let cast = null;- if (deck.universeId) {- const { getUniverse } = await import('../services/universeBuilder.js');- universe = await getUniverse(deck.universeId).catch(() => null);- if (universe && body.cast && roster.some((c) => targetIds.has(c.id) && !c.canonRef)) {- cast = await castDeckFromUniverse({ deck, cards: roster, universe, ...llm });- // Only cards not yet cast take an assignment; a user-accepted link stays.- const uncast = new Set(roster.filter((c) => !c.canonRef).map((c) => c.id));- const applied = new Map(cast.assignments.filter((a) => uncast.has(a.cardId)).map((a) => [a.cardId, a.canonRef]));- await applyCardGenerations(deck.id, [...applied].map(([cardId, canonRef]) => ({ cardId, canonRef })));- roster = roster.map((c) => (applied.has(c.id) ? { ...c, canonRef: applied.get(c.id) } : c));+ try {+ if (deck.universeId) {+ const { getUniverse } = await import('../services/universeBuilder.js');+ universe = await getUniverse(deck.universeId).catch(() => null);+ if (universe && body.cast && roster.some((c) => targetIds.has(c.id) && !c.canonRef)) {+ emit({ type: 'phase', deckId: deck.id, phase: 'casting', label: 'Casting the universe onto the cards…' });+ cast = await castDeckFromUniverse({ deck, cards: roster, universe, ...llm });+ // Only cards not yet cast take an assignment; a user-accepted link stays.+ const uncast = new Set(roster.filter((c) => !c.canonRef).map((c) => c.id));+ const applied = new Map(cast.assignments.filter((a) => uncast.has(a.cardId)).map((a) => [a.cardId, a.canonRef]));+ await applyCardGenerations(deck.id, [...applied].map(([cardId, canonRef]) => ({ cardId, canonRef })));+ roster = roster.map((c) => (applied.has(c.id) ? { ...c, canonRef: applied.get(c.id) } : c));+ emit({ type: 'phase', deckId: deck.id, phase: 'cast', label: 'Casting done — writing prompts…', assigned: cast.assignments.filter((a) => a.canonRef).length });+ }}+ const targets = roster.filter((c) => targetIds.has(c.id));+ const perCall = Number.isFinite(PROMPTS_PER_CALL) && PROMPTS_PER_CALL > 0 ? PROMPTS_PER_CALL : 12;+ const chunks = Math.max(1, Math.ceil(targets.length / perCall));+ emit({ type: 'start', deckId: deck.id, requested: targets.length, chunks, at: new Date().toISOString() });++ // Prompts persist chunk by chunk, so a chunk that fails mid-deck (a model+ // that returns bad JSON on its third call) leaves the earlier cards written.+ let appliedCount = 0;+ let chunkIndex = 0;+ const byId = new Map(targets.map((c) => [c.id, c]));+ const generated = await generateDeckCardPrompts({+ deck, roster, targets, universe, ...llm,+ onChunk: async (chunk) => {+ appliedCount += await applyCardGenerations(deck.id, chunk);+ chunkIndex += 1;+ emit({+ type: 'chunk', deckId: deck.id, chunk: chunkIndex, chunks,+ written: appliedCount, requested: targets.length,+ keys: chunk.map((e) => byId.get(e.cardId)?.key || null).filter(Boolean),+ });+ },+ });+ finish({+ type: 'complete', deckId: deck.id, written: appliedCount, requested: targets.length,+ completedAt: new Date().toISOString(),+ });+ res.json({+ deck: await getDeck(deck.id),+ written: appliedCount,+ requested: targets.length,+ cast: cast ? cast.assignments.filter((a) => a.canonRef).length : 0,+ llm: generated.llm,+ });+ } catch (error) {+ finish({ type: 'error', deckId: deck.id, error: (error?.message || String(error)).slice(0, 1000) });+ throw error;}- const targets = roster.filter((c) => targetIds.has(c.id));-- // Prompts persist chunk by chunk, so a chunk that fails mid-deck (a model- // that returns bad JSON on its third call) leaves the earlier cards written.- let applied = 0;- const generated = await generateDeckCardPrompts({- deck, roster, targets, universe, ...llm,- onChunk: async (chunk) => { applied += await applyCardGenerations(deck.id, chunk); },- });- res.json({- deck: await getDeck(deck.id),- written: applied,- requested: targets.length,- cast: cast ? cast.assignments.filter((a) => a.canonRef).length : 0,- llm: generated.llm,- });}));+// Live progress for the POST above. Attaching OPENS the channel, so the+// client can subscribe before (or concurrently with) the generate POST+// without racing it — and generation runs unchanged when nobody listens.+router.get('/:id/generate-prompts/progress', (req, res) => {+ attachPromptProgressClient(deckId(req), res);+});+router.post('/:id/render', asyncHandler(async (req, res) => {const body = validateRequest(deckRenderSchema, req.body ?? {});const { renderDeckCards } = await render();diff --git a/server/routes/decks.test.js b/server/routes/decks.test.jsindex f05d90c4b5..e3468c18b7 100644--- a/server/routes/decks.test.js+++ b/server/routes/decks.test.js@@ -20,10 +20,16 @@ vi.mock('../services/decks.js', () => ({}));vi.mock('../services/deckStyleAnalysis.js', () => ({ analyzeDeckSample: vi.fn() }));vi.mock('../services/deckPrompts.js', () => ({+ PROMPTS_PER_CALL: 12,castDeckFromUniverse: vi.fn(),generateDeckCardPrompts: vi.fn(),}));vi.mock('../services/deckRender.js', () => ({ renderDeckCards: vi.fn() }));+vi.mock('../services/deckPromptProgress.js', () => ({+ attachClient: vi.fn(() => true),+ emitPromptProgress: vi.fn(),+ finishPromptProgress: vi.fn(),+}));vi.mock('../services/universeBuilder.js', () => ({ getUniverse: vi.fn() }));vi.mock('./universeBuilder/shared.js', () => ({resolveGalleryImageOrThrow: vi.fn((f) => ({ imageFilename: f, imagePath: `/abs/${f}` })),@@ -32,6 +38,7 @@ vi.mock('./universeBuilder/shared.js', () => ({import * as svc from '../services/decks.js';import { analyzeDeckSample } from '../services/deckStyleAnalysis.js';import { castDeckFromUniverse, generateDeckCardPrompts } from '../services/deckPrompts.js';+import { attachClient, emitPromptProgress, finishPromptProgress } from '../services/deckPromptProgress.js';import { renderDeckCards } from '../services/deckRender.js';import { getUniverse } from '../services/universeBuilder.js';import deckRoutes from './decks.js';@@ -140,6 +147,34 @@ describe('deck routes', () => {expect(generateDeckCardPrompts).not.toHaveBeenCalled();});+ it('generate-prompts streams start/chunk/complete progress frames', async () => {+ const res = await request(makeApp()).post(`/api/decks/${D1}/generate-prompts`).send({});+ expect(res.status).toBe(200);+ expect(emitPromptProgress).toHaveBeenCalledWith(D1, expect.objectContaining({ type: 'start', requested: 2 }));+ expect(emitPromptProgress).toHaveBeenCalledWith(D1, expect.objectContaining({+ type: 'chunk', chunk: 1, written: 1, requested: 2, keys: [C0],+ }));+ expect(finishPromptProgress).toHaveBeenCalledWith(D1, expect.objectContaining({+ type: 'complete', written: 1, requested: 2,+ }));+ });++ it('generate-prompts finishes with an error frame when the run throws', async () => {+ generateDeckCardPrompts.mockRejectedValueOnce(new Error('model blew up'));+ const res = await request(makeApp()).post(`/api/decks/${D1}/generate-prompts`).send({});+ expect(res.status).toBe(500);+ expect(finishPromptProgress).toHaveBeenCalledWith(D1, expect.objectContaining({ type: 'error' }));+ });++ it('generate-prompts/progress attaches the deck channel', async () => {+ // The real handler holds the SSE stream open; end it from the mock so+ // the request settles.+ attachClient.mockImplementationOnce((_id, res) => { res.status(200).end(); return true; });+ const res = await request(makeApp()).get(`/api/decks/${D1}/generate-prompts/progress`);+ expect(attachClient).toHaveBeenCalledWith(D1, expect.anything());+ expect(res.status).toBe(200);+ });+it('single-card render narrows the batch to that card', async () => {renderDeckCards.mockResolvedValueOnce({ mode: 'local', jobs: [], skipped: 0 });const res = await request(makeApp()).post(`/api/decks/${D1}/cards/${C0}/render`).send({ mode: 'local' });diff --git a/server/services/deckPromptProgress.js b/server/services/deckPromptProgress.jsnew file mode 100644index 0000000000..47009391df--- /dev/null+++ b/server/services/deckPromptProgress.js@@ -0,0 +1,137 @@+/**+ * Deck prompt-writing progress channel.+ *+ * `POST /decks/:id/generate-prompts` writes a 79-card tarot deck in ~7+ * sequential LLM calls with no realtime feedback — the client sat on+ * "Writing prompts…" until the whole POST settled. This module carries the+ * per-chunk frames for that work.+ *+ * This is the subscribe-first sibling of the pipeline text-stage channel+ * (`services/pipeline/textStageProgress.js`): same `sseUtils` wire primitives+ * (`broadcastSse` / `attachSseClient`), same lifecycle —+ * 1. The client opens `GET /decks/:id/generate-prompts/progress`.+ * `attachClient` OPENS the channel when it doesn't exist yet, so the+ * subscriber never 404s on a run it is about to trigger.+ * 2. The client POSTs `…/generate-prompts`. The route pushes frames through+ * `emitPromptProgress`, which is a NO-OP when nobody subscribed.+ * 3. `finishPromptProgress` broadcasts the terminal frame and lets the+ * channel linger for `SSE_CLEANUP_DELAY_MS` so a late attach replays it.+ *+ * The channel is purely advisory: generation never waits on it, never fails+ * because of it, and a caller with no subscriber runs the pre-change path.+ */++import { broadcastSse, attachSseClient, SSE_CLEANUP_DELAY_MS } from '../lib/sseUtils.js';++// Same abandoned-reservation reap as the text-stage sibling: a channel opened+// by a subscriber that never sees a generation start (POST failed validation,+// navigation between GET and POST, …) is closed rather than held open forever.+// Only covers the pre-start window — once frames flow the channel lives until+// its terminal frame, however long generation takes.+export const CHANNEL_IDLE_MS = 60_000;++// channels: Map<deckId, { 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 lets a fresh+// run reclaim a channel still inside its replay window.+const channels = new Map();++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 depends on it.+ */+export function attachClient(deckId, res) {+ const key = String(deckId);+ 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(`🧹 Deck prompt progress — reaped idle channel deck=${String(deckId).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 deck. */+export const isChannelOpen = (deckId) => channels.has(String(deckId));++/**+ * Broadcast one progress frame. No-op when nothing is subscribed — this is+ * the whole reason generation never depends on the channel.+ */+export function emitPromptProgress(deckId, payload) {+ const channel = channels.get(String(deckId));+ 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 finishPromptProgress(deckId, payload) {+ const key = String(deckId);+ 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/deckPromptProgress.test.js b/server/services/deckPromptProgress.test.jsnew file mode 100644index 0000000000..72bde341c6--- /dev/null+++ b/server/services/deckPromptProgress.test.js@@ -0,0 +1,95 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import {+ attachClient,+ emitPromptProgress,+ finishPromptProgress,+ isChannelOpen,+ CHANNEL_IDLE_MS,+ __testing,+} from './deckPromptProgress.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('deck prompt progress channel', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ __testing.reset();+ });+ afterEach(() => {+ __testing.reset();+ vi.useRealTimers();+ });++ it('emits are a no-op when nobody is subscribed', () => {+ expect(isChannelOpen('deck-1')).toBe(false);+ expect(() => emitPromptProgress('deck-1', { type: 'chunk' })).not.toThrow();+ expect(() => finishPromptProgress('deck-1', { 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('deck-1', res)).toBe(true);+ expect(isChannelOpen('deck-1')).toBe(true);+ expect(res.headers.status).toBe(200);+ expect(res.headers['Content-Type']).toBe('text/event-stream');++ emitPromptProgress('deck-1', { type: 'chunk', written: 12, requested: 79 });+ expect(framesOf(res)).toEqual([{ type: 'chunk', written: 12, requested: 79 }]);+ });++ it('keeps channels separate per deck', () => {+ const first = fakeRes();+ const second = fakeRes();+ attachClient('deck-1', first);+ attachClient('deck-2', second);+ emitPromptProgress('deck-1', { type: 'chunk', written: 1, requested: 2 });+ expect(framesOf(first)).toHaveLength(1);+ expect(framesOf(second)).toHaveLength(0);+ });++ it('a terminal frame ends the stream after the replay grace window', () => {+ const res = fakeRes();+ attachClient('deck-1', res);+ emitPromptProgress('deck-1', { type: 'start', requested: 79 });+ finishPromptProgress('deck-1', { type: 'complete', written: 79, requested: 79 });+ expect(framesOf(res).at(-1)).toEqual({ type: 'complete', written: 79, requested: 79 });+ expect(res.ended).toBe(false);+ vi.advanceTimersByTime(10_000);+ expect(res.ended).toBe(true);+ expect(isChannelOpen('deck-1')).toBe(false);+ });++ it('reaps a reservation that never sees a generation start', () => {+ const res = fakeRes();+ attachClient('deck-1', res);+ vi.advanceTimersByTime(CHANNEL_IDLE_MS + 1);+ expect(isChannelOpen('deck-1')).toBe(false);+ expect(res.ended).toBe(true);+ });++ it('does not reap a channel once frames are flowing', () => {+ const res = fakeRes();+ attachClient('deck-1', res);+ emitPromptProgress('deck-1', { type: 'start', requested: 79 });+ vi.advanceTimersByTime(CHANNEL_IDLE_MS * 3);+ expect(isChannelOpen('deck-1')).toBe(true);+ expect(res.ended).toBe(false);+ });+});