[GH-ISSUE #2804] [Issue]: Game Setup Wizard "Cancel" hard-deletes the campaign with no confirmation — gameId/sessionStatus-gated auto-delete trap (CRITICAL data loss; #2790 fixes the #2801 trigger but not the trap) #1426

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

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

Originally assigned to: @SpicyMarinara on GitHub.

Summary

In Game Mode, when the Game Setup Wizard is shown for an existing campaign, clicking Cancel (or back) on the wizard performs an unconfirmed deleteChat.mutate(activeChatId) that TRUE-hard-deletes the entire campaign — chat row plus all gameStateSnapshots, gameCheckpoints, agentRuns, agentMemory, chatImages, and the on-disk gallery directory. There is no soft-delete or trash, so the campaign is irrecoverable from the app.

The wizard is shown whenever needsCreation || sessionStatus === "setup" is true (GameSurface.tsx:7968), and the same condition gates the delete on Cancel (GameSurface.tsx:8010). The user perceives this as their game "resetting to the setup screen," then "Cancel" silently destroys the campaign instead of just dismissing the wizard.

This issue is filed for the residual trap that survives the v2.0.1 hotfix PR #2790. #2790 fixes the specific client-cache corruption (#2801) that armed this trap via the Spotify-agent-removal path, but it does not touch the Cancel handler, so the unconfirmed auto-delete remains armed for every other path that can yield chatMeta.gameId === undefined or gameSessionStatus === "setup".

Symptom & DATA-LOSS impact

  • A Game Mode campaign that previously worked flips to the Game Setup Wizard ("settings reset" as the user perceives it).
  • The user clicks Cancel/back expecting to dismiss the wizard and return to their game.
  • Instead, the campaign is permanently and irrecoverably deleted — the chat, all narrative messages, all saved game state/checkpoints, generated images, and the gallery folder on disk are removed. This is a TRUE server-side hard delete, not an orphaned/recoverable record. There is no in-app recovery; only a filesystem/SQLite backup taken before the deletion can restore it.

Steps to reproduce

Two independent armings of the same trap:

A. Stale/absent gameId path (the #2801 family — fixed by #2790, but other cache-staleness paths remain):

  1. On released 2.0.0 (6b22be3b), open a Game Mode campaign that has gameId in metadata (e.g. a 1.6.x-origin campaign carried into 2.0.0).
  2. Open Chat Settings → Agents → remove the Spotify DJ agent (any agent toggle issues updateMeta.mutateAsync({ activeAgentIds }), ChatSettingsDrawer.tsx:1888,1924).
  3. Within the 60s useChat detail-cache staleTime, the surface flips to the Game Setup Wizard because the optimistic metadata merge dropped gameId.
  4. Without refreshing, click Cancel/back on the wizard.
  5. Campaign is permanently deleted. (Refreshing at step 3 before Cancel heals the cache and prevents the delete.)

B. sessionStatus === "setup" path (fully independent of #2801 and #2790):

  1. Have a campaign with a valid gameId AND persisted game state whose metadata left gameSessionStatus === "setup" (e.g. a prior setup that failed/was interrupted, GameSurface.tsx:6918 defaults to that value).
  2. The wizard renders (because sessionStatus === "setup", GameSurface.tsx:7968) even though needsCreation is false.
  3. Click Cancel → needsCreation || sessionStatus === "setup" is true → unconfirmed hard delete of a campaign that has a real game and state.

To verify the trap in isolation: force chatMeta.gameId undefined or gameSessionStatus === "setup" while a real game exists, render the wizard, and click Cancel.

Root cause (file:line — TRUE delete, not orphan)

  • packages/client/src/components/game/GameSurface.tsx:7952 — const needsCreation = !chatMeta.gameId; (negative signal: any absence of gameId is treated as "this is a brand-new game to create").
  • GameSurface.tsx:6918 — sessionStatus = chatMeta.gameSessionStatus || "active".
  • GameSurface.tsx:7968 — wizard renders when isSetupActive || needsCreation || sessionStatus === "setup".
  • GameSurface.tsx:8009-8016 — onCancel runs, when needsCreation || sessionStatus === "setup", useChatStore.getState().setActiveChatId(null); deleteChat.mutate(activeChatId); with no confirmation dialog and no emptiness/just-created check.
  • chatMeta is parseChatMetadata(chat.metadata) from the useChat cache (ChatArea.tsx:639-643, fed as a prop). parseChatMetadata (chat-display.ts:10-21) returns a non-array object as-is, so a corrupted/object-shaped or partial metadata yields gameId === undefined.
  • useDeleteChat (use-chats.ts:374-420) → DELETE /chats/:id (chats.routes.ts:949-970) → storage.remove (chats.storage.ts:506-518) cascades agentRuns/agentMemory/gameCheckpoints/gameStateSnapshots/chatImages, rmSyncs the gallery dir, and deletes the chat row. No soft-delete. This is a genuine irrecoverable hard delete, not an orphan.

How chatMeta.gameId goes undefined in the released #2801 path (for context): metadata is stored as a JSON string (schema/chats.ts:29 text("metadata"), not json mode; getById/list do raw selects with no parse). useUpdateChatMetadata.onMutate (use-chats.ts:510-518) does metadata: { ...existing.metadata, ...metadata }, spreading a string into numeric-indexed keys and dropping gameId; onSuccess (use-chats.ts:536) { ...data.metadata, ...existing.metadata } re-overlays the corrupted object and does not heal; useChat staleTime 60s keeps the corrupt cache live. The server never receives corrupted metadata — PATCH (chats.routes.ts:535-570) → patchMetadata (chats.storage.ts:388-410) merges only sent keys onto fresh DB metadata — which is why a refresh before Cancel heals it.

Relationship to #2801 and #2790

  • #2801 is the client-cache corruption that arms this trap on the Spotify/agent-toggle path: the optimistic string-spread drops gameId, making needsCreation true.
  • #2790 (v2.0.1 hotfix, target staging) — what it FIXES: it rewrites useUpdateChatMetadata in use-chats.ts, adding normalizeChatMetadataValue() which JSON-parses a string base before merging, plus mergeMetadataForVersion()/syncCachedChat(). onMutate now builds metadata from the parsed base + new keys; onSuccess/onError use the version-aware merge. This removes the string-spread that dropped gameId, so the #2801 corruption no longer occurs and the specific Spotify-agent-removal repro (path A) should stop reproducing. (#2790 also adds a defensive parseExtra in the DELETE route and cosmetic create/delete error toasts.) Verified at PR diff: use-chats.ts rewrite hunks add normalizeChatMetadataValue (~PR L5391+), onMutate/onSuccess/onError rewritten (~PR L5598+).
  • What #2790 does NOT fix (this issue): #2790's GameSurface.tsx hunks contain zero changes to onCancel/needsCreation/deleteChat (verified: the only match in those hunks is a cosmetic sessionStatus line). The DELETE route still calls storage.remove unconditionally, and chats.storage.ts remove() (L506-518) is untouched (the PR's chats.storage.ts hunks are at L63/L390/L426 only). So:
    • The unconfirmed, gameId/sessionStatus-gated auto-delete-on-Cancel remains armed.
    • gameId can be transiently/legitimately absent for reasons besides #2801: a stale or legacy list-cache row, an in-flight create before gameId persists, any future merge regression, or any path that yields chatMeta without gameId.
    • The sessionStatus === "setup" arming (path B) is entirely independent of #2801/#2790 and is not addressed at all.
  • Net: #2790 closes the corruption that armed this trap in the Spotify path; it does not disarm the trap itself.

Suggested fix

Defense-in-depth on the delete trap (independent of the cache fix):

  1. Require explicit confirmation before deleting from the wizard Cancel path (GameSurface.tsx:8009-8016), especially when the chat has messages or persisted game state. Cancel should default to just dismissing the wizard, not deleting.
  2. Auto-delete only a genuinely new/empty chat. Gate on a positive "just-created, never had a game" signal — e.g. message count 0 AND no gameStateSnapshots AND a created-in-session flag — instead of the negative !chatMeta.gameId. Never auto-delete when sessionStatus === "setup" but a real gameId/state exists.
  3. Read gameId from a trusted source (refetched server chat, or parseChatMetadata of the raw metadata string) before computing needsCreation, so a stale/corrupt cache can't drive a destructive decision.
  4. Server hardening: make storage.remove (chats.storage.ts:506-518) a soft-delete/trash with recovery, OR refuse to hard-delete a game chat that has messages or gameStateSnapshots without an explicit force flag.

User mitigation until fixed (2.0.1+): if a campaign flips to the setup wizard after an agent or settings change, refresh the page immediately and do NOT click Cancel — refreshing heals the cache. Avoid removing agents from existing campaigns until on 2.0.1+.

Recovery note: where deletion already occurred, it is a TRUE hard delete (chat row + gameStateSnapshots + gameCheckpoints + chatImages + gallery files) and is recoverable ONLY from a filesystem/SQLite backup taken before the deletion — not from within the app.

Affected files

  • packages/client/src/components/game/GameSurface.tsx (onCancel/needsCreation/sessionStatus — the trap)
  • packages/client/src/hooks/use-chats.ts (useUpdateChatMetadata corruption — #2790 fixes the corruption but not the trap; useDeleteChat)
  • packages/client/src/components/chat/ChatArea.tsx (chatMeta prop source)
  • packages/client/src/lib/chat-display.ts (parseChatMetadata returns object as-is)
  • packages/client/src/components/chat/ChatSettingsDrawer.tsx (agent-toggle trigger)
  • packages/server/src/routes/chats.routes.ts (DELETE route)
  • packages/server/src/services/storage/chats.storage.ts (remove() hard-delete cascade — soft-delete candidate)

Validation checklist

  • Reproduce path A on released 2.0.0 (6b22be3b): remove Spotify agent from a campaign with gameId, observe wizard flip within 60s, confirm Cancel hard-deletes the campaign.
  • Confirm #2790 (or staging with #2790 merged) prevents path A: agent removal no longer flips the surface to the wizard.
  • Reproduce path B independent of #2790: force gameSessionStatus === "setup" on a campaign with a valid gameId and state, render the wizard, click Cancel, confirm the campaign is still hard-deleted with no confirmation.
  • Verify the trap with chatMeta.gameId forced undefined (non-#2801 cache-staleness simulation): wizard Cancel deletes.
  • After fix: Cancel on an existing campaign's wizard dismisses without deleting (no confirmation triggered for genuinely-empty new chats only).
  • After fix: confirmation dialog appears before any delete from the wizard Cancel path when the chat has messages or game state.
  • After fix: deleting a brand-new empty game chat from Cancel still works as intended.
  • Server: confirm storage.remove either soft-deletes/recovers or refuses to hard-delete a game chat with messages/gameStateSnapshots without force.
  • Confirm no regression to useUpdateChatMetadata (#2790) gameId-preservation across agent toggles and metadata edits.

AI-investigated note

This issue was investigated and root-caused by an AI agent reading the released 2.0.0 code at tip 6b22be3b (verified still present at HEAD ecc32dbe; #2790 is NOT merged) and the open #2790 diff (gh pr diff 2790 --repo Pasta-Devs/Marinara-Engine). All file:line citations were verified against the actual source (accurate within ~1–2 lines). Mechanism: a TRUE user-triggered server-side hard delete via an unconfirmed gameId/sessionStatus-gated auto-delete on the Game Setup Wizard's Cancel handler. #2790 removes the #2801 cache corruption that arms this on the Spotify-agent path but leaves the delete trap itself armed. Maintainers should confirm the suggested fix before merge.

Originally created by @kolacheee on GitHub (Jun 22, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2804 Originally assigned to: @SpicyMarinara on GitHub. ## Summary In Game Mode, when the Game Setup Wizard is shown for an *existing* campaign, clicking **Cancel** (or back) on the wizard performs an unconfirmed `deleteChat.mutate(activeChatId)` that **TRUE-hard-deletes the entire campaign** — chat row plus all `gameStateSnapshots`, `gameCheckpoints`, `agentRuns`, `agentMemory`, `chatImages`, and the on-disk gallery directory. There is no soft-delete or trash, so the campaign is irrecoverable from the app. The wizard is shown whenever `needsCreation || sessionStatus === "setup"` is true (`GameSurface.tsx:7968`), and the same condition gates the delete on Cancel (`GameSurface.tsx:8010`). The user perceives this as their game "resetting to the setup screen," then "Cancel" silently destroys the campaign instead of just dismissing the wizard. This issue is filed for the **residual trap** that survives the v2.0.1 hotfix PR #2790. #2790 fixes the specific client-cache corruption (#2801) that armed this trap via the Spotify-agent-removal path, but it does **not** touch the Cancel handler, so the unconfirmed auto-delete remains armed for every other path that can yield `chatMeta.gameId === undefined` or `gameSessionStatus === "setup"`. ## Symptom & DATA-LOSS impact - A Game Mode campaign that previously worked flips to the Game Setup Wizard ("settings reset" as the user perceives it). - The user clicks Cancel/back expecting to dismiss the wizard and return to their game. - Instead, the campaign is **permanently and irrecoverably deleted** — the chat, all narrative messages, all saved game state/checkpoints, generated images, and the gallery folder on disk are removed. This is a TRUE server-side hard delete, **not** an orphaned/recoverable record. There is no in-app recovery; only a filesystem/SQLite backup taken *before* the deletion can restore it. ## Steps to reproduce Two independent armings of the same trap: **A. Stale/absent gameId path (the #2801 family — fixed by #2790, but other cache-staleness paths remain):** 1. On released 2.0.0 (`6b22be3b`), open a Game Mode campaign that has `gameId` in metadata (e.g. a 1.6.x-origin campaign carried into 2.0.0). 2. Open Chat Settings → Agents → remove the Spotify DJ agent (any agent toggle issues `updateMeta.mutateAsync({ activeAgentIds })`, `ChatSettingsDrawer.tsx:1888,1924`). 3. Within the 60s `useChat` detail-cache `staleTime`, the surface flips to the Game Setup Wizard because the optimistic metadata merge dropped `gameId`. 4. Without refreshing, click Cancel/back on the wizard. 5. Campaign is permanently deleted. (Refreshing at step 3 before Cancel heals the cache and prevents the delete.) **B. `sessionStatus === "setup"` path (fully independent of #2801 and #2790):** 1. Have a campaign with a valid `gameId` AND persisted game state whose metadata left `gameSessionStatus === "setup"` (e.g. a prior setup that failed/was interrupted, `GameSurface.tsx:6918` defaults to that value). 2. The wizard renders (because `sessionStatus === "setup"`, `GameSurface.tsx:7968`) even though `needsCreation` is false. 3. Click Cancel → `needsCreation || sessionStatus === "setup"` is true → unconfirmed hard delete of a campaign that has a real game and state. To verify the trap in isolation: force `chatMeta.gameId` undefined **or** `gameSessionStatus === "setup"` while a real game exists, render the wizard, and click Cancel. ## Root cause (file:line — TRUE delete, not orphan) - `packages/client/src/components/game/GameSurface.tsx:7952` — `const needsCreation = !chatMeta.gameId;` (negative signal: any absence of `gameId` is treated as "this is a brand-new game to create"). - `GameSurface.tsx:6918` — `sessionStatus = chatMeta.gameSessionStatus || "active"`. - `GameSurface.tsx:7968` — wizard renders when `isSetupActive || needsCreation || sessionStatus === "setup"`. - `GameSurface.tsx:8009-8016` — `onCancel` runs, when `needsCreation || sessionStatus === "setup"`, `useChatStore.getState().setActiveChatId(null); deleteChat.mutate(activeChatId);` with **no confirmation dialog** and **no emptiness/just-created check**. - `chatMeta` is `parseChatMetadata(chat.metadata)` from the `useChat` cache (`ChatArea.tsx:639-643`, fed as a prop). `parseChatMetadata` (`chat-display.ts:10-21`) returns a non-array object as-is, so a corrupted/object-shaped or partial metadata yields `gameId === undefined`. - `useDeleteChat` (`use-chats.ts:374-420`) → `DELETE /chats/:id` (`chats.routes.ts:949-970`) → `storage.remove` (`chats.storage.ts:506-518`) cascades `agentRuns`/`agentMemory`/`gameCheckpoints`/`gameStateSnapshots`/`chatImages`, `rmSync`s the gallery dir, and deletes the chat row. **No soft-delete.** This is a genuine irrecoverable hard delete, not an orphan. How `chatMeta.gameId` goes undefined in the released #2801 path (for context): `metadata` is stored as a JSON **string** (`schema/chats.ts:29` `text("metadata")`, not json mode; `getById`/`list` do raw selects with no parse). `useUpdateChatMetadata.onMutate` (`use-chats.ts:510-518`) does `metadata: { ...existing.metadata, ...metadata }`, spreading a **string** into numeric-indexed keys and dropping `gameId`; `onSuccess` (`use-chats.ts:536`) `{ ...data.metadata, ...existing.metadata }` re-overlays the corrupted object and does not heal; `useChat` `staleTime` 60s keeps the corrupt cache live. The **server never receives** corrupted metadata — PATCH (`chats.routes.ts:535-570`) → `patchMetadata` (`chats.storage.ts:388-410`) merges only sent keys onto fresh DB metadata — which is why a refresh before Cancel heals it. ## Relationship to #2801 and #2790 - **#2801** is the client-cache corruption that arms this trap on the Spotify/agent-toggle path: the optimistic string-spread drops `gameId`, making `needsCreation` true. - **#2790 (v2.0.1 hotfix, target staging) — what it FIXES:** it rewrites `useUpdateChatMetadata` in `use-chats.ts`, adding `normalizeChatMetadataValue()` which JSON-parses a string base **before** merging, plus `mergeMetadataForVersion()`/`syncCachedChat()`. `onMutate` now builds metadata from the parsed base + new keys; `onSuccess`/`onError` use the version-aware merge. This removes the string-spread that dropped `gameId`, so the **#2801 corruption no longer occurs** and the specific Spotify-agent-removal repro (path A) should stop reproducing. (#2790 also adds a defensive `parseExtra` in the DELETE route and cosmetic create/delete error toasts.) Verified at PR diff: use-chats.ts rewrite hunks add `normalizeChatMetadataValue` (~PR L5391+), onMutate/onSuccess/onError rewritten (~PR L5598+). - **What #2790 does NOT fix (this issue):** #2790's `GameSurface.tsx` hunks contain **zero** changes to `onCancel`/`needsCreation`/`deleteChat` (verified: the only match in those hunks is a cosmetic `sessionStatus` line). The DELETE route still calls `storage.remove` unconditionally, and `chats.storage.ts remove()` (L506-518) is **untouched** (the PR's chats.storage.ts hunks are at L63/L390/L426 only). So: - The unconfirmed, `gameId`/`sessionStatus`-gated **auto-delete-on-Cancel remains armed**. - `gameId` can be transiently/legitimately absent for reasons besides #2801: a stale or legacy list-cache row, an in-flight create before `gameId` persists, any future merge regression, or any path that yields `chatMeta` without `gameId`. - The **`sessionStatus === "setup"` arming (path B) is entirely independent of #2801/#2790** and is not addressed at all. - **Net:** #2790 closes the corruption that armed this trap *in the Spotify path*; it does not disarm the trap itself. ## Suggested fix Defense-in-depth on the delete trap (independent of the cache fix): 1. **Require explicit confirmation before deleting from the wizard Cancel path** (`GameSurface.tsx:8009-8016`), especially when the chat has messages or persisted game state. Cancel should default to *just dismissing the wizard*, not deleting. 2. **Auto-delete only a genuinely new/empty chat.** Gate on a *positive* "just-created, never had a game" signal — e.g. message count 0 AND no `gameStateSnapshots` AND a created-in-session flag — instead of the negative `!chatMeta.gameId`. Never auto-delete when `sessionStatus === "setup"` but a real `gameId`/state exists. 3. **Read `gameId` from a trusted source** (refetched server chat, or `parseChatMetadata` of the raw metadata string) before computing `needsCreation`, so a stale/corrupt cache can't drive a destructive decision. 4. **Server hardening:** make `storage.remove` (`chats.storage.ts:506-518`) a soft-delete/trash with recovery, OR refuse to hard-delete a game chat that has messages or `gameStateSnapshots` without an explicit `force` flag. User mitigation until fixed (2.0.1+): if a campaign flips to the setup wizard after an agent or settings change, **refresh the page immediately and do NOT click Cancel** — refreshing heals the cache. Avoid removing agents from existing campaigns until on 2.0.1+. Recovery note: where deletion already occurred, it is a TRUE hard delete (chat row + `gameStateSnapshots` + `gameCheckpoints` + `chatImages` + gallery files) and is recoverable ONLY from a filesystem/SQLite backup taken before the deletion — not from within the app. ## Affected files - `packages/client/src/components/game/GameSurface.tsx` (onCancel/needsCreation/sessionStatus — the trap) - `packages/client/src/hooks/use-chats.ts` (useUpdateChatMetadata corruption — #2790 fixes the corruption but not the trap; useDeleteChat) - `packages/client/src/components/chat/ChatArea.tsx` (chatMeta prop source) - `packages/client/src/lib/chat-display.ts` (parseChatMetadata returns object as-is) - `packages/client/src/components/chat/ChatSettingsDrawer.tsx` (agent-toggle trigger) - `packages/server/src/routes/chats.routes.ts` (DELETE route) - `packages/server/src/services/storage/chats.storage.ts` (remove() hard-delete cascade — soft-delete candidate) ## Validation checklist - [ ] Reproduce path A on released 2.0.0 (`6b22be3b`): remove Spotify agent from a campaign with `gameId`, observe wizard flip within 60s, confirm Cancel hard-deletes the campaign. - [ ] Confirm #2790 (or staging with #2790 merged) prevents path A: agent removal no longer flips the surface to the wizard. - [ ] Reproduce path B independent of #2790: force `gameSessionStatus === "setup"` on a campaign with a valid `gameId` and state, render the wizard, click Cancel, confirm the campaign is still hard-deleted with no confirmation. - [ ] Verify the trap with `chatMeta.gameId` forced undefined (non-#2801 cache-staleness simulation): wizard Cancel deletes. - [ ] After fix: Cancel on an existing campaign's wizard dismisses without deleting (no confirmation triggered for genuinely-empty new chats only). - [ ] After fix: confirmation dialog appears before any delete from the wizard Cancel path when the chat has messages or game state. - [ ] After fix: deleting a brand-new empty game chat from Cancel still works as intended. - [ ] Server: confirm `storage.remove` either soft-deletes/recovers or refuses to hard-delete a game chat with messages/`gameStateSnapshots` without `force`. - [ ] Confirm no regression to `useUpdateChatMetadata` (#2790) gameId-preservation across agent toggles and metadata edits. ## AI-investigated note This issue was investigated and root-caused by an AI agent reading the released 2.0.0 code at tip `6b22be3b` (verified still present at HEAD `ecc32dbe`; #2790 is NOT merged) and the open #2790 diff (`gh pr diff 2790 --repo Pasta-Devs/Marinara-Engine`). All file:line citations were verified against the actual source (accurate within ~1–2 lines). Mechanism: a TRUE user-triggered server-side hard delete via an unconfirmed `gameId`/`sessionStatus`-gated auto-delete on the Game Setup Wizard's Cancel handler. #2790 removes the #2801 cache corruption that arms this on the Spotify-agent path but leaves the delete trap itself armed. Maintainers should confirm the suggested fix before merge.
bsakaguchi 2026-10-21 05:33:39 +07:00
  • closed this issue
  • added the
    in-pr
    label
Author
Owner

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

Claiming this for a focused fix. I’ll patch the Game Setup Wizard cancel path so it cannot silently hard-delete existing campaigns, validate the repro path against current staging, and open a draft PR back to staging.

<!-- gh-comment-id:4773813097 --> @SpicyMarinara commented on GitHub (Jun 22, 2026): Claiming this for a focused fix. I’ll patch the Game Setup Wizard cancel path so it cannot silently hard-delete existing campaigns, validate the repro path against current staging, and open a draft PR back to 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#1426
No description provided.