mirror of
https://github.com/Pasta-Devs/Marinara-Engine.git
synced 2026-12-03 19:00:50 +07:00
[GH-ISSUE #2801] [Issue]: Roleplay: editing any chat setting wipes the applied Chat Preset + its agents/trackers for the session — useUpdateChatMetadata spreads chat.metadata (a JSON string) as an object, corrupting the cache #1427
Labels
No labels
android
bug
bugfix
ci
client
code freeze pause
container
dependencies
docs
documentation
duplicate
enhancement
feature
feature
feature
feature-creep
fixed-in-refactor
fixed-in-staging
good first issue
help wanted
in-pr
in-pr
needs-codeowner-decision
normal-scope
old-codebase
old-codebase
pull-request
qol
question
refactor
regression
revisit later
roadmap
scope-risk
scope-risk
server
server
shared
soup
upstream
windows
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
Pasta-Devs/Marinara-Engine#1427
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Originally created by @kolacheee on GitHub (Jun 22, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2801
Summary
In Roleplay (and Visual Novel) mode, performing almost any Chat Settings action — toggling Memory Recall / Tool Use, editing Advanced Parameters, applying a Featured Character Card on the Trackers tab, adding/removing a lorebook, etc. — visibly resets the Chat Preset dropdown to the "Custom settings / choose a preset" placeholder and makes the preset's agents and trackers disappear from the panel.
The trigger is a metadata-merge bug in
useUpdateChatMetadata(packages/client/src/hooks/use-chats.ts). At runtime,chat.metadatain the React Query cache is a JSON string (the raw DBTEXTcolumn), but the mutation hook spreads it as if it were an object. Spreading a string into an object literal produces a character-indexed object ({ "0": "{", "1": "\"", ... }) that loses every real metadata key, includingappliedChatPresetId,activeAgentIds, andagentOverrides. The drawer then reads that garbage object and the Chat Preset selection collapses to the placeholder.Two important clarifications versus the original report title:
promptPresetIdis NOT nulled.chat.promptPresetIdis a top-level chat column, and the metadata mutation preserves it (it is carried through via...existing). The RP Prompt Preset dropdown readschat.promptPresetIdand is unaffected. There is no code path in the metadata flow that nullspromptPresetId. What actually resets is the Chat Preset dropdown, which reads the metadata keyappliedChatPresetId. The title's "promptPresetId nulled / prompt preset reset to none" wording conflates two different presets; the real victim ismetadata.appliedChatPresetId.Symptom & UX impact
metadata.activeAgentIdsandmetadata.agentOverridesare wiped from the cached object, so the panel renders as if no preset agents are active.Steps to reproduce
ChatSettingsDrawer.tsx:2647→updateMeta.mutate({ id, enableMemoryRecall }))updateMeta.mutatecall sites in the drawer)Agent-toggle exception: Enabling/disabling an individual Agent also resets the Chat Preset dropdown to the placeholder, but the agents themselves stay visible. That is because the agent toggle patch writes
activeAgentIdsin the same mutation (ChatSettingsDrawer.tsx:2377,6320–6325, etc.). After the string-spread wipes the cached metadata, the freshly-patchedactiveAgentIdskey is re-applied on top, so it survives — butappliedChatPresetIdis still lost, so the dropdown still resets.Root cause
useUpdateChatMetadatainpackages/client/src/hooks/use-chats.tstreatschat.metadataas an object in both the optimistic update and the success merge:onMutate(line 514):onSuccess(line 536):But at runtime
chat.metadatais a JSON string, not an object:TEXT;chatsStorage.getByIdreturns the raw row unparsed —packages/server/src/services/storage/chats.storage.ts:246–249.patchMetadatawritesJSON.stringify(merged)and returnsgetById(id)—chats.storage.ts:404,408— so the PATCH response'smetadatais also a string.GET /chats/:idand metadata PATCH routes pass the row through without parsingmetadata(e.g.packages/server/src/routes/chats.routes.ts:286keeps it a string).return res.json()—packages/client/src/lib/api-client.ts:130— it does not transformmetadata.useChat/useChatshave noselecttransform —use-chats.ts:167–179— so the cache holdsmetadataas a string.Spreading a string into an object literal enumerates its characters:
{ ...someString }→{ "0": ..., "1": ..., ... }. SoonMutateline 514 replaceschat.metadatain the cache with a character-indexed object that has none of the real keys.onSuccessline 536 then spreads two strings together and stays garbage. (Verified withnode:appliedChatPresetId,activeAgentIds,agentOverridesall becomeundefined.)Why the drawer shows the placeholder:
ChatSettingsDrawer.tsx:618–621defensivelyJSON.parsesmetadataonly when it is a string. After corruption it is already an object, so the parse is skipped and the garbage object is used directly.appliedPresetId = metadata.appliedChatPresetId ?? null—ChatSettingsDrawer.tsx:2222— is nownull.chatPresetSelectValuetherefore falls back toCHAT_PRESET_UNAPPLIED_SELECT_VALUE(the placeholder) —ChatSettingsDrawer.tsx:2231–2232.metadata.activeAgentIds/metadata.agentOverridesare gone.Why the RP Prompt Preset dropdown is safe: it reads
chat.promptPresetId(a top-level column), e.g.ChatSettingsDrawer.tsx:622, and that column is preserved through...existingin the metadata merge. Only metadata keys are corrupted.Why the agent enable/disable action is the safe(r) exception: those patches include
activeAgentIdsin the same mutation body (ChatSettingsDrawer.tsx:2377,6320–6325). The spread order re-applies that key on top of the corrupted object, soactiveAgentIdssurvives — butappliedChatPresetIdis still wiped, so the Chat Preset dropdown still resets.Regression origin: introduced by commit
dfc55305("Fix remaining issue sweep regressions"), which added the optimisticonMutateobject-spread and changedonSuccessto{ ...data.metadata, ...existing.metadata }. The prior commitcaca4e0dwrotemetadata: data.metadata(the server string) with noonMutateand was string-safe. (Note: the original investigation namedcaca4e0das the regression — that is off by one;git log -Lon the hook confirmsdfc55305.)The server is not at fault:
patchMetadataparses, merges, and re-stringifies only the metadata column and never touchespromptPresetId.Suggested fix
Make
useUpdateChatMetadatatolerant of string-or-object metadata by parsing both sides before merging. The client already treats metadata as string-or-object in ~20 places (parseChatMetadata, guards atChatSettingsDrawer.tsx:565/619,use-game.ts:141,GameInput.tsx:135,use-scene.ts:121, etc.), so merging into a valid object (no re-stringify needed) is the minimal correct change:Keep the
onMutateoptimistic update and theonSuccess"keep newer optimistic metadata on top" ordering — those were added deliberately indfc55305to stop an older in-flight metadata PATCH response from clobbering a concurrent edit. (Note: the original investigation proposed removingonMutateand writing the server response straight into the cache; that is string-safe but partially reverts the concurrency fix and drops optimistic responsiveness, so prefer the parse-merge above.)Durable hardening (recommended, separate but ideally same PR): add a
selecttouseChat/useChats(use-chats.ts:167–179) that parsesmetadatato an object exactly once, so the cache representation is consistently an object and future spreads are always valid:This is lower risk than the investigation's alternative of retyping
Chat.metadataasstringat the API boundary, which would force touching many object-style consumers (e.g.ChatSidebar.tsx:60chat.metadata?.tags).Validate with
pnpm check. PerCLAUDE.md, target thestagingbranch.Affected files
packages/client/src/hooks/use-chats.ts—useUpdateChatMetadataonMutate(~514) andonSuccess(~536); optionalselectinuseChat/useChats(~167–179). Primary fix.packages/client/src/components/chat/ChatSettingsDrawer.tsx— consumer that surfaces the symptom (metadatamemo at 618–621;appliedChatPresetIdat 2222;chatPresetSelectValueat 2231–2232; Memory Recall toggle at 2647; agent-toggle patches at 2377 / 6320–6325). No change strictly required if the hook is fixed, but useful for verification.packages/shared/src/types/chat.ts—Chat.metadatais typedChatMetadata(line 92) while it is a string at the API boundary; relevant context for theselect-based hardening. Only edit if pursuing the type-level approach.Validation
pnpm installpnpm checkpasses (TypeScript + ESLint)useUpdateChatMetadata(onMutateandonSuccess)selectparsesmetadataonce inuseChat/useChatsappliedChatPresetId)chat.promptPresetId) is unaffected before and afterappliedChatPresetId,activeAgentIds, andagentOverridessurvive in the cached chatAI-investigated against released 2.0.0; verify before fixing.
@kolacheee commented on GitHub (Jun 22, 2026):
Related: #2769 (Advanced Parameters baking defaults into chat-level overrides) also surfaces as a "preset looks reset" symptom when editing Advanced Parameters. They are distinct mechanisms — #2769 is the AdvancedParametersSection override-baking; THIS issue (#2801) is the broader cache-corruption (
useUpdateChatMetadataspreading thechat.metadataJSON string as an object), which is what resets the applied Chat Preset + its agents/trackers across the ~8 other triggers (Memory Recall, Tool Use, Featured Card, lorebook add/remove, etc.). Fixing #2801 addresses the dominant cause; #2769 should still be fixed for the override-precedence half.@SpicyMarinara commented on GitHub (Jun 22, 2026):
Verified and addressed in PR #2790 / commit acab1fba: chat metadata updates normalize JSON-string metadata before merging, so editing settings no longer spreads a serialized metadata string into cache and resets the active preset/session state.
@kolacheee commented on GitHub (Jun 22, 2026):
Severe downstream consequence: in Game Mode, this metadata-cache corruption can drop
gameId, which flips an existing campaign to the Game Setup Wizard — and clicking Cancel there triggers an unconfirmed hard-delete of the whole campaign (chat + all game state/checkpoints/images, irrecoverable). Tracked in #2804. Note: PR #2790 fixes the corruption here (#2801) — which disarms the Spotify-agent trigger — but does not remove the auto-delete trap itself (#2804), which still fires whengameSessionStatus === 'setup'orgameIdis otherwise transiently absent.