[GH-ISSUE #2742] [Issue]: SSE keepalive omitted across most streaming routes + missing X-Accel-Buffering + no client watchdog (proxy idle-timeout / stuck spinner) #1381

Closed
opened 2026-10-21 05:32:42 +07:00 by bsakaguchi · 1 comment
Owner

Originally created by @kolacheee on GitHub (Jun 21, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2742

Originally assigned to: @SpicyMarinara on GitHub.

Summary

The only SSE keepalive in the codebase is a 15s : keepalive\n\n setInterval scoped inside generateForCharacter (generate.routes.ts:5969, cleared at 6856). Its own comment says it exists because "Cloudflare and other reverse proxies often kill idle connections after ~100s." Every other long byte-silent phase runs outside that window: pre-generation (smart-group selector, lorebook/memory recall), post-generation (prose-guardian rewrite + auto-summary), the turn-game bot loop, the /retry-agents route, and the Professor-Mari /prompt agent loop. /retry-agents also omits the X-Accel-Buffering: no header that the three other SSE routes set. Separately, the client streamEvents() never settles streaming state on {type:'done'} and has no idle watchdog, so the post-done illustration tail keeps the UI in a streaming state. Behind a reverse proxy with a short idle timeout, these drop the connection or freeze the UI.

Sub-bug 1: No keepalive during pre-generation (MEDIUM, hang)

  • How it breaks: selectSmartGroupResponders runs a blocking non-streaming chatComplete before any generateForCharacter, so the selector model (possibly a slow reasoning model on the same connection) can run for tens of seconds with zero keepalive bytes. Applies to all pre-gen work (recall, sequential agents, prompt assembly) too.
  • Repro: Smart group chat behind a proxy with ~60-100s idle timeout + a slow selector model; stream drops before the first token.
  • Trace: generate.routes.ts:5720-5734 (blocking selector), awaited 5772; keepalive only at 5969 inside generateForCharacter (first invoked 6931).

Sub-bug 2: No keepalive during post-generation rewrite/summary (MEDIUM, hang)

  • How it breaks: After token gen, the keepalive is cleared (6856); the prose-guardian/text-rewrite executeAgent LLM call (8791) and auto-summary chatComplete (7137/awaited 8874) run with the socket idle. When holdForProseGuardianRewrite is true, message_saved carries the PROSE_GUARDIAN_PENDING_MESSAGE placeholder and the real text only arrives via the later text_rewrite event — if the proxy kills the idle connection in between, the client stays on "Prose Guardian is working!".
  • Repro: Enable Prose Guardian behind a short-idle-timeout proxy; the bubble sticks on the placeholder until reload.
  • Trace: generate.routes.ts:5969/6856 (keepalive lifetime), 6741-6754 (placeholder message_saved), 8765-8868 (rewrite emit), 10656 (done).

Sub-bug 3: No keepalive on turn-game bot path (MEDIUM, hang/truncation)

  • How it breaks: The turnGameBots branch early-returns at 1398-1410, never entering generateForCharacter. runTurnGameBotTurns does two blocking chatComplete calls per bot turn (move + narration) with no : keepalive between group_turn and message_saved. Disconnect is NOT propagated in conversation mode (see abort issue), so the loop also continues as a zombie.
  • Repro: Multi-bot turn game (UNO) with a slow model behind a proxy; game freezes mid-turn.
  • Trace: generate.routes.ts:1398-1410; turn-game-bot-runner.service.ts:170/197-203/244/259/274; MAX_BOT_TURNS=100.

Sub-bug 4: No keepalive on /retry-agents + missing X-Accel-Buffering (MEDIUM, hang/truncation)

  • How it breaks: After startSseReply the route sends one agent_start, then runs all agent batches + lorebook-keeper backfill (N sequential LLM calls) before the first agent_result — no keepalive in between. It also calls startSseReply(reply) with no extra header, so nginx buffers the whole stream (the early agent_start progress signal is held, UI looks frozen, idle-timeout risk).
  • Repro: Manual tracker/lorebook-keeper retry with backfill behind nginx; no incremental progress, possible drop.
  • Trace: retry-agents-route.ts:2880 (startSseReply(reply) no header), 3063 (agent_start), 3078-3103 (batches), 3174 (first result); contrast generate.routes.ts:1331 + 5969.

Sub-bug 5: No keepalive on Professor-Mari /prompt (MEDIUM, truncation)

  • How it breaks: /prompt flushes headers and wires abort, but a multi-step tool loop / 10-min approval wait produces dead air with no : keepalive; the client stays in-progress until done.
  • Trace: professor-mari-workspace.routes.ts:93-129, await service.prompt 115-120.

Sub-bug 6: Client never settles on done; post-done tail hangs UI (MEDIUM, hang)

  • How it breaks: streamEvents() only ends on [DONE]/error, yielding {type:'done'} through; the consumer's done case doesn't setStreaming(false). The server emits done before awaiting the slow illustration tail and only end()s after, so isStreaming stays true (stop button shown) for the whole image-gen duration.
  • Repro: Generate a message with an illustrator agent; the streaming indicator persists after the text is final until the image finishes.
  • Trace: api-client.ts:275-298; consumer use-generate.ts:2106-2114; server generate.routes.ts:10653-10666 (done before await pendingIllustration).

Suggested Fix

  • Hoist the keepalive to request scope: start one setInterval(() => { if (!reply.raw.destroyed) reply.raw.write(': keepalive\n\n'); }, 15000) right after startSseReply and clear it once in the outer finally, covering pre-gen, gen, and post-gen uniformly.
  • Add request-scoped keepalive around runTurnGameBotTurns, the /retry-agents handler, and the Professor-Mari /prompt agent loop (clear in finally).
  • Change retry-agents-route.ts:2880 to startSseReply(reply, { 'X-Accel-Buffering': 'no' }).
  • In streamEvents(), treat {type:'done'} as terminal (return after yielding) like stream() does, or arm a bounded post-done watchdog; ensure the consumer settles streaming state on done.

Root-cause throughline

The keepalive and proxy-buffering protections were added narrowly to the per-character token loop and were never generalized to the request lifecycle, so every other long byte-silent phase (selector, recall, rewrite, summary, bot turns, retries, workspace tool loops, and the post-done illustration tail) runs unprotected — and the client compounds it by never treating done as terminal.

Verification checklist (leave all UNCHECKED)

  • Manually verify behind a reverse proxy (~60s idle): smart-group selector turn does not drop before first token
  • Manually verify behind a proxy: Prose-Guardian turn updates from placeholder to real text without reload
  • Manually verify behind a proxy: multi-bot turn game does not freeze mid-turn
  • Manually verify behind nginx: /retry-agents shows incremental progress and completes
  • Manually verify: Professor Mari /prompt survives a long tool/approval step
  • Manually verify: streaming indicator clears when an illustrated message's text is final (post-done tail)
  • Run pnpm check

Affected files

  • packages/server/src/routes/generate.routes.ts
  • packages/server/src/routes/generate/retry-agents-route.ts
  • packages/server/src/services/turn-games/turn-game-bot-runner.service.ts
  • packages/server/src/routes/professor-mari-workspace.routes.ts
  • packages/client/src/lib/api-client.ts

Audit provenance

Found by a multi-agent static audit of the streaming/SSE subsystem (Round 1 + round-2 gap sweep + completeness critic, each finding adversarially verified) against the merged staging tree. Severity: MEDIUM.

AI-drafted from a static read; validation/test-plan boxes intentionally left UNCHECKED for a human to verify before close.

Originally created by @kolacheee on GitHub (Jun 21, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2742 Originally assigned to: @SpicyMarinara on GitHub. ## Summary The only SSE keepalive in the codebase is a 15s `: keepalive\n\n` `setInterval` scoped inside `generateForCharacter` (`generate.routes.ts:5969`, cleared at `6856`). Its own comment says it exists because "Cloudflare and other reverse proxies often kill idle connections after ~100s." Every other long byte-silent phase runs outside that window: pre-generation (smart-group selector, lorebook/memory recall), post-generation (prose-guardian rewrite + auto-summary), the turn-game bot loop, the `/retry-agents` route, and the Professor-Mari `/prompt` agent loop. `/retry-agents` also omits the `X-Accel-Buffering: no` header that the three other SSE routes set. Separately, the client `streamEvents()` never settles streaming state on `{type:'done'}` and has no idle watchdog, so the post-done illustration tail keeps the UI in a streaming state. Behind a reverse proxy with a short idle timeout, these drop the connection or freeze the UI. ### Sub-bug 1: No keepalive during pre-generation (MEDIUM, hang) - **How it breaks:** `selectSmartGroupResponders` runs a blocking non-streaming `chatComplete` before any `generateForCharacter`, so the selector model (possibly a slow reasoning model on the same connection) can run for tens of seconds with zero keepalive bytes. Applies to all pre-gen work (recall, sequential agents, prompt assembly) too. - **Repro:** Smart group chat behind a proxy with ~60-100s idle timeout + a slow selector model; stream drops before the first token. - **Trace:** `generate.routes.ts:5720-5734` (blocking selector), awaited `5772`; keepalive only at `5969` inside `generateForCharacter` (first invoked `6931`). ### Sub-bug 2: No keepalive during post-generation rewrite/summary (MEDIUM, hang) - **How it breaks:** After token gen, the keepalive is cleared (`6856`); the prose-guardian/text-rewrite `executeAgent` LLM call (`8791`) and auto-summary `chatComplete` (`7137`/awaited `8874`) run with the socket idle. When `holdForProseGuardianRewrite` is true, `message_saved` carries the `PROSE_GUARDIAN_PENDING_MESSAGE` placeholder and the real text only arrives via the later `text_rewrite` event — if the proxy kills the idle connection in between, the client stays on "Prose Guardian is working!". - **Repro:** Enable Prose Guardian behind a short-idle-timeout proxy; the bubble sticks on the placeholder until reload. - **Trace:** `generate.routes.ts:5969/6856` (keepalive lifetime), `6741-6754` (placeholder message_saved), `8765-8868` (rewrite emit), `10656` (done). ### Sub-bug 3: No keepalive on turn-game bot path (MEDIUM, hang/truncation) - **How it breaks:** The `turnGameBots` branch early-returns at `1398-1410`, never entering `generateForCharacter`. `runTurnGameBotTurns` does two blocking `chatComplete` calls per bot turn (move + narration) with no `: keepalive` between `group_turn` and `message_saved`. Disconnect is NOT propagated in conversation mode (see abort issue), so the loop also continues as a zombie. - **Repro:** Multi-bot turn game (UNO) with a slow model behind a proxy; game freezes mid-turn. - **Trace:** `generate.routes.ts:1398-1410`; `turn-game-bot-runner.service.ts:170/197-203/244/259/274`; MAX_BOT_TURNS=100. ### Sub-bug 4: No keepalive on /retry-agents + missing X-Accel-Buffering (MEDIUM, hang/truncation) - **How it breaks:** After `startSseReply` the route sends one `agent_start`, then runs all agent batches + lorebook-keeper backfill (N sequential LLM calls) before the first `agent_result` — no keepalive in between. It also calls `startSseReply(reply)` with no extra header, so nginx buffers the whole stream (the early `agent_start` progress signal is held, UI looks frozen, idle-timeout risk). - **Repro:** Manual tracker/lorebook-keeper retry with backfill behind nginx; no incremental progress, possible drop. - **Trace:** `retry-agents-route.ts:2880` (`startSseReply(reply)` no header), `3063` (agent_start), `3078-3103` (batches), `3174` (first result); contrast `generate.routes.ts:1331` + `5969`. ### Sub-bug 5: No keepalive on Professor-Mari /prompt (MEDIUM, truncation) - **How it breaks:** `/prompt` flushes headers and wires abort, but a multi-step tool loop / 10-min approval wait produces dead air with no `: keepalive`; the client stays in-progress until `done`. - **Trace:** `professor-mari-workspace.routes.ts:93-129`, `await service.prompt` `115-120`. ### Sub-bug 6: Client never settles on done; post-done tail hangs UI (MEDIUM, hang) - **How it breaks:** `streamEvents()` only ends on `[DONE]`/`error`, yielding `{type:'done'}` through; the consumer's `done` case doesn't `setStreaming(false)`. The server emits `done` before awaiting the slow illustration tail and only `end()`s after, so `isStreaming` stays true (stop button shown) for the whole image-gen duration. - **Repro:** Generate a message with an illustrator agent; the streaming indicator persists after the text is final until the image finishes. - **Trace:** `api-client.ts:275-298`; consumer `use-generate.ts:2106-2114`; server `generate.routes.ts:10653-10666` (done before `await pendingIllustration`). ## Suggested Fix - Hoist the keepalive to request scope: start one `setInterval(() => { if (!reply.raw.destroyed) reply.raw.write(': keepalive\n\n'); }, 15000)` right after `startSseReply` and clear it once in the outer `finally`, covering pre-gen, gen, and post-gen uniformly. - Add request-scoped keepalive around `runTurnGameBotTurns`, the `/retry-agents` handler, and the Professor-Mari `/prompt` agent loop (clear in finally). - Change `retry-agents-route.ts:2880` to `startSseReply(reply, { 'X-Accel-Buffering': 'no' })`. - In `streamEvents()`, treat `{type:'done'}` as terminal (return after yielding) like `stream()` does, or arm a bounded post-done watchdog; ensure the consumer settles streaming state on done. ## Root-cause throughline The keepalive and proxy-buffering protections were added narrowly to the per-character token loop and were never generalized to the request lifecycle, so every other long byte-silent phase (selector, recall, rewrite, summary, bot turns, retries, workspace tool loops, and the post-done illustration tail) runs unprotected — and the client compounds it by never treating `done` as terminal. ## Verification checklist (leave all UNCHECKED) - [ ] Manually verify behind a reverse proxy (~60s idle): smart-group selector turn does not drop before first token - [ ] Manually verify behind a proxy: Prose-Guardian turn updates from placeholder to real text without reload - [ ] Manually verify behind a proxy: multi-bot turn game does not freeze mid-turn - [ ] Manually verify behind nginx: /retry-agents shows incremental progress and completes - [ ] Manually verify: Professor Mari /prompt survives a long tool/approval step - [ ] Manually verify: streaming indicator clears when an illustrated message's text is final (post-done tail) - [ ] Run `pnpm check` --- ### Affected files - `packages/server/src/routes/generate.routes.ts` - `packages/server/src/routes/generate/retry-agents-route.ts` - `packages/server/src/services/turn-games/turn-game-bot-runner.service.ts` - `packages/server/src/routes/professor-mari-workspace.routes.ts` - `packages/client/src/lib/api-client.ts` ### Audit provenance Found by a multi-agent static audit of the streaming/SSE subsystem (Round 1 + round-2 gap sweep + completeness critic, each finding adversarially verified) against the merged `staging` tree. Severity: **MEDIUM**. > AI-drafted from a static read; validation/test-plan boxes intentionally left UNCHECKED for a human to verify before close.
Author
Owner

@SpicyMarinara commented on GitHub (Jun 21, 2026):

Addressed on PR #2747. Added a shared SSE keepalive helper and wired request-scoped heartbeats into /generate, /generate/retry-agents, and Professor Mari /prompt; /retry-agents now also sends X-Accel-Buffering: no. The old per-character generate keepalive was hoisted so pre-generation, turn-game bots, post-generation rewrites/summaries, and illustration tails are covered by one outer cleanup path. On the client, the generation consumer now settles visible streaming state on the done event while keeping streamEvents open for late illustration events; dry-run already had its own keepalive/header coverage. Deferred full pnpm validation until the end of the issue sweep, per maintainer request.

<!-- gh-comment-id:4763235420 --> @SpicyMarinara commented on GitHub (Jun 21, 2026): Addressed on PR #2747. Added a shared SSE keepalive helper and wired request-scoped heartbeats into /generate, /generate/retry-agents, and Professor Mari /prompt; /retry-agents now also sends X-Accel-Buffering: no. The old per-character generate keepalive was hoisted so pre-generation, turn-game bots, post-generation rewrites/summaries, and illustration tails are covered by one outer cleanup path. On the client, the generation consumer now settles visible streaming state on the done event while keeping streamEvents open for late illustration events; dry-run already had its own keepalive/header coverage. Deferred full pnpm validation until the end of the issue sweep, per maintainer request.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Pasta-Devs/Marinara-Engine#1381
No description provided.