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

fix: preserve deck prompt progress across runs

[._.]/ Adam Eivy0c49ec22e713
diff --git a/client/src/pages/DeckDetail.jsx b/client/src/pages/DeckDetail.jsx
index 38b01ac3d9..618d2f3b32 100644
--- a/client/src/pages/DeckDetail.jsx
+++ b/client/src/pages/DeckDetail.jsx
@@ -66,13 +66,12 @@ 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 lastChunkSeen = useRef(0);
+ // Live prompt-writing progress. The URL is set for the duration of one
+ // generate call. The server reserves the channel on POST arrival and retains
+ // each frame until attach, so starting the POST before React's EventSource
+ // effect runs cannot drop progress.
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
@@ -178,8 +177,9 @@ 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.
+ lastChunkSeen.current = 0;
+ // Start the advisory progress stream alongside the POST. The server
+ // reserves the channel at POST arrival and replays late frames.
setPromptProgressUrl(null);
if (typeof EventSource !== 'undefined') setPromptProgressUrl(deckPromptsProgressUrl(id));
const result = await generateDeckPrompts(id, { overwrite }, { silent: true }).catch((err) => {
@@ -187,8 +187,8 @@ function DeckEditor({ id }) {
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.
+ // Close the stream once the POST has settled — frames stay rendered until
+ // the next run, when the chunk counter is reset above.
setPromptProgressUrl(null);
setGenerating(false);
if (!result) return;
@@ -200,7 +200,6 @@ function DeckEditor({ id }) {
// 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];
diff --git a/client/src/pages/DeckDetail.promptProgress.test.jsx b/client/src/pages/DeckDetail.promptProgress.test.jsx
new file mode 100644
index 0000000000..d8acd60a66
--- /dev/null
+++ b/client/src/pages/DeckDetail.promptProgress.test.jsx
@@ -0,0 +1,123 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { MemoryRouter, Route, Routes } from 'react-router';
+import DeckDetail from './DeckDetail';
+import { MockEventSource } from '../test/mockEventSource';
+
+const api = vi.hoisted(() => ({ getDeck: vi.fn(), generateDeckPrompts: vi.fn() }));
+
+vi.mock('../services/api', () => ({
+ deleteDeck: vi.fn(),
+ deckPromptsProgressUrl: (id) => `/api/decks/${encodeURIComponent(id)}/generate-prompts/progress`,
+ generateDeckPrompts: (...args) => api.generateDeckPrompts(...args),
+ getDeck: (...args) => api.getDeck(...args),
+ listUniverseSummaries: vi.fn().mockResolvedValue([]),
+ removeDeckSample: vi.fn(),
+ renderDeckCard: vi.fn(),
+ renderDeckCards: vi.fn(),
+ updateDeck: vi.fn(),
+ updateDeckCard: vi.fn(),
+}));
+vi.mock('../services/apiImageVideo', () => ({ getGalleryImages: vi.fn(), getVideoHistoryItem: vi.fn() }));
+vi.mock('../components/media/MediaPreview', () => ({ default: () => null }));
+vi.mock('../components/decks/DeckRenderControls', () => ({
+ default: ({ onGeneratePrompts, generatingStatus }) => (
+ <div>
+ <button type="button" onClick={() => onGeneratePrompts({ overwrite: false })}>Generate prompts</button>
+ {generatingStatus ? <div role="status">{generatingStatus}</div> : null}
+ </div>
+ ),
+}));
+vi.mock('../components/decks/DeckCardGrid', () => ({ default: () => null }));
+vi.mock('../components/decks/DeckCardDrawer', () => ({ default: () => null }));
+vi.mock('../components/decks/DeckStylePanel', () => ({ default: () => null }));
+vi.mock('../hooks/useDeckRenderTarget', () => ({ default: () => ({ summary: '', blocked: false }) }));
+
+const deck = {
+ id: 'deck-example',
+ name: 'Example Deck',
+ kind: 'playing',
+ universeId: null,
+ influences: { embrace: [], avoid: [] },
+ cardSize: { width: 1096, height: 1536 },
+ samples: [],
+ cards: [{
+ id: 'card-example', key: 'hearts-ace', name: 'Ace of Hearts', group: 'suit', groupLabel: 'Hearts',
+ prompt: '', negativePrompt: '', imageRefs: [], primaryImageRef: null, render: null, canonRef: null,
+ }],
+};
+
+const deferred = () => {
+ let resolve;
+ const promise = new Promise((done) => { resolve = done; });
+ return { promise, resolve };
+};
+
+const renderPage = async () => {
+ render(
+ <MemoryRouter initialEntries={['/decks/deck-example']}>
+ <Routes><Route path="/decks/:id" element={<DeckDetail />} /></Routes>
+ </MemoryRouter>,
+ );
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Generate prompts' })).toBeInTheDocument());
+};
+
+const emit = async (source, frame) => act(async () => { source.emit(frame); });
+
+beforeEach(() => {
+ MockEventSource.reset();
+ global.EventSource = MockEventSource;
+ api.getDeck.mockReset().mockResolvedValue(deck);
+ api.generateDeckPrompts.mockReset();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ delete global.EventSource;
+});
+
+describe('DeckDetail prompt progress', () => {
+ it('refreshes chunks on each later run', async () => {
+ const firstRun = deferred();
+ const secondRun = deferred();
+ api.generateDeckPrompts.mockReturnValueOnce(firstRun.promise).mockReturnValueOnce(secondRun.promise);
+ await renderPage();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Generate prompts' }));
+ expect(MockEventSource.instances).toHaveLength(1);
+ expect(api.generateDeckPrompts).toHaveBeenCalledTimes(1);
+
+ const firstSource = MockEventSource.instances[0];
+ await act(async () => { firstSource.onopen?.(); });
+ expect(api.generateDeckPrompts).toHaveBeenCalledTimes(1);
+ await emit(firstSource, { type: 'start', requested: 24, chunks: 2 });
+ await emit(firstSource, { type: 'chunk', written: 12, requested: 24, chunk: 1, chunks: 2 });
+ await waitFor(() => expect(api.getDeck).toHaveBeenCalledTimes(2));
+ await emit(firstSource, { type: 'chunk', written: 24, requested: 24, chunk: 2, chunks: 2 });
+ await waitFor(() => expect(api.getDeck).toHaveBeenCalledTimes(3));
+ await emit(firstSource, { type: 'complete', written: 24, requested: 24 });
+ await act(async () => { firstRun.resolve({ deck, written: 24, cast: 0 }); });
+
+ fireEvent.click(screen.getByRole('button', { name: 'Generate prompts' }));
+ expect(MockEventSource.instances).toHaveLength(2);
+ const secondSource = MockEventSource.instances[1];
+ await act(async () => { secondSource.onopen?.(); });
+ expect(api.generateDeckPrompts).toHaveBeenCalledTimes(2);
+ await emit(secondSource, { type: 'start', requested: 12, chunks: 1 });
+ await emit(secondSource, { type: 'chunk', written: 12, requested: 12, chunk: 1, chunks: 1 });
+ await waitFor(() => expect(api.getDeck).toHaveBeenCalledTimes(4));
+ await emit(secondSource, { type: 'complete', written: 12, requested: 12 });
+ await act(async () => { secondRun.resolve({ deck, written: 12, cast: 0 }); });
+ });
+
+ it('continues generation when EventSource is unavailable', async () => {
+ const run = deferred();
+ api.generateDeckPrompts.mockReturnValue(run.promise);
+ await renderPage();
+
+ delete global.EventSource;
+ fireEvent.click(screen.getByRole('button', { name: 'Generate prompts' }));
+ expect(api.generateDeckPrompts).toHaveBeenCalledTimes(1);
+ await act(async () => { run.resolve({ deck, written: 1, cast: 0 }); });
+ });
+});
diff --git a/server/routes/decks.js b/server/routes/decks.js
index 170900e522..f25c718778 100644
--- a/server/routes/decks.js
+++ b/server/routes/decks.js
@@ -22,7 +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';
+import { attachClient as attachPromptProgressClient, beginPromptProgress, 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
@@ -126,16 +126,16 @@ 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.
+ // The GET may arrive before or after this POST. Reserve the channel here so
+ // every emitted frame is retained for a late subscriber; generation is still
+ // advisory and never waits on an SSE client.
const emit = (payload) => emitPromptProgress(deck.id, payload);
const finish = (payload) => finishPromptProgress(deck.id, payload);
let universe = null;
let cast = null;
try {
+ beginPromptProgress(deck.id);
if (deck.universeId) {
const { getUniverse } = await import('../services/universeBuilder.js');
universe = await getUniverse(deck.universeId).catch(() => null);
diff --git a/server/routes/decks.test.js b/server/routes/decks.test.js
index e3468c18b7..c6506bfc17 100644
--- a/server/routes/decks.test.js
+++ b/server/routes/decks.test.js
@@ -27,6 +27,7 @@ vi.mock('../services/deckPrompts.js', () => ({
vi.mock('../services/deckRender.js', () => ({ renderDeckCards: vi.fn() }));
vi.mock('../services/deckPromptProgress.js', () => ({
attachClient: vi.fn(() => true),
+ beginPromptProgress: vi.fn(() => true),
emitPromptProgress: vi.fn(),
finishPromptProgress: vi.fn(),
}));
@@ -38,7 +39,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 { attachClient, beginPromptProgress, emitPromptProgress, finishPromptProgress } from '../services/deckPromptProgress.js';
import { renderDeckCards } from '../services/deckRender.js';
import { getUniverse } from '../services/universeBuilder.js';
import deckRoutes from './decks.js';
@@ -150,6 +151,8 @@ describe('deck routes', () => {
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(beginPromptProgress).toHaveBeenCalledWith(D1);
+ expect(beginPromptProgress.mock.invocationCallOrder[0]).toBeLessThan(emitPromptProgress.mock.invocationCallOrder[0]);
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],
diff --git a/server/services/deckPromptProgress.js b/server/services/deckPromptProgress.js
index 47009391df..9ff827e8f7 100644
--- a/server/services/deckPromptProgress.js
+++ b/server/services/deckPromptProgress.js
@@ -6,14 +6,13 @@
* "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 —
+ * This shares the pipeline text-stage channel's SSE primitives. A GET or POST
+ * creates the channel, and late subscribers replay its latest frame —
* 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.
+ * `attachClient` opens the channel when needed; the POST also reserves
+ * it before work starts, so neither request order loses progress frames.
* 2. The client POSTs `…/generate-prompts`. The route pushes frames through
- * `emitPromptProgress`, which is a NO-OP when nobody subscribed.
+ * `emitPromptProgress`, which retains the latest frame for late clients.
* 3. `finishPromptProgress` broadcasts the terminal frame and lets the
* channel linger for `SSE_CLEANUP_DELAY_MS` so a late attach replays it.
*
@@ -51,16 +50,10 @@ const dropChannel = (key, channel) => {
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);
+const ensureChannel = (key, 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.
+ // A finished channel still inside its replay window belongs to the previous
+ // run. A new subscriber or POST starts a fresh channel for the next run.
if (channel?.finished) {
dropChannel(key, channel);
channel = null;
@@ -76,6 +69,27 @@ export function attachClient(deckId, res) {
}, CHANNEL_IDLE_MS);
channel.timer.unref?.();
}
+ return channel;
+};
+
+/** Reserve a channel when generation begins, even if GET has not arrived. */
+export function beginPromptProgress(deckId) {
+ const key = String(deckId);
+ const channel = ensureChannel(key, deckId);
+ if (!channel.started) {
+ channel.started = true;
+ clearTimer(channel);
+ }
+ return true;
+}
+
+/**
+ * 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);
+ const channel = ensureChannel(key, deckId);
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.
@@ -90,8 +104,8 @@ export function attachClient(deckId, res) {
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.
+ * Broadcast one progress frame. Keep its latest payload for replay even when
+ * no client has connected yet.
*/
export function emitPromptProgress(deckId, payload) {
const channel = channels.get(String(deckId));
diff --git a/server/services/deckPromptProgress.test.js b/server/services/deckPromptProgress.test.js
index 72bde341c6..b2b99c7f75 100644
--- a/server/services/deckPromptProgress.test.js
+++ b/server/services/deckPromptProgress.test.js
@@ -1,6 +1,7 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import {
attachClient,
+ beginPromptProgress,
emitPromptProgress,
finishPromptProgress,
isChannelOpen,
@@ -54,6 +55,19 @@ describe('deck prompt progress channel', () => {
expect(framesOf(res)).toEqual([{ type: 'chunk', written: 12, requested: 79 }]);
});
+ it('replays the latest frame when POST reserves the channel before the subscriber connects', () => {
+ beginPromptProgress('deck-1');
+ emitPromptProgress('deck-1', { type: 'start', requested: 79, chunks: 7 });
+ emitPromptProgress('deck-1', { type: 'chunk', written: 12, requested: 79, chunk: 1, chunks: 7 });
+
+ const res = fakeRes();
+ attachClient('deck-1', res);
+ expect(framesOf(res)).toEqual([{ type: 'chunk', written: 12, requested: 79, chunk: 1, chunks: 7 }]);
+
+ emitPromptProgress('deck-1', { type: 'chunk', written: 24, requested: 79, chunk: 2, chunks: 7 });
+ expect(framesOf(res).at(-1)).toEqual({ type: 'chunk', written: 24, requested: 79, chunk: 2, chunks: 7 });
+ });
+
it('keeps channels separate per deck', () => {
const first = fakeRes();
const second = fakeRes();