[GH-ISSUE #2726] [Issue]: Client tracker mutations and live-write races lose manual edits and agent writes; rerun lifecycle not flagged #1370

Closed
opened 2026-10-21 05:32:32 +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/2726

Originally assigned to: @SpicyMarinara on GitHub.

Summary

Manual tracker edits and concurrent agent writes race each other with no reconciliation, producing the historically top-reported "tracker lost my manually-edited value" symptom. Array mutations (stats/inventory/quests/characters/custom) rebuild the next array from a stale closure-captured render prop instead of the live store, so a concurrent agent write to the same array is silently dropped. Manual debounced PATCHes can flush AFTER an agent's SSE write lands and overwrite it. The tracker re-run path never sets the isRefreshing flag, so the only edit-drop guard is inert during a rerun and mid-rerun edits are clobbered by the final refresh GET. A detached NPC-avatar generation does a multi-second read-modify-write of the whole presentCharacters array with no concurrency guard, overwriting any edit/retry write landing in the window. And avatar upload resolves the target NPC by a positional index captured at click time, so a reorder during the OS file dialog sends the image to the wrong character.


Bug 1 — Array mutations use a stale render prop, losing concurrent agent writes (high)

How it breaks the pipeline: updateInventoryItem/updateQuest/updatePersonaStats/updateCustomFields/updateCharacter spread the closure-captured prop array (the last render's snapshot), not useGameStateStore.getState().current. The whole array is sent to patchPlayerStats/patchField, overwriting any newer rows the agent added/changed since that render.

Steps to replicate: During/after a tracker re-run, the agent adds an inventory item; the user edits a different inventory row; the new item vanishes (same for quests/personaStats/customTrackerFields/presentCharacters).

Code trace: use-tracker-mutations.ts:169-216,233-237 rebuild from props inventory/quests/personaStats/customFields (sourced render-time TrackerSectionList.tsx:93-98); patchPlayerStatsField (use-game-state-patcher.ts:422-425) merges only OTHER playerStats fields from the live store, taking the array verbatim from the stale prop. Server _applyUpdate replaces playerStats wholesale (game-state.storage.ts:377-378). Contrast handleAvatarUpload (use-tracker-mutations.ts:91-98) which deliberately re-reads the live store — pattern known but not applied to array editors.

Bug 2 — Manual debounced PATCH overwrites a concurrent agent write (medium)

How it breaks the pipeline: Manual edits debounce the server PATCH by 500ms with manual:true; an agent SSE game_state_patch overwrites the store immediately. When the older debounced manual patch flushes after the agent's write landed, it PATCHes the pre-agent value, clobbering the agent's update and pinning a manual override.

Steps to replicate: Edit a tracker field within ~500ms of a tracker agent finishing mid-generation; the HUD shows the agent value then snaps back to the user value, which persists.

Code trace: use-game-state-patcher.ts:35 debounce const, :216-243 queue/timer, :288 flush PATCH, :415 guard only on store.isRefreshing (not set during streaming); store apply use-generate.ts:823-852; server applies field-only partial to last assistant snapshot (chats.routes.ts:1465-1513).

Bug 3 — Re-run never sets the refreshing flag; edit-drop guard inert (medium)

How it breaks the pipeline: retryAgents only calls setProcessing(true) on the agent store, never setRefreshingChat, so gameStateStore.isRefreshing stays false for the whole re-run. The patchGameStateField isRefreshing guard does not block edits during a re-run, inline inputs are not gated on trackerRetryBusy, and the always-on refreshVisibleGameStateAfterGeneration GET in the finally overwrites the store with authoritative state — losing a mid-rerun edit until reload.

Code trace: use-generate.ts:2406-2424 (setProcessing only), :2692-2700 finally GET; guard use-game-state-patcher.ts:415; refresh :744-762; swipe path DOES set/clear (ChatArea.tsx:1189/1232).

Bug 4 — NPC avatar generation clobbers newer presentCharacters (medium)

How it breaks the pipeline: A detached IIFE awaits multi-second generateImage, then re-reads presentCharacters, overlays avatar paths, and writes the WHOLE array back via updateByMessage (full replace) with no version/abort guard. Any presentCharacters write between the read and write (manual edit or retry-agents) is overwritten.

Steps to replicate: With auto NPC avatar generation enabled, after a character-tracker introduces a new NPC, edit that NPC's mood/outfit while avatars generate; the edit is overwritten when the avatar write lands.

Code trace: generate.routes.ts:7744 detached IIFE, await generateImage :7786, re-read :7819-7820, write :7839-7848; _applyUpdate full replace game-state.storage.ts:376-406; racers use-tracker-mutations.ts:128-134/use-game-state-patcher.ts:287-288 and retry-agents-route.ts:2193-2202; locks only protect locked fields :7831-7834.

Bug 5 — Avatar upload uses a stale click-time array index (low)

How it breaks the pipeline: openAvatarUpload(index) stores the render-time positional index and opens the file picker; handleAvatarUpload later indexes that into the LIVE store array at file-pick time. If a tracker re-run reorders/inserts presentCharacters while the OS dialog is open, the image is attached to the wrong NPC (and the id-based write-back derives from the wrong character, so it consistently writes to the wrong row).

Code trace: use-tracker-mutations.ts:55-65 (store index, open picker), :117-126 (read index, call handler), :63-65,68 (live array + targetCharacterId from wrong row); reorder source retry-agents-route.ts:2171,2203 + use-generate.ts:832.


Suggested Fix

  • Derive the base array from the live store at mutation time (useGameStateStore.getState().current, guard chatId, re-locate the row by id/index) for all array editors, mirroring handleAvatarUpload. (Bug 1.)
  • Pause/cancel pending manual game-state patches while a generation/tracker run is active (reuse discardPendingGameStatePatch / suppress queuePatch), or make the server PATCH revision/version-aware. (Bugs 2-3.)
  • Wrap the re-run lifecycle with setRefreshingChat/clearRefreshingChat (as swipe/delete do), gate inline tracker edits on trackerRetryBusy, and/or re-flush pending patches before the final refresh GET. (Bug 3.)
  • In the avatar IIFE, re-fetch at write time and update only avatarPath on the freshly-read row (or guard with a snapshot id/updatedAt check, skip if changed). (Bug 4.)
  • Capture a stable characterId at openAvatarUpload time and resolve by findIndex(characterId) in handleAvatarUpload. (Bug 5.)

Template checklist

  • pnpm check passes (TypeScript + ESLint)
  • Manually verify editing one inventory/quest/stat row during a tracker re-run does not drop an item the agent just added
  • Manually verify editing a field right as a tracker finishes does not clobber the agent's value
  • Manually verify a mid-re-run inline edit is not reverted by the post-run refresh
  • Manually verify a panel edit during NPC avatar generation survives the avatar write
  • Manually verify uploading an avatar attaches the image to the intended NPC even after a re-run reorders characters

Affected files

  • packages/client/src/features/tracker-panel/hooks/use-tracker-mutations.ts
  • packages/client/src/hooks/use-game-state-patcher.ts
  • packages/client/src/hooks/use-generate.ts
  • packages/server/src/routes/generate.routes.ts
  • packages/server/src/services/storage/game-state.storage.ts

Audit provenance

Found by a multi-agent static audit of the trackers/widgets subsystem (Round 1 + round-2 gap sweep + completeness critic, each finding adversarially verified). Severity: HIGH. Line numbers are against the staging working tree.

Note: this issue was AI-drafted from a static read of the code; the validation/test-plan boxes are 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/2726 Originally assigned to: @SpicyMarinara on GitHub. ## Summary Manual tracker edits and concurrent agent writes race each other with no reconciliation, producing the historically top-reported "tracker lost my manually-edited value" symptom. Array mutations (stats/inventory/quests/characters/custom) rebuild the next array from a stale closure-captured render prop instead of the live store, so a concurrent agent write to the same array is silently dropped. Manual debounced PATCHes can flush AFTER an agent's SSE write lands and overwrite it. The tracker re-run path never sets the `isRefreshing` flag, so the only edit-drop guard is inert during a rerun and mid-rerun edits are clobbered by the final refresh GET. A detached NPC-avatar generation does a multi-second read-modify-write of the whole `presentCharacters` array with no concurrency guard, overwriting any edit/retry write landing in the window. And avatar upload resolves the target NPC by a positional index captured at click time, so a reorder during the OS file dialog sends the image to the wrong character. --- ### Bug 1 — Array mutations use a stale render prop, losing concurrent agent writes (high) **How it breaks the pipeline:** `updateInventoryItem`/`updateQuest`/`updatePersonaStats`/`updateCustomFields`/`updateCharacter` spread the closure-captured prop array (the last render's snapshot), not `useGameStateStore.getState().current`. The whole array is sent to `patchPlayerStats`/`patchField`, overwriting any newer rows the agent added/changed since that render. **Steps to replicate:** During/after a tracker re-run, the agent adds an inventory item; the user edits a different inventory row; the new item vanishes (same for quests/personaStats/customTrackerFields/presentCharacters). **Code trace:** `use-tracker-mutations.ts:169-216,233-237` rebuild from props `inventory`/`quests`/`personaStats`/`customFields` (sourced render-time `TrackerSectionList.tsx:93-98`); `patchPlayerStatsField` (`use-game-state-patcher.ts:422-425`) merges only OTHER playerStats fields from the live store, taking the array verbatim from the stale prop. Server `_applyUpdate` replaces playerStats wholesale (`game-state.storage.ts:377-378`). Contrast `handleAvatarUpload` (`use-tracker-mutations.ts:91-98`) which deliberately re-reads the live store — pattern known but not applied to array editors. ### Bug 2 — Manual debounced PATCH overwrites a concurrent agent write (medium) **How it breaks the pipeline:** Manual edits debounce the server PATCH by 500ms with `manual:true`; an agent SSE `game_state_patch` overwrites the store immediately. When the older debounced manual patch flushes after the agent's write landed, it PATCHes the pre-agent value, clobbering the agent's update and pinning a manual override. **Steps to replicate:** Edit a tracker field within ~500ms of a tracker agent finishing mid-generation; the HUD shows the agent value then snaps back to the user value, which persists. **Code trace:** `use-game-state-patcher.ts:35` debounce const, `:216-243` queue/timer, `:288` flush PATCH, `:415` guard only on `store.isRefreshing` (not set during streaming); store apply `use-generate.ts:823-852`; server applies field-only partial to last assistant snapshot (`chats.routes.ts:1465-1513`). ### Bug 3 — Re-run never sets the refreshing flag; edit-drop guard inert (medium) **How it breaks the pipeline:** `retryAgents` only calls `setProcessing(true)` on the agent store, never `setRefreshingChat`, so `gameStateStore.isRefreshing` stays false for the whole re-run. The `patchGameStateField` `isRefreshing` guard does not block edits during a re-run, inline inputs are not gated on `trackerRetryBusy`, and the always-on `refreshVisibleGameStateAfterGeneration` GET in the finally overwrites the store with authoritative state — losing a mid-rerun edit until reload. **Code trace:** `use-generate.ts:2406-2424` (`setProcessing` only), `:2692-2700` finally GET; guard `use-game-state-patcher.ts:415`; refresh `:744-762`; swipe path DOES set/clear (`ChatArea.tsx:1189/1232`). ### Bug 4 — NPC avatar generation clobbers newer presentCharacters (medium) **How it breaks the pipeline:** A detached IIFE awaits multi-second `generateImage`, then re-reads `presentCharacters`, overlays avatar paths, and writes the WHOLE array back via `updateByMessage` (full replace) with no version/abort guard. Any presentCharacters write between the read and write (manual edit or retry-agents) is overwritten. **Steps to replicate:** With auto NPC avatar generation enabled, after a character-tracker introduces a new NPC, edit that NPC's mood/outfit while avatars generate; the edit is overwritten when the avatar write lands. **Code trace:** `generate.routes.ts:7744` detached IIFE, `await generateImage` `:7786`, re-read `:7819-7820`, write `:7839-7848`; `_applyUpdate` full replace `game-state.storage.ts:376-406`; racers `use-tracker-mutations.ts:128-134`/`use-game-state-patcher.ts:287-288` and `retry-agents-route.ts:2193-2202`; locks only protect locked fields `:7831-7834`. ### Bug 5 — Avatar upload uses a stale click-time array index (low) **How it breaks the pipeline:** `openAvatarUpload(index)` stores the render-time positional index and opens the file picker; `handleAvatarUpload` later indexes that into the LIVE store array at file-pick time. If a tracker re-run reorders/inserts presentCharacters while the OS dialog is open, the image is attached to the wrong NPC (and the id-based write-back derives from the wrong character, so it consistently writes to the wrong row). **Code trace:** `use-tracker-mutations.ts:55-65` (store index, open picker), `:117-126` (read index, call handler), `:63-65,68` (live array + targetCharacterId from wrong row); reorder source `retry-agents-route.ts:2171,2203` + `use-generate.ts:832`. --- ## Suggested Fix - Derive the base array from the live store at mutation time (`useGameStateStore.getState().current`, guard chatId, re-locate the row by id/index) for all array editors, mirroring `handleAvatarUpload`. (Bug 1.) - Pause/cancel pending manual game-state patches while a generation/tracker run is active (reuse `discardPendingGameStatePatch` / suppress `queuePatch`), or make the server PATCH revision/version-aware. (Bugs 2-3.) - Wrap the re-run lifecycle with `setRefreshingChat`/`clearRefreshingChat` (as swipe/delete do), gate inline tracker edits on `trackerRetryBusy`, and/or re-flush pending patches before the final refresh GET. (Bug 3.) - In the avatar IIFE, re-fetch at write time and update only `avatarPath` on the freshly-read row (or guard with a snapshot id/updatedAt check, skip if changed). (Bug 4.) - Capture a stable `characterId` at `openAvatarUpload` time and resolve by `findIndex(characterId)` in `handleAvatarUpload`. (Bug 5.) --- ## Template checklist - [ ] `pnpm check` passes (TypeScript + ESLint) - [ ] Manually verify editing one inventory/quest/stat row during a tracker re-run does not drop an item the agent just added - [ ] Manually verify editing a field right as a tracker finishes does not clobber the agent's value - [ ] Manually verify a mid-re-run inline edit is not reverted by the post-run refresh - [ ] Manually verify a panel edit during NPC avatar generation survives the avatar write - [ ] Manually verify uploading an avatar attaches the image to the intended NPC even after a re-run reorders characters --- ### Affected files - `packages/client/src/features/tracker-panel/hooks/use-tracker-mutations.ts` - `packages/client/src/hooks/use-game-state-patcher.ts` - `packages/client/src/hooks/use-generate.ts` - `packages/server/src/routes/generate.routes.ts` - `packages/server/src/services/storage/game-state.storage.ts` ### Audit provenance Found by a multi-agent static audit of the trackers/widgets subsystem (Round 1 + round-2 gap sweep + completeness critic, each finding adversarially verified). Severity: **HIGH**. Line numbers are against the `staging` working tree. > Note: this issue was AI-drafted from a static read of the code; the validation/test-plan boxes are intentionally left UNCHECKED for a human to verify before close.
Author
Owner

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

Fixed in dc41ffa0. Tracker array mutations now re-read the live game-state store before applying row edits/adds/removals, avatar upload targets a stable characterId instead of a click-time index, retry-agent tracker runs set/clear the game-state refreshing flag so edit guards engage, and incoming tracker SSE patches discard stale queued manual patches before applying authoritative state. Skipped as already addressed in current code: the NPC avatar generation path re-fetches the latest snapshot after image generation and overlays generated avatarPath values onto those fresh character rows instead of writing the original stale array.

<!-- gh-comment-id:4761818801 --> @SpicyMarinara commented on GitHub (Jun 21, 2026): Fixed in dc41ffa0. Tracker array mutations now re-read the live game-state store before applying row edits/adds/removals, avatar upload targets a stable characterId instead of a click-time index, retry-agent tracker runs set/clear the game-state refreshing flag so edit guards engage, and incoming tracker SSE patches discard stale queued manual patches before applying authoritative state. Skipped as already addressed in current code: the NPC avatar generation path re-fetches the latest snapshot after image generation and overlays generated avatarPath values onto those fresh character rows instead of writing the original stale array.
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#1370
No description provided.