[GH-ISSUE #3573] [Issue]: marinara-autonomous-sse-roundrobin bug #1935

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

Originally created by @captinalex1 on GitHub (Jul 13, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/3573

Originally assigned to: @SpicyMarinara on GitHub.

Summary

Autonomous/offline character exchange in group Conversation mode could fail to save or chain valid character replies. The visible symptom looked like "offline/autonomous bickering does not work," but locally it was one combined failure chain across candidate selection, sequential/round-robin scoping, wrong-speaker pruning, and OpenAI-compatible SSE/provider parsing.

In the failing state, Marinara could generate or receive valid text, then lose it as an empty response or prune it as the wrong speaker. Separately, autonomous candidate selection could stop at one blocked/capped/cooldowned character instead of falling through to another eligible character. Together, those made offline multi-character chatter look dead or unreliable.

The related SSE/provider bug matters because a valid provider response could be treated as empty before the autonomous exchange had anything to save or chain.

Expected behavior

  • Offline/autonomous character exchange should select an eligible character and save the generated reply.
  • If the first candidate is capped, cooling down, blocked by status, or otherwise ineligible, the route should fall through to another eligible candidate.
  • Conversation mode with groupResponseOrder: "sequential" should behave like one-character-at-a-time generation, not merged multi-speaker generation.
  • Wrong-speaker pruning should remove actual wrong-speaker output without deleting valid target-character output.
  • OpenAI-compatible SSE/chat responses should preserve assistant text whether it appears in choice.delta.content, choice.message.content, or buffered provider result content.
  • Empty-response handling/logging should make it clear whether the loss happened at provider parsing, prompt/post-processing, wrong-speaker pruning, or save time.

Actual behavior

  • Valid provider output could be interpreted as empty.
  • Autonomous/offline chatter could fail to persist even when characters were eligible.
  • Character exchange could choose one blocked/capped/cooldowned candidate and stop.
  • Sequential group conversations could produce multi-speaker output or labels that were later pruned incorrectly.
  • Wrong-speaker pruning could treat the target character's own display name as an "other speaker" name and delete a valid Target: ... response.

Observed local error pattern:

The AI returned an empty response

Related OpenAI-compatible non-stream/parser failure seen with gateway metadata:

Failed to parse JSON response (Unexpected token ':', ": x-omniro"... is not valid JSON).
Body starts with:
: x-omniroute-cache-hit=false
: x-omniroute-latency-ms=12
: x-omniroute-response-cost=0.0000000000
: x-omniroute-tokens-in=0
: x-omniroute-tokens-out=0
: x-omniroute-version=...
: x-omniroute-model...

Steps to reproduce

  1. Configure a group chat using Conversation mode.
  2. Set group response order to sequential/round-robin style behavior.
  3. Enable autonomous/offline character exchanges for multiple characters.
  4. Use an OpenAI-compatible provider/gateway that returns chat output through SSE frames.
  5. Let the autonomous/offline path trigger a character response while the user is away/offline.
  6. Watch server logs and saved messages.

Extra conditions that made the local bug easier to hit:

  • A multi-character room where the first autonomous candidate is blocked by budget, cooldown, or status, while another character is still eligible.
  • Model output includes speaker labels such as CharacterName:.
  • The target character's own name can appear in the wrong-speaker filtering list due to stale/duplicate name handling.
  • Provider output includes useful content in SSE frames or buffered provider content that the parser does not read.

Environment

  • Marinara Engine version: locally patched 2.2.0 build
  • Install type: Docker
  • Host: Unraid running the Docker container
  • Client: web UI
  • Provider/gateway: OpenAI-compatible custom provider through ChubAI Soji Model SSE responses (Also tested in linking Marinara to OmniRoute with ChubAI Soji Provider enabled there)
  • Model path involved: OpenAI-compatible chat completions / SSE streaming

Root cause chain

This did not appear to be one single autonomous scheduler bug. It was a chain of smaller issues that masked each other:

  1. Autonomous candidate selection returned/used only one top candidate.
  2. checkCharacterExchange() returned only one randomly chosen candidate.
  3. Route-level autonomous handling could not fall through from a blocked candidate to another eligible one.
  4. Conversation mode with sequential response order was not consistently treated as individual target-character generation.
  5. Individual group scoping was applied more reliably in roleplay/manual paths than in Conversation/sequential paths.
  6. Wrong-speaker pruning could include the target character's own display name in the "other speakers" regex.
  7. OpenAI-compatible SSE/provider parsing could miss valid text when it arrived in choice.message.content or buffered provider result content instead of only choice.delta.content.

The result: valid autonomous turns were generated but not saved, saved as the wrong speaker, pruned to empty, or never attempted because candidate selection stopped too early.

Code locations and local patch notes

packages/server/src/services/conversation/autonomous.service.ts

Relevant functions/behavior:

  • Added isAutonomousDailyCapUncapped(meta).
  • Added isAutonomousDailyBudgetExhausted(characterId, schedule, meta).
  • Changed checkAutonomousMessaging() so group chats return all eligible candidates in priority order, not only the top one.
  • Changed checkCharacterExchange() so it shuffles eligible characters and returns the whole ordered candidate list, not just one candidate.

Important behavior:

if (isAutonomousDailyCapUncapped(chatMeta)) return false;
const sent = budget.counts[characterId] ?? 0;
const cap = dailyCapForCharacter(schedule, chatMeta);
return sent >= cap;

Why it matters:

The autonomous system needs enough candidate information for route-level checks to skip a blocked character and try the next eligible one.

packages/server/src/routes/conversation.routes.ts

Relevant functions/behavior:

  • evaluateAutonomousCandidate() now calls isAutonomousDailyBudgetExhausted().
  • Autonomous trigger route loops through returned characterIds, skips capped/cooldowned candidates, and starts generation for the first allowed one.
  • Catch-up user-inactivity path does the same.
  • Character-exchange endpoint chooses the first returned candidate whose daily budget is not exhausted.

Important behavior:

for (const characterId of result.characterIds) {
  const evaluation = evaluateAutonomousCandidate(chatId, characterId, schedule, meta);
  if (!evaluation.ok) {
    blockedReason = blockedReason ?? evaluation.reason;
    continue;
  }

  const generationStartedAt = markGenerationInProgress(chatId);
  return reply.send({
    ...result,
    characterIds: [characterId],
    generationStartedAt,
    ...evaluation.intent,
  });
}

Why it matters:

Before this, one blocked candidate could make the whole autonomous pass look blocked even when another character should have been allowed to respond.

packages/server/src/routes/generate.routes.ts

Relevant functions/behavior:

  • Conversation groupResponseOrder === "sequential" is treated like individual mode, same as manual.
  • Individual group message scoping now applies in conversation mode too, not only roleplay.
  • Added stricter per-target prompt: respond only as this character; do not write labels/dialogue/actions for other characters; let the next round-robin turn handle reactions.
  • Wrong-speaker guard removes the target's own display name from otherSpeakerNames before building the regex.
  • If response begins with another speaker, it can skip ahead to an embedded target prefix, drop wrong-speaker-only output, or prune leading wrong-speaker paragraphs instead of saving mislabeled text.
  • Empty-response logging was expanded so post-processing losses are visible.
  • Autonomous daily budget patch is skipped when chat meta is autonomousDailyCapMode: "uncapped".

Critical guard detail:

const otherNames = charInfo
  .filter((c) => c.id !== targetCharId)
  .map((c) => c.name)
  .filter((name): name is string => Boolean(name))
  .filter((name) => name.trim().toLocaleLowerCase() !== cName.trim().toLocaleLowerCase())
  .map((name) => name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));

Target-only prompt behavior:

return [
  `Respond ONLY as ${charName}.`,
  `Your entire answer is ${charName}'s next message only.`,
  `Do not write dialogue, narration, labels, or actions for anyone except ${charName}.`,
  otherNames.length > 0
    ? `Forbidden speaker labels for this turn: ${otherNames.join(", ")}. Do not start any line with those names.`
    : null,
  `If you want another character to react, stop after ${charName}'s message and let the next round-robin turn handle them.`,
]
  .filter(Boolean)
  .join("\n");

Why it matters:

Round-robin/sequential generation only works if each generation pass is truly scoped to one target speaker. Otherwise characters can step on each other, write each other's reactions, or produce labels that later get pruned as wrong-speaker output.

packages/server/src/services/llm/providers/openai.provider.ts

Relevant functions/behavior:

  • SSE JSON recovery scans for a message-bearing payload instead of returning the first non-empty SSE frame.
  • Streaming parsing accepts both choice.delta.content and choice.message.content.
  • Buffered provider result.content is used when stream callbacks produce nothing but the provider result still contains text.

Important behavior:

const content = delta?.content ?? message?.content;
if (typeof content === "string" && content) yield content;

Why it matters:

Some OpenAI-compatible gateways/providers return useful assistant text in a final/full message.content frame or buffered result content. If Marinara only reads delta.content, a valid reply can collapse into "empty response."

UI/types touched locally

  • packages/shared/src/types/chat.ts
    • Added autonomousDailyCapMode?: "default" | "capped" | "uncapped".
  • packages/client/src/components/chat/ChatSettingsDrawer.tsx
    • Added Power user: no daily cap.
  • packages/client/src/components/chat/CharacterScheduleEditorModal.tsx
    • Clarified that power-user mode bypasses daily counter but not schedule/status/cooldowns.

Logs, screenshots, or video

Local verification after patch:

  • Health showed the patched build active.
  • Exact failing autonomous payload for Group Convo saved real messages after patch.
  • Logs showed non-empty resolved content and provider-content fallback instead of empty-response failure.
  • Living-room/group chatter produced multiple server-side follow-up turns.
  • DND still blocked correctly with user_dnd.
  • Away/server eligibility returned eligible after clearing a stale test lock.

Additional context

Short version:

The bug was not just "autonomous failed" and not just "SSE parsing failed." It was a combined chain:

  • Candidate selection stopped too early.
  • Sequential/round-robin Conversation mode was not always individual/scoped.
  • Characters could step on each other by producing labels/dialogue/actions for other speakers.
  • Wrong-speaker pruning could delete valid target-character output.
  • Provider streaming sometimes put useful text somewhere Marinara did not read.

Fixing those together made offline/autonomous bickering persist and chain correctly.

Template check

  • I DID NOT read this template and provide the requested details.

Patch appendix

The full local diff is included below so maintainers can inspect or test the actual patch shape directly. It is scoped to the Marinara files involved in the autonomous/round-robin/wrong-speaker/SSE chain.

2.2.0 Patch for automatic offline character chatter.txt

Originally created by @captinalex1 on GitHub (Jul 13, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/3573 Originally assigned to: @SpicyMarinara on GitHub. ## Summary Autonomous/offline character exchange in group Conversation mode could fail to save or chain valid character replies. The visible symptom looked like "offline/autonomous bickering does not work," but locally it was one combined failure chain across candidate selection, sequential/round-robin scoping, wrong-speaker pruning, and OpenAI-compatible SSE/provider parsing. In the failing state, Marinara could generate or receive valid text, then lose it as an empty response or prune it as the wrong speaker. Separately, autonomous candidate selection could stop at one blocked/capped/cooldowned character instead of falling through to another eligible character. Together, those made offline multi-character chatter look dead or unreliable. The related SSE/provider bug matters because a valid provider response could be treated as empty before the autonomous exchange had anything to save or chain. ## Expected behavior - Offline/autonomous character exchange should select an eligible character and save the generated reply. - If the first candidate is capped, cooling down, blocked by status, or otherwise ineligible, the route should fall through to another eligible candidate. - Conversation mode with `groupResponseOrder: "sequential"` should behave like one-character-at-a-time generation, not merged multi-speaker generation. - Wrong-speaker pruning should remove actual wrong-speaker output without deleting valid target-character output. - OpenAI-compatible SSE/chat responses should preserve assistant text whether it appears in `choice.delta.content`, `choice.message.content`, or buffered provider result content. - Empty-response handling/logging should make it clear whether the loss happened at provider parsing, prompt/post-processing, wrong-speaker pruning, or save time. ## Actual behavior - Valid provider output could be interpreted as empty. - Autonomous/offline chatter could fail to persist even when characters were eligible. - Character exchange could choose one blocked/capped/cooldowned candidate and stop. - Sequential group conversations could produce multi-speaker output or labels that were later pruned incorrectly. - Wrong-speaker pruning could treat the target character's own display name as an "other speaker" name and delete a valid `Target: ...` response. Observed local error pattern: ```text The AI returned an empty response ``` Related OpenAI-compatible non-stream/parser failure seen with gateway metadata: ```text Failed to parse JSON response (Unexpected token ':', ": x-omniro"... is not valid JSON). Body starts with: : x-omniroute-cache-hit=false : x-omniroute-latency-ms=12 : x-omniroute-response-cost=0.0000000000 : x-omniroute-tokens-in=0 : x-omniroute-tokens-out=0 : x-omniroute-version=... : x-omniroute-model... ``` ## Steps to reproduce 1. Configure a group chat using Conversation mode. 2. Set group response order to sequential/round-robin style behavior. 3. Enable autonomous/offline character exchanges for multiple characters. 4. Use an OpenAI-compatible provider/gateway that returns chat output through SSE frames. 5. Let the autonomous/offline path trigger a character response while the user is away/offline. 6. Watch server logs and saved messages. Extra conditions that made the local bug easier to hit: - A multi-character room where the first autonomous candidate is blocked by budget, cooldown, or status, while another character is still eligible. - Model output includes speaker labels such as `CharacterName:`. - The target character's own name can appear in the wrong-speaker filtering list due to stale/duplicate name handling. - Provider output includes useful content in SSE frames or buffered provider content that the parser does not read. ## Environment - Marinara Engine version: locally patched 2.2.0 build - Install type: Docker - Host: Unraid running the Docker container - Client: web UI - Provider/gateway: OpenAI-compatible custom provider through ChubAI Soji Model SSE responses (Also tested in linking Marinara to OmniRoute with ChubAI Soji Provider enabled there) - Model path involved: OpenAI-compatible chat completions / SSE streaming ## Root cause chain This did not appear to be one single autonomous scheduler bug. It was a chain of smaller issues that masked each other: 1. Autonomous candidate selection returned/used only one top candidate. 2. `checkCharacterExchange()` returned only one randomly chosen candidate. 3. Route-level autonomous handling could not fall through from a blocked candidate to another eligible one. 4. Conversation mode with sequential response order was not consistently treated as individual target-character generation. 5. Individual group scoping was applied more reliably in roleplay/manual paths than in Conversation/sequential paths. 6. Wrong-speaker pruning could include the target character's own display name in the "other speakers" regex. 7. OpenAI-compatible SSE/provider parsing could miss valid text when it arrived in `choice.message.content` or buffered provider result content instead of only `choice.delta.content`. The result: valid autonomous turns were generated but not saved, saved as the wrong speaker, pruned to empty, or never attempted because candidate selection stopped too early. ## Code locations and local patch notes ### `packages/server/src/services/conversation/autonomous.service.ts` Relevant functions/behavior: - Added `isAutonomousDailyCapUncapped(meta)`. - Added `isAutonomousDailyBudgetExhausted(characterId, schedule, meta)`. - Changed `checkAutonomousMessaging()` so group chats return all eligible candidates in priority order, not only the top one. - Changed `checkCharacterExchange()` so it shuffles eligible characters and returns the whole ordered candidate list, not just one candidate. Important behavior: ```ts if (isAutonomousDailyCapUncapped(chatMeta)) return false; const sent = budget.counts[characterId] ?? 0; const cap = dailyCapForCharacter(schedule, chatMeta); return sent >= cap; ``` Why it matters: The autonomous system needs enough candidate information for route-level checks to skip a blocked character and try the next eligible one. ### `packages/server/src/routes/conversation.routes.ts` Relevant functions/behavior: - `evaluateAutonomousCandidate()` now calls `isAutonomousDailyBudgetExhausted()`. - Autonomous trigger route loops through returned `characterIds`, skips capped/cooldowned candidates, and starts generation for the first allowed one. - Catch-up user-inactivity path does the same. - Character-exchange endpoint chooses the first returned candidate whose daily budget is not exhausted. Important behavior: ```ts for (const characterId of result.characterIds) { const evaluation = evaluateAutonomousCandidate(chatId, characterId, schedule, meta); if (!evaluation.ok) { blockedReason = blockedReason ?? evaluation.reason; continue; } const generationStartedAt = markGenerationInProgress(chatId); return reply.send({ ...result, characterIds: [characterId], generationStartedAt, ...evaluation.intent, }); } ``` Why it matters: Before this, one blocked candidate could make the whole autonomous pass look blocked even when another character should have been allowed to respond. ### `packages/server/src/routes/generate.routes.ts` Relevant functions/behavior: - Conversation `groupResponseOrder === "sequential"` is treated like individual mode, same as manual. - Individual group message scoping now applies in conversation mode too, not only roleplay. - Added stricter per-target prompt: respond only as this character; do not write labels/dialogue/actions for other characters; let the next round-robin turn handle reactions. - Wrong-speaker guard removes the target's own display name from `otherSpeakerNames` before building the regex. - If response begins with another speaker, it can skip ahead to an embedded target prefix, drop wrong-speaker-only output, or prune leading wrong-speaker paragraphs instead of saving mislabeled text. - Empty-response logging was expanded so post-processing losses are visible. - Autonomous daily budget patch is skipped when chat meta is `autonomousDailyCapMode: "uncapped"`. Critical guard detail: ```ts const otherNames = charInfo .filter((c) => c.id !== targetCharId) .map((c) => c.name) .filter((name): name is string => Boolean(name)) .filter((name) => name.trim().toLocaleLowerCase() !== cName.trim().toLocaleLowerCase()) .map((name) => name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")); ``` Target-only prompt behavior: ```ts return [ `Respond ONLY as ${charName}.`, `Your entire answer is ${charName}'s next message only.`, `Do not write dialogue, narration, labels, or actions for anyone except ${charName}.`, otherNames.length > 0 ? `Forbidden speaker labels for this turn: ${otherNames.join(", ")}. Do not start any line with those names.` : null, `If you want another character to react, stop after ${charName}'s message and let the next round-robin turn handle them.`, ] .filter(Boolean) .join("\n"); ``` Why it matters: Round-robin/sequential generation only works if each generation pass is truly scoped to one target speaker. Otherwise characters can step on each other, write each other's reactions, or produce labels that later get pruned as wrong-speaker output. ### `packages/server/src/services/llm/providers/openai.provider.ts` Relevant functions/behavior: - SSE JSON recovery scans for a message-bearing payload instead of returning the first non-empty SSE frame. - Streaming parsing accepts both `choice.delta.content` and `choice.message.content`. - Buffered provider `result.content` is used when stream callbacks produce nothing but the provider result still contains text. Important behavior: ```ts const content = delta?.content ?? message?.content; if (typeof content === "string" && content) yield content; ``` Why it matters: Some OpenAI-compatible gateways/providers return useful assistant text in a final/full `message.content` frame or buffered result content. If Marinara only reads `delta.content`, a valid reply can collapse into "empty response." ### UI/types touched locally - `packages/shared/src/types/chat.ts` - Added `autonomousDailyCapMode?: "default" | "capped" | "uncapped"`. - `packages/client/src/components/chat/ChatSettingsDrawer.tsx` - Added `Power user: no daily cap`. - `packages/client/src/components/chat/CharacterScheduleEditorModal.tsx` - Clarified that power-user mode bypasses daily counter but not schedule/status/cooldowns. ## Logs, screenshots, or video Local verification after patch: - Health showed the patched build active. - Exact failing autonomous payload for `Group Convo` saved real messages after patch. - Logs showed non-empty resolved content and provider-content fallback instead of empty-response failure. - Living-room/group chatter produced multiple server-side follow-up turns. - DND still blocked correctly with `user_dnd`. - Away/server eligibility returned eligible after clearing a stale test lock. ## Additional context Short version: The bug was not just "autonomous failed" and not just "SSE parsing failed." It was a combined chain: - Candidate selection stopped too early. - Sequential/round-robin Conversation mode was not always individual/scoped. - Characters could step on each other by producing labels/dialogue/actions for other speakers. - Wrong-speaker pruning could delete valid target-character output. - Provider streaming sometimes put useful text somewhere Marinara did not read. Fixing those together made offline/autonomous bickering persist and chain correctly. ## Template check - [ ] I DID NOT read this template and provide the requested details. ## Patch appendix The full local diff is included below so maintainers can inspect or test the actual patch shape directly. It is scoped to the Marinara files involved in the autonomous/round-robin/wrong-speaker/SSE chain. [2.2.0 Patch for automatic offline character chatter.txt](https://github.com/user-attachments/files/29982099/2.2.0.Patch.for.automatic.offline.character.chatter.txt)
bsakaguchi 2026-10-21 05:43:57 +07:00
  • closed this issue
  • added the
    in-pr
    bug
    labels
Author
Owner

@SpicyMarinara commented on GitHub (Jul 13, 2026):

Implemented and validated in #3574. The PR is ready for review against staging.

<!-- gh-comment-id:4962318910 --> @SpicyMarinara commented on GitHub (Jul 13, 2026): Implemented and validated in #3574. The PR is ready for review against staging.
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#1935
No description provided.