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
fix: keep text-stage progress visible when generation starts first (#8418)
[._.]/ Adam Eivycc05f8838fc0
diff --git a/server/lib/README.md b/server/lib/README.mdindex 288b7a586c..79cb61dbc8 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -677,6 +677,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `singleFlight.js` | `createSingleFlight()` → `run(key, fn)` — keyed in-flight coalescer: concurrent calls for the same key share one `fn()` execution and result; the slot auto-clears on settle. Minimal by design (no TTL/result cache layered on top, doesn't reject concurrent callers). Used by `services/promptRunner.js`'s fallback mark-and-pick. || `staleWhileRevalidate.js` | `createStaleWhileRevalidate({ ttlMs, failureBackoffMs?, isComplete?, partialTtlMs? })` → `read(key, produce, { wait })` / `clear(key?)` — TTL cache that serves a STALE value immediately and revalidates behind the caller, for readings too slow to block on (10-20s CLI/PTY spawns). `wait`: `'fresh'` bypasses and blocks, `'cached'` (default) blocks only on a cold cache, `'never'` returns the `PENDING` symbol on a cold cache for UIs that render "still reading" and poll. Failures keep the last good value and back off; a cold cache whose producer failed throws rather than promising a reading that isn't coming. Used by `providerUsage.js` (TUI scrapes) and `claudeCodeUsage.js`. || `staticImportGraph.js` | Static ES-module import scanning for structural test guards. `staticImportSpecifiers(file)` → every specifier a file statically imports (verbatim, source order); `staticImportClosure(entry)` → `{files, packages}` for the whole reachable graph; `buildStaticImportGraph(rootDir)` → `Map<relPath, relPath[]>` of one directory's internal static edges (recurses into subdirectories, skips `.test.js`); `listModuleFiles(rootDir)` → every non-test `.js` under a directory, keyed by `/`-separated relative path (the same walk the graph builder uses, shared so a layering guard cannot drift from it); `findImportCycles(graph)` → each cycle rendered as `a.js -> b.js -> a.js` (depth-first, so WHICH rings it names depends on where the walk enters a component — fine for an "is this empty?" assertion, unusable as a baseline); `findImportCycleComponents(graph)` → the cyclic strongly-connected components as sorted member lists, traversal-order invariant and therefore baselineable (#5693); `specifierMatchesPackage(spec, pkg)` matches a package or any subpath; `toModuleKey(relPath)` is the one graph-key mint — always `/`-separated, because the keys are built two ways (entry-name concatenation vs `path.relative`) and Windows spells the second one with `\`, which silently dropped every edge into a subdirectory module and made the acyclicity guards pass vacuously there (#5909). Static imports only — `await import()` is deferred and can't create a load-time cycle or drag a native dep into an init graph. Shared by `serviceImportCycles.test.js` (the tree-wide cycle ratchet), `agentImportCycles.test.js` and `twinImportCycles.test.js` (per-cluster acyclicity) and `spriteAnimationTracks.test.js` (the request-validation graph reaches no sharp/ffmpeg). |+| `progressChannels.js` | `createProgressChannels({ label, describeKey })` — shared GET/POST progress channel lifecycle with late subscriber replay, idle reservation reaping, and one active stream owner per key. || `sseUtils.js` | Per-job SSE stream helpers (imageGen + others) plus `createSseRunner` — the shared batch-runner lifecycle (runs map, terminal-frame replay, cancel, fire-and-forget coordinator) used by the pipeline completeness/analysis/checks runners. `createJobFailureFinalizer({ jobs, activeJobs, activeSlots, label, events, failedPayload? })` — the shared job-failure finalizer (idempotency guard w/ `force` escape hatch, slot-owner clear, SSE error frame, `failed` event, `closeJobAfterDelay`, plus a `.canceled(job, jobId, slotOwner?)` convenience) behind all six media-generation backends (`imageGen/{agy,codex,grok}.js`, `videoGen/{grok,fal,reactor}.js`). || `streamAttachment.js` | `streamAttachment(res,stream,{filename,contentType,failure,label})` — pipe a readable to a response as a file download. Sets the attachment headers plus `X-Content-Type-Options:nosniff`, and owns the teardown every attachment route needs: a pre-stream failure drops the download headers and returns `failure` via `sendErrorResponse`, a mid-stream failure destroys the socket (the envelope no-ops once headers are sent), and a client disconnect calls `stream.abort?.()` so an upstream child process is torn down. Shared by `routes/imageTo3d.js` (GLB, full-mesh) and `routes/backup.js` (snapshot tarball). || `streamBackpressure.js` | `awaitWritableDrain(res)` — park a streaming-response producer on the socket's next `drain` (or `close`) when `res.write()` returned false, so SSE/NDJSON writes stay bounded for a slow reader. Shared by `routes/ask.js` (SSE) and `routes/localLlm.js` (NDJSON). |diff --git a/server/lib/index.js b/server/lib/index.jsindex b0db6c62a5..b417a84a23 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -657,6 +657,7 @@ export * from './slashdoCatalog.js';export * from './slashdoInvocation.js';export * from './slashdoLoader.js';export * from './singleFlight.js';+export * from './progressChannels.js';export * from './staleWhileRevalidate.js';export * from './staticImportGraph.js';export * from './streamAttachment.js';diff --git a/server/lib/progressChannels.js b/server/lib/progressChannels.jsnew file mode 100644index 0000000000..31d146a255--- /dev/null+++ b/server/lib/progressChannels.js@@ -0,0 +1,101 @@+/** Shared SSE channel lifecycle for request-owned progress streams. */+import { attachSseClient, broadcastSse, SSE_CLEANUP_DELAY_MS } from './sseUtils.js';++export const CHANNEL_IDLE_MS = 60_000;++export function createProgressChannels({ label, describeKey }) {+ const channels = new Map();++ const clearTimer = (channel) => {+ if (channel.timer) clearTimeout(channel.timer);+ channel.timer = null;+ };++ const dropChannel = (key, channel) => {+ clearTimer(channel);+ for (const client of channel.clients) client.end();+ if (channels.get(key) === channel) channels.delete(key);+ };++ const ensureChannel = (key) => {+ let channel = channels.get(key);+ // A finished channel belongs to the previous run, even during its replay+ // window. A fresh GET or POST must not attach to that run.+ if (channel?.finished) {+ dropChannel(key, channel);+ channel = null;+ }+ if (!channel) {+ channel = { clients: [], lastPayload: null, started: false, finished: false, timer: null };+ channels.set(key, channel);+ channel.timer = setTimeout(() => {+ if (channels.get(key) !== channel || channel.started) return;+ console.log(`🧹 ${label} — reaped idle channel ${describeKey(key)}`);+ dropChannel(key, channel);+ }, CHANNEL_IDLE_MS);+ channel.timer.unref?.();+ }+ return channel;+ };++ const begin = (key) => {+ const channel = ensureChannel(key);+ if (channel.started) return false;+ channel.started = true;+ clearTimer(channel);+ return true;+ };++ const attach = (key, res) => {+ const channel = ensureChannel(key);+ attachSseClient(channels, key, res);+ res.req.on('close', () => {+ if (channels.get(key) === channel && !channel.started && channel.clients.length === 0) {+ dropChannel(key, channel);+ }+ });+ return true;+ };++ const emit = (key, payload) => {+ const channel = channels.get(key);+ if (!channel) return;+ // Preserve the existing start-frame revival for a subscriber that stayed+ // attached through a previous terminal frame.+ if (channel.finished) {+ if (payload?.type !== 'start') return;+ channel.finished = false;+ clearTimer(channel);+ }+ if (!channel.started) {+ channel.started = true;+ clearTimer(channel);+ }+ broadcastSse(channel, payload);+ };++ const finish = (key, payload) => {+ 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?.();+ };++ return {+ attach,+ begin,+ emit,+ finish,+ isOpen: (key) => channels.has(key),+ __testing: {+ channels,+ reset: () => {+ for (const [key, channel] of [...channels]) dropChannel(key, channel);+ channels.clear();+ },+ },+ };+}diff --git a/server/services/deckPromptProgress.js b/server/services/deckPromptProgress.jsindex b413b7cad2..9d092701af 100644--- a/server/services/deckPromptProgress.js+++ b/server/services/deckPromptProgress.js@@ -1,155 +1,18 @@/**- * 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 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 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 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.- *- * 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.+ * Deck prompt progress. GET and POST may arrive in either order: POST reserves+ * the channel before writing frames, and a late subscriber replays the latest.*/--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);-};--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 or POST starts a fresh channel for the next run.- 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?.();- }- 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);- // A started, unfinished channel belongs to an active generation run. Only- // one prompt POST may own a deck channel at a time; otherwise one run could- // publish the other run's chunks or terminal frame to every subscriber.- if (channel.started) return false;- 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.- 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. Keep its latest payload for replay even when- * no client has connected yet.- */-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();- },-};+import { createProgressChannels, CHANNEL_IDLE_MS } from '../lib/progressChannels.js';++const progress = createProgressChannels({+ label: 'Deck prompt progress',+ describeKey: (key) => `deck=${String(key).slice(0, 8)}`,+});++export { CHANNEL_IDLE_MS };+export const beginPromptProgress = (deckId) => progress.begin(String(deckId));+export const attachClient = (deckId, res) => progress.attach(String(deckId), res);+export const isChannelOpen = (deckId) => progress.isOpen(String(deckId));+export const emitPromptProgress = (deckId, payload) => progress.emit(String(deckId), payload);+export const finishPromptProgress = (deckId, payload) => progress.finish(String(deckId), payload);+export const __testing = progress.__testing;diff --git a/server/services/pipeline/textStageProgress.js b/server/services/pipeline/textStageProgress.jsindex 3f80670e13..e517b51254 100644--- a/server/services/pipeline/textStageProgress.js+++ b/server/services/pipeline/textStageProgress.js@@ -1,152 +1,25 @@/**- * 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.+ * Pipeline text-stage generation progress (#3393). GET and POST may arrive in+ * either order. `generateStage` reserves the channel before its first frame,+ * and a late subscriber replays the latest frame. The stream is advisory:+ * an overlapping run still generates, but cannot publish into or finish the+ * first run's channel.*/+import { createProgressChannels, CHANNEL_IDLE_MS } from '../../lib/progressChannels.js';-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();+const progress = createProgressChannels({+ label: 'Text-stage progress',+ describeKey: (key) => {+ const [issueId, stageId] = key.split('::');+ return `stage=${stageId} issue=${String(issueId).slice(0, 8)}`;+ },+});-/** Channel key for one issue's one text stage. */+export { CHANNEL_IDLE_MS };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();- },-};+export const beginStageProgress = (issueId, stageId) => progress.begin(channelKey(issueId, stageId));+export const attachClient = (issueId, stageId, res) => progress.attach(channelKey(issueId, stageId), res);+export const isChannelOpen = (issueId, stageId) => progress.isOpen(channelKey(issueId, stageId));+export const emitStageProgress = (issueId, stageId, payload) => progress.emit(channelKey(issueId, stageId), payload);+export const finishStageProgress = (issueId, stageId, payload) => progress.finish(channelKey(issueId, stageId), payload);+export const __testing = progress.__testing;diff --git a/server/services/pipeline/textStageProgress.test.js b/server/services/pipeline/textStageProgress.test.jsindex be3b4a30fb..98bd3f3122 100644--- a/server/services/pipeline/textStageProgress.test.js+++ b/server/services/pipeline/textStageProgress.test.js@@ -1,6 +1,7 @@import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import {attachClient,+ beginStageProgress,emitStageProgress,finishStageProgress,isChannelOpen,@@ -55,6 +56,19 @@ describe('text-stage progress channel', () => {expect(framesOf(res)).toEqual([{ type: 'phase', phase: 'generate', attempt: 1 }]);});+ it('replays POST-first progress and keeps the reserved channel through a long run', () => {+ expect(beginStageProgress('issue-1', 'prose')).toBe(true);+ emitStageProgress('issue-1', 'prose', { type: 'start' });+ emitStageProgress('issue-1', 'prose', { type: 'phase', phase: 'generate' });+ vi.advanceTimersByTime(CHANNEL_IDLE_MS * 3);++ const late = fakeRes();+ attachClient('issue-1', 'prose', late);+ expect(framesOf(late)).toEqual([{ type: 'phase', phase: 'generate' }]);+ expect(late.ended).toBe(false);+ expect(beginStageProgress('issue-1', 'prose')).toBe(false);+ });+it('keeps channels separate per issue and per stage', () => {const prose = fakeRes();const script = fakeRes();diff --git a/server/services/pipeline/textStages.js b/server/services/pipeline/textStages.jsindex 84584f5b52..b0ee93ec1a 100644--- a/server/services/pipeline/textStages.js+++ b/server/services/pipeline/textStages.js@@ -21,7 +21,7 @@import { runStagedLLM, resolveStageContext } from '../stageRunner.js';import { getStage } from '../promptService.js';-import { emitStageProgress, finishStageProgress } from './textStageProgress.js';+import { beginStageProgress, 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';@@ -889,14 +889,18 @@ 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);+ // Generation may overlap, but only the first run owns this stream.+ const ownsProgress = beginStageProgress(issueId, stageId);+ const emit = (payload) => {+ if (ownsProgress) 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, {+ if (ownsProgress) finishStageProgress(issueId, stageId, {type: 'error',issueId,stageId,@@ -905,7 +909,7 @@ export async function generateStage(issueId, stageId, options = {}) {});throw outcome.error;}- finishStageProgress(issueId, stageId, {+ if (ownsProgress) finishStageProgress(issueId, stageId, {type: 'complete',issueId,stageId,diff --git a/server/services/pipeline/textStages.test.js b/server/services/pipeline/textStages.test.jsindex 21b710b5a9..a0046afbdf 100644--- a/server/services/pipeline/textStages.test.js+++ b/server/services/pipeline/textStages.test.js@@ -1300,11 +1300,52 @@ describe('text-stage generation progress frames (#3393)', () => {return { series, issue };}- it('generates normally with nobody subscribed (the channel is never a dependency)', async () => {+ it('generates normally with nobody subscribed and reserves progress for a late client', 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);+ expect(textStageProgress.__testing.channels.get(textStageProgress.channelKey(issue.id, 'prose')).lastPayload.type)+ .toBe('complete');+ });++ it('an overlapping generation cannot finish the first run\'s progress stream', async () => {+ const { issue } = await seedProse();+ const res = fakeRes();+ textStageProgress.attachClient(issue.id, 'prose', res);++ let firstStarted;+ let secondStarted;+ let finishFirst;+ let finishSecond;+ const firstAtProvider = new Promise((resolve) => { firstStarted = resolve; });+ const secondAtProvider = new Promise((resolve) => { secondStarted = resolve; });+ const firstCanFinish = new Promise((resolve) => { finishFirst = resolve; });+ const secondCanFinish = new Promise((resolve) => { finishSecond = resolve; });+ runnerSvc.executeApiRun.mockImplementationOnce(async ({ onData, onComplete }) => {+ firstStarted();+ await firstCanFinish;+ onData('First draft');+ onComplete({ success: true });+ }).mockImplementationOnce(async ({ onData, onComplete }) => {+ secondStarted();+ await secondCanFinish;+ onData('Second draft');+ onComplete({ success: true });+ });++ const first = textStages.generateStage(issue.id, 'prose', {});+ await firstAtProvider;+ const second = textStages.generateStage(issue.id, 'prose', {});+ await secondAtProvider;+ finishSecond();+ await second;+ expect(framesOf(res).some((frame) => frame.type === 'complete')).toBe(false);+ expect(textStageProgress.__testing.channels.get(textStageProgress.channelKey(issue.id, 'prose')).finished)+ .toBe(false);++ finishFirst();+ await first;+ expect(framesOf(res).filter((frame) => frame.type === 'complete')).toHaveLength(1);});it('streams start → context → generate → complete on the single-shot path', async () => {