[PR #5650] [MERGED] fix(client): stop stale server snapshots reverting newer chat metadata edits #6865

Closed
opened 2026-10-23 04:14:24 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/5650
Author: @kolacheee
Created: 8/29/2026
Status: ✅ Merged
Merged: 8/29/2026
Merged by: @kolacheee

Base: staging ← Head: fix/5641-guarded-cache-writers


📝 Commits (5)

  • e9738bd fix(client): stop stale server snapshots reverting newer chat metadata edits
  • 1763a3c test(e2e): make the stale-echo pin robust and add the changelog entry
  • 0f60d13 fix(client): address the verification findings on the snapshot guard
  • 5b77ae8 fix(client): mirror guarded game snapshots into the active-chat store
  • 9cd9ac2 fix(client): only fall back to activeChat when no chat is selected

📊 Changes

9 files changed (+274 additions, -27 deletions)

View changed files

📝 CHANGELOG.md (+1 -0)
📝 e2e/core-flows.e2e.ts (+152 -0)
📝 packages/client/src/components/chat/HomeProfessorMariChat.tsx (+4 -0)
📝 packages/client/src/components/game/GameSurface.tsx (+10 -2)
📝 packages/client/src/hooks/use-background-autonomous.ts (+6 -2)
📝 packages/client/src/hooks/use-chat-presets.ts (+4 -3)
📝 packages/client/src/hooks/use-chats.ts (+60 -11)
📝 packages/client/src/hooks/use-connections.ts (+3 -2)
📝 packages/client/src/hooks/use-game.ts (+34 -7)

📄 Description

Closes #5641

Why

The per-field metadata version guard lived only inside useUpdateChatMetadata. Every other mutation wrote its response chat back into the caches raw — so a response produced before a metadata edit but consumed after it replaced the whole cached chat, flipping the just-edited field back and unmounting the settings section it gates. With a refetch pending the flicker was brief; without one, the revert stuck until reload. The auto-fired autonomous-unread clear makes this reachable with completely ordinary behavior: open a chat with unread residue, toggle a setting while the clear round trip is in flight, and the toggle silently reverts. (Found during the #5636/#5640 verification pass.)

The fix

guardServerChatSnapshot(qc, chat, versionAtRequest) prepares any server snapshot for a cache write: metadata merges through the same per-field version guard useUpdateChatMetadata uses, keyed on a version captured when the request was issued — fields the user edited after that moment keep their local values; non-metadata fields stay server-authoritative; each writer keeps its original write target.

Converted writers: the chat PATCH (useUpdateChat, including its group-cache branch-selector patch), summary entries, the autonomous-unread clear, preset apply, the connection-delete chat detach, the background autonomous-unread mark, and the three per-chat game mutations (campaign progression, recruit, remove). The JSON-repair apply callback guards at version 0 (its request is issued by the shared repair flow, no pre-request snapshot exists) and relies on its existing immediate invalidation. Deliberately left raw, documented in place: game session-start and the Professor Mari load/switch writes — they target chats whose ids are unknown before the request, with no concurrent edits to protect.

One deletion-semantics case needed special handling (caught by the adversarial pass): the server clears unread state by deleting the metadata keys, so its response omits them and a merge would keep the cached residue forever — leaving a phantom unread count that refired a no-op clear on every switch back to the chat. That writer explicitly drops the three autonomousUnread* keys from the guarded result; nothing client-side ever patches them, so no field version can legitimately outrank their deletion.

The e2e pin

New test: chat settings survive a stale autonomous-unread echo. It seeds unread residue, lets the app's auto-clear fire, forwards the DELETE to the server immediately but holds its response, toggles Secret Plot on through the UI, confirms the server saved it, releases the stale echo, and asserts the toggle and its gated section survive — with the ordering pinned at every step (server-processed-before-toggle via the route state, browser-side response event before asserting, and a re-assert after a beat so a late-consumed echo can't slip past).

A/B on the final code: with the client fix reverted the test fails at the post-echo toggle assertion (Expected: checked, Received: unchecked — the revert, reproduced deterministically); with the fix, green 3/3 (--retries=0).

Getting the pin deterministic surfaced two reusable e2e lessons, both now encoded in the test: the sr-only switch inputs pass toBeChecked but hang check() forever (toggle through the visible label), and a test that times out with a route handler parked on a held promise hangs teardown and wedges every subsequent local run (the finally releases the hold and unrouteAll({ behavior: "ignoreErrors" })).

Verification

  • 3-reviewer adversarial pass over guard semantics, writer coverage, and the pin. It confirmed the version-capture points are correct for the subtle cases (preset apply intentionally overwrites pre-click edits and still does; only post-click edits outrank the response), found the deletion-semantics defect above plus a raw group-cache write in useUpdateChat that undid the guarded write (both fixed), and had the dead context fallbacks aligned to the conservative direction (?? 0).
  • pnpm check green (includes the e2e type lane).
  • Manually verify: open a chat that has an unread badge from autonomous messaging, immediately toggle any agent setting in Chat Settings while the badge is clearing, and confirm the toggle stays put; confirm the unread badge still clears normally and does not reappear when switching chats back and forth.

Notes

  • #5631 (server-side tx-gate window) is the follow-up and will be a separate PR, per the subsystem split discussed on the issues.
  • The stale-echo class in game-mode metadata (HUD/widget gates) is covered by the same guard through the converted game mutations.

Summary by CodeRabbit

  • Bug Fixes

    • Prevented delayed server responses from overwriting newer chat-setting changes.
    • Preserved recent updates when applying presets, clearing unread status, managing connections, and progressing gameplay.
    • Kept dependent chat controls enabled during concurrent updates.
  • Tests

    • Added an end-to-end regression test for stale unread responses and concurrent setting changes.
  • Documentation

    • Documented the fix in the changelog.

🔄 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/5650 **Author:** [@kolacheee](https://github.com/kolacheee) **Created:** 8/29/2026 **Status:** ✅ Merged **Merged:** 8/29/2026 **Merged by:** [@kolacheee](https://github.com/kolacheee) **Base:** `staging` ← **Head:** `fix/5641-guarded-cache-writers` --- ### 📝 Commits (5) - [`e9738bd`](https://github.com/Pasta-Devs/Marinara-Engine/commit/e9738bdf9fe953d53f326fa55ee81842a060cf6d) fix(client): stop stale server snapshots reverting newer chat metadata edits - [`1763a3c`](https://github.com/Pasta-Devs/Marinara-Engine/commit/1763a3c9b8fbb5afe3f23fafcbe8f820ddd87b31) test(e2e): make the stale-echo pin robust and add the changelog entry - [`0f60d13`](https://github.com/Pasta-Devs/Marinara-Engine/commit/0f60d131dbf0a0bd0f28529f67d1cbf570204703) fix(client): address the verification findings on the snapshot guard - [`5b77ae8`](https://github.com/Pasta-Devs/Marinara-Engine/commit/5b77ae86f953f6c363512dfd947c750a85de5f29) fix(client): mirror guarded game snapshots into the active-chat store - [`9cd9ac2`](https://github.com/Pasta-Devs/Marinara-Engine/commit/9cd9ac2dc6557f0e571ed49d1a0d6dbee4a050da) fix(client): only fall back to activeChat when no chat is selected ### 📊 Changes **9 files changed** (+274 additions, -27 deletions) <details> <summary>View changed files</summary> 📝 `CHANGELOG.md` (+1 -0) 📝 `e2e/core-flows.e2e.ts` (+152 -0) 📝 `packages/client/src/components/chat/HomeProfessorMariChat.tsx` (+4 -0) 📝 `packages/client/src/components/game/GameSurface.tsx` (+10 -2) 📝 `packages/client/src/hooks/use-background-autonomous.ts` (+6 -2) 📝 `packages/client/src/hooks/use-chat-presets.ts` (+4 -3) 📝 `packages/client/src/hooks/use-chats.ts` (+60 -11) 📝 `packages/client/src/hooks/use-connections.ts` (+3 -2) 📝 `packages/client/src/hooks/use-game.ts` (+34 -7) </details> ### 📄 Description Closes #5641 ## Why The per-field metadata version guard lived only inside `useUpdateChatMetadata`. Every other mutation wrote its response chat back into the caches raw — so a response produced *before* a metadata edit but consumed *after* it replaced the whole cached chat, flipping the just-edited field back and unmounting the settings section it gates. With a refetch pending the flicker was brief; without one, the revert stuck until reload. The auto-fired autonomous-unread clear makes this reachable with completely ordinary behavior: open a chat with unread residue, toggle a setting while the clear round trip is in flight, and the toggle silently reverts. (Found during the #5636/#5640 verification pass.) ## The fix `guardServerChatSnapshot(qc, chat, versionAtRequest)` prepares any server snapshot for a cache write: metadata merges through the same per-field version guard `useUpdateChatMetadata` uses, keyed on a version captured **when the request was issued** — fields the user edited after that moment keep their local values; non-metadata fields stay server-authoritative; each writer keeps its original write target. Converted writers: the chat PATCH (`useUpdateChat`, including its group-cache branch-selector patch), summary entries, the autonomous-unread clear, preset apply, the connection-delete chat detach, the background autonomous-unread mark, and the three per-chat game mutations (campaign progression, recruit, remove). The JSON-repair apply callback guards at version 0 (its request is issued by the shared repair flow, no pre-request snapshot exists) and relies on its existing immediate invalidation. Deliberately left raw, documented in place: game session-start and the Professor Mari load/switch writes — they target chats whose ids are unknown before the request, with no concurrent edits to protect. One deletion-semantics case needed special handling (caught by the adversarial pass): the server clears unread state by *deleting* the metadata keys, so its response omits them and a merge would keep the cached residue forever — leaving a phantom unread count that refired a no-op clear on every switch back to the chat. That writer explicitly drops the three `autonomousUnread*` keys from the guarded result; nothing client-side ever patches them, so no field version can legitimately outrank their deletion. ## The e2e pin New test: `chat settings survive a stale autonomous-unread echo`. It seeds unread residue, lets the app's auto-clear fire, **forwards the DELETE to the server immediately but holds its response**, toggles Secret Plot on through the UI, confirms the server saved it, releases the stale echo, and asserts the toggle and its gated section survive — with the ordering pinned at every step (server-processed-before-toggle via the route state, browser-side response event before asserting, and a re-assert after a beat so a late-consumed echo can't slip past). A/B on the final code: with the client fix reverted the test fails at the post-echo toggle assertion (`Expected: checked, Received: unchecked` — the revert, reproduced deterministically); with the fix, green 3/3 (`--retries=0`). Getting the pin deterministic surfaced two reusable e2e lessons, both now encoded in the test: the sr-only switch inputs pass `toBeChecked` but hang `check()` forever (toggle through the visible label), and a test that times out with a route handler parked on a held promise hangs teardown and wedges every subsequent local run (the `finally` releases the hold and `unrouteAll({ behavior: "ignoreErrors" })`). ## Verification - 3-reviewer adversarial pass over guard semantics, writer coverage, and the pin. It confirmed the version-capture points are correct for the subtle cases (preset apply intentionally overwrites pre-click edits and still does; only post-click edits outrank the response), found the deletion-semantics defect above plus a raw group-cache write in `useUpdateChat` that undid the guarded write (both fixed), and had the dead context fallbacks aligned to the conservative direction (`?? 0`). - `pnpm check` green (includes the e2e type lane). - Manually verify: open a chat that has an unread badge from autonomous messaging, immediately toggle any agent setting in Chat Settings while the badge is clearing, and confirm the toggle stays put; confirm the unread badge still clears normally and does not reappear when switching chats back and forth. ## Notes - #5631 (server-side tx-gate window) is the follow-up and will be a separate PR, per the subsystem split discussed on the issues. - The stale-echo class in *game-mode* metadata (HUD/widget gates) is covered by the same guard through the converted game mutations. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Prevented delayed server responses from overwriting newer chat-setting changes. * Preserved recent updates when applying presets, clearing unread status, managing connections, and progressing gameplay. * Kept dependent chat controls enabled during concurrent updates. * **Tests** * Added an end-to-end regression test for stale unread responses and concurrent setting changes. * **Documentation** * Documented the fix in the changelog. <!-- 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-23 04:14:24 +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#6865
No description provided.