[PR #824] [MERGED] fix(game-start): silent race recovery when an intro already exists #4792

Closed
opened 2026-10-22 04:10:42 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/824
Author: @Romuromylus
Created: 5/14/2026
Status: ✅ Merged
Merged: 5/14/2026
Merged by: @Romuromylus

Base: main ← Head: fix/game-start-race-recovery


📝 Commits (3)

  • f425513 fix(game-start): silent race recovery when an intro already exists
  • 82bd06f fix(game-start): atomic ready→active claim via patchMetadata
  • 7542bdd fix(game-start): make the entry guard idempotent on "active"

📊 Changes

3 files changed (+63 additions, -3 deletions)

View changed files

📝 packages/client/src/components/game/GameSurface.tsx (+8 -1)
📝 packages/client/src/hooks/use-game.ts (+6 -0)
📝 packages/server/src/routes/game.routes.ts (+49 -2)

📄 Description

Linked issue

Closes #821

Why this change

#821 reproduces the same Game Mode race as the earlier-fixed #321 — on 1.5.9, clicking Start Game snaps back to the idle Start Game screen mid-stream and a second click produces a duplicate GM intro turn. Confirmed in a live trace: two POST /api/game/start calls both return 200 because a concurrent chats.updateMetadata({ ...meta, … }) writer reverts gameSessionStatus from "active" back to "ready" between the two clicks.

#320 audited and migrated 7 stale-meta writes in packages/server/src/routes/generate.routes.ts to the freshChat → freshMeta → field-only update pattern. All 6 remaining chats.updateMetadata(input.chatId, …) sites in that file now re-fetch, but at least one stale-write writer remains elsewhere (likely in packages/server/src/routes/game.routes.ts) and the race still reproduces.

A complete audit of every chats.updateMetadata(…, { ...meta, … }) and a migration of partial updates to the existing race-safe chats.patchMetadata(…) helper at packages/server/src/services/storage/chats.storage.ts:303 is the proper root-cause fix. That is a large, code-touchy change. This PR ships a narrow defensive guard that makes the user-visible symptom impossible while the deeper audit happens separately.

What changed

Server — packages/server/src/routes/game.routes.ts

POST /game/start already throws when meta.gameSessionStatus !== "ready". After that check it now also lists the chat's messages and looks for any non-empty role: "assistant" message. If one exists, the game has clearly already started — the only way we got back into the "ready" branch is the race. Instead of throwing (which leaves the UI stuck on Start Game with a generic 500 toast) the handler:

  • emits a logger.warn describing the race recovery (so this is visible in logs if it fires in production),
  • writes gameSessionStatus: "active" back to the DB,
  • returns { status: "active", alreadyStarted: true }.

Client — packages/client/src/hooks/use-game.ts and packages/client/src/components/game/GameSurface.tsx

The StartGameResponse interface now carries an optional alreadyStarted flag. GameSurface's useStartGame.mutate onSuccess callback checks that flag and skips generateInitialGameTurn when it's true — so the second click no longer fires a second /api/generate. The chat detail invalidate that already runs on useStartGame.onSuccess re-fetches the freshly-restored "active" status, and the existing awaitingFirstTurn logic moves the UI past the Start Game screen.

Validation

  • pnpm check passes locally
  • Container (Docker / Podman) built and ran without issue
  • Ran the app, clicked through the changes manually
  • Checked edge cases (light + dark mode, mobile viewport, empty states, error paths)
  • Above manual verification completed (describe below)
  • Read and followed CONTRIBUTING.md

Manual verification notes

I tested on a fork build autoDeployed to a private EasyPanel instance. Both the stuck-state recovery path and the full fresh-game flow were verified:

  • Repro confirmed twice on a freshly-set-up Game Mode chat with HUD widgets (Fantasy / dark / heroic): clicking Start Game produces the intro typewriter, the screen falls back to the idle Start Game button mid-stream, the second click on that button reproduces the duplicate-intro pattern reported in #821 (two role: "assistant" messages back-to-back, no user message between).
  • Stuck-chat recovery (intro already saved, status reverted to "ready"): clicked Start Game once on the existing stuck chat. Server emitted the [game/start] Race recovery warn, returned alreadyStarted: true, client skipped generateInitialGameTurn. UI progressed past Start Game on the next chat refetch. No duplicate intro. Note: post-stream hooks (scene-wrap, generate-assets) that failed to fire on the original stuck stream are not re-played — the saved intro lacks background art on a recovered chat. That's acceptable for a race-recovery edge; fresh games are unaffected.
  • Fresh-game flow with the fix: new game from scratch, full setup, intro generation, race fires, screen snaps back to Start Game button, second click fires /game/start and gets alreadyStarted: true, no duplicate intro, no error toast, UI lands in the active game with exactly one GM intro message.

To-verify by upstream maintainers, on each platform's normal install (Docker / installer / source):

  • Manually verify Game Mode Start Game on a fresh chat — the first click should still kick off the intro generation as before, and the chat should contain exactly one role: "assistant" message at the end of the intro.
  • Manually verify that a forced-retry path (refresh between Start click and intro arriving) does not produce a duplicate intro.
  • Manually verify normal turns and /api/generate flow are unaffected — the new branch in /game/start only runs on the start path.

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed
  • Version/release files updated (only if this PR includes a version bump)

UI evidence (if applicable)

n/a — server-side guard + small client onSuccess branch. The user-visible difference is "second Start Game click no longer creates a duplicate intro turn."

Summary by CodeRabbit

  • Bug Fixes
    • Fixed a race condition where game initialization could be triggered multiple times. The system now detects when a game has already started and prevents redundant setup processes.

Review Change Stack


🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Pasta-Devs/Marinara-Engine/pull/824 **Author:** [@Romuromylus](https://github.com/Romuromylus) **Created:** 5/14/2026 **Status:** ✅ Merged **Merged:** 5/14/2026 **Merged by:** [@Romuromylus](https://github.com/Romuromylus) **Base:** `main` ← **Head:** `fix/game-start-race-recovery` --- ### 📝 Commits (3) - [`f425513`](https://github.com/Pasta-Devs/Marinara-Engine/commit/f42551365603bdf6ac2f301e3843a8cdb9cf6ccd) fix(game-start): silent race recovery when an intro already exists - [`82bd06f`](https://github.com/Pasta-Devs/Marinara-Engine/commit/82bd06f8d5be2cdc029b23c186b45485c9c083a5) fix(game-start): atomic ready→active claim via patchMetadata - [`7542bdd`](https://github.com/Pasta-Devs/Marinara-Engine/commit/7542bddadd6fd92839d96f7299edce8763695401) fix(game-start): make the entry guard idempotent on "active" ### 📊 Changes **3 files changed** (+63 additions, -3 deletions) <details> <summary>View changed files</summary> 📝 `packages/client/src/components/game/GameSurface.tsx` (+8 -1) 📝 `packages/client/src/hooks/use-game.ts` (+6 -0) 📝 `packages/server/src/routes/game.routes.ts` (+49 -2) </details> ### 📄 Description ## Linked issue Closes #821 ## Why this change [#821](https://github.com/Pasta-Devs/Marinara-Engine/issues/821) reproduces the same Game Mode race as the earlier-fixed [#321](https://github.com/Pasta-Devs/Marinara-Engine/issues/321) — on 1.5.9, clicking **Start Game** snaps back to the idle Start Game screen mid-stream and a second click produces a duplicate GM intro turn. Confirmed in a live trace: two `POST /api/game/start` calls **both return 200** because a concurrent `chats.updateMetadata({ ...meta, … })` writer reverts `gameSessionStatus` from `"active"` back to `"ready"` between the two clicks. [#320](https://github.com/Pasta-Devs/Marinara-Engine/pull/320) audited and migrated 7 stale-meta writes in `packages/server/src/routes/generate.routes.ts` to the `freshChat` → `freshMeta` → field-only update pattern. All 6 remaining `chats.updateMetadata(input.chatId, …)` sites in that file now re-fetch, but at least one stale-write writer remains elsewhere (likely in `packages/server/src/routes/game.routes.ts`) and the race still reproduces. A complete audit of every `chats.updateMetadata(…, { ...meta, … })` and a migration of partial updates to the existing race-safe `chats.patchMetadata(…)` helper at [packages/server/src/services/storage/chats.storage.ts:303](packages/server/src/services/storage/chats.storage.ts#L303) is the proper root-cause fix. That is a large, code-touchy change. This PR ships a narrow defensive guard that makes the user-visible symptom impossible while the deeper audit happens separately. ## What changed **Server — `packages/server/src/routes/game.routes.ts`** `POST /game/start` already throws when `meta.gameSessionStatus !== "ready"`. After that check it now also lists the chat's messages and looks for any non-empty `role: "assistant"` message. If one exists, the game has clearly already started — the only way we got back into the `"ready"` branch is the race. Instead of throwing (which leaves the UI stuck on Start Game with a generic 500 toast) the handler: - emits a `logger.warn` describing the race recovery (so this is visible in logs if it fires in production), - writes `gameSessionStatus: "active"` back to the DB, - returns `{ status: "active", alreadyStarted: true }`. **Client — `packages/client/src/hooks/use-game.ts`** and **`packages/client/src/components/game/GameSurface.tsx`** The `StartGameResponse` interface now carries an optional `alreadyStarted` flag. `GameSurface`'s `useStartGame.mutate` `onSuccess` callback checks that flag and **skips `generateInitialGameTurn`** when it's true — so the second click no longer fires a second `/api/generate`. The chat detail invalidate that already runs on `useStartGame.onSuccess` re-fetches the freshly-restored `"active"` status, and the existing `awaitingFirstTurn` logic moves the UI past the Start Game screen. ## Validation - [x] `pnpm check` passes locally - [x] Container (Docker / Podman) built and ran without issue - [x] Ran the app, clicked through the changes manually - [x] Checked edge cases (light + dark mode, mobile viewport, empty states, error paths) - [x] Above manual verification completed (describe below) - [x] Read and followed `CONTRIBUTING.md` ### Manual verification notes I tested on a fork build autoDeployed to a private EasyPanel instance. Both the stuck-state recovery path and the full fresh-game flow were verified: - **Repro confirmed twice** on a freshly-set-up Game Mode chat with HUD widgets (Fantasy / dark / heroic): clicking Start Game produces the intro typewriter, the screen falls back to the idle Start Game button mid-stream, the second click on that button reproduces the duplicate-intro pattern reported in #821 (two `role: "assistant"` messages back-to-back, no user message between). - **Stuck-chat recovery** (intro already saved, status reverted to `"ready"`): clicked Start Game once on the existing stuck chat. Server emitted the `[game/start] Race recovery` warn, returned `alreadyStarted: true`, client skipped `generateInitialGameTurn`. UI progressed past Start Game on the next chat refetch. No duplicate intro. Note: post-stream hooks (scene-wrap, generate-assets) that failed to fire on the original stuck stream are not re-played — the saved intro lacks background art on a recovered chat. That's acceptable for a race-recovery edge; fresh games are unaffected. - **Fresh-game flow with the fix:** new game from scratch, full setup, intro generation, race fires, screen snaps back to Start Game button, second click fires `/game/start` and gets `alreadyStarted: true`, no duplicate intro, no error toast, UI lands in the active game with exactly one GM intro message. To-verify by upstream maintainers, on each platform's normal install (Docker / installer / source): - Manually verify Game Mode Start Game on a fresh chat — the first click should still kick off the intro generation as before, and **the chat should contain exactly one `role: "assistant"` message** at the end of the intro. - Manually verify that a forced-retry path (refresh between Start click and intro arriving) does not produce a duplicate intro. - Manually verify normal turns and `/api/generate` flow are unaffected — the new branch in `/game/start` only runs on the start path. ## Docs and release impact - [x] No docs changes needed - [ ] Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed - [ ] Version/release files updated (only if this PR includes a version bump) ## UI evidence (if applicable) n/a — server-side guard + small client onSuccess branch. The user-visible difference is "second Start Game click no longer creates a duplicate intro turn." <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Fixed a race condition where game initialization could be triggered multiple times. The system now detects when a game has already started and prevents redundant setup processes. <!-- review_stack_entry_start --> [![Review Change Stack](https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg)](https://app.coderabbit.ai/change-stack/Pasta-Devs/Marinara-Engine/pull/824) <!-- review_stack_entry_end --> <!-- end of auto-generated comment: release notes by coderabbit.ai --> --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-22 04:10:42 +07:00
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#4792
No description provided.