[PR #6735] [MERGED] Add per-chat variables usable in your own messages #7305

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

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/6735
Author: @kentarofujiy
Created: 9/26/2026
Status: ✅ Merged
Merged: 9/28/2026
Merged by: @SpicyMarinara

Base: staging ← Head: feat/chat-variables


📝 Commits (10+)

  • e0cb2fb feat(chat): resolve per-chat {{name}} variables in messages
  • 6ad42bb fix(chat): keep chat variable edits made while a save is in flight
  • 519faad fix(chat): confirm chat variable writes and reset rows per chat
  • e3d39e4 Merge staging into feat/chat-variables and resolve conflicts
  • f97af84 Merge branch 'staging' into feat/chat-variables
  • 39cde53 fix(chat): preset precedence, queued renames, and legacy variable names
  • 5ece78a Merge branch 'staging' into feat/chat-variables
  • 21fd0b0 refactor(prompt): read a dry run's preset parts once
  • 2934ca0 Merge branch 'staging' into feat/chat-variables
  • f979493 Merge branch 'staging' into feat/chat-variables

📊 Changes

23 files changed (+1947 additions, -33 deletions)

View changed files

📝 CHANGELOG.md (+2 -0)
📝 docs/chats/chat-settings.md (+14 -0)
📝 docs/prompts/macros.md (+16 -2)
📝 docs/prompts/preset-variables.md (+1 -1)
➕ e2e/chat-variables.e2e.ts (+258 -0)
📝 packages/client/src/components/chat/ChatSettingsDrawer.tsx (+21 -0)
➕ packages/client/src/features/chat-settings/sections/ChatVariablesSection.tsx (+239 -0)
➕ packages/client/src/features/chat-settings/sections/chat-variables-rows.ts (+119 -0)
📝 packages/client/src/localization/locales/en.json (+14 -0)
📝 packages/server/src/routes/chats.routes.ts (+75 -1)
📝 packages/server/src/routes/generate.routes.ts (+41 -7)
📝 packages/server/src/routes/generate/dry-run-route.ts (+46 -10)
📝 packages/server/src/services/prompt/index.ts (+3 -0)
📝 packages/server/src/services/prompt/macro-context.ts (+67 -2)
📝 packages/shared/src/index.ts (+1 -0)
➕ packages/shared/src/utils/chat-variables.ts (+100 -0)
📝 packages/shared/src/utils/macro-engine.ts (+68 -8)
➕ scripts/regressions/chat-variables-persistence.regression.ts (+290 -0)
➕ scripts/regressions/chat-variables-preset-precedence.regression.ts (+136 -0)
➕ scripts/regressions/chat-variables-rows.regression.ts (+149 -0)

...and 3 more files

📄 Description

Linked issue

Closes #6734

Why this change

  • There was no way to give a name to a piece of text and reuse it in your own messages. Typing {{char1}} and having the model read "Mary" was not possible: {{setvar}} and {{getvar}} typed into a message both resolve to an empty string, because the client resolves macros before the message is stored with a context that carries no variable map, so the stored text is already blank and the server never sees the macro.
  • Preset variables do not help either — history is resolved before preset values are merged into the macro context, so a preset variable named char1 leaves the literal tag in the prompt.
  • A chat already persisted macroVariables, written by {{setvar}} from prompt sections and lorebook entries, but nothing in the UI showed or edited them. That state was invisible.
  • The only working route was a regex script with Apply To: User Input and Apply Mode: Only Prompt — obscure for what reads like a basic feature, and not per chat.

What changed

  • Chat Variables section in the Chat Settings drawer (packages/client/src/features/chat-settings/sections/ChatVariablesSection.tsx): name/value rows, add and remove, commit on blur or Enter, an atomic rename, and live name validation. It reuses the existing per-chat macroVariables store, so values a prompt or lorebook set show up as editable rows.
  • {{NAME}} catch-all falls back to the chat's variables after the preset variables (packages/shared/src/utils/macro-engine.ts). Every path that already passes that map starts working at once: typed messages, prompt sections, lorebooks, character cards, Peek Prompt. Preset variables keep precedence on a name clash. The {{#if}} operand paths get the same fallback.
  • The lookup now requires an own string property, which also fixes a pre-existing leak it would otherwise have widened: {{toString}} previously resolved to "function toString() { [native code] }" in any macro-enabled field.
  • Naming rules in a new shared helper (packages/shared/src/utils/chat-variables.ts), with the reserved set derived from SUPPORTED_MACROS rather than hand-maintained. A built-in macro name is refused, because a built-in always resolves first and such a variable could never be read.
  • PATCH /chats/:id/metadata merges macroVariables instead of replacing them, with a null value meaning removal. A generation persists its own {{setvar}} writes into the same key mid-request, so a whole-map write from the drawer would have dropped them. A combined patch is refused rather than silently skipping the other keys' handling.
  • Chat export resolves them too, so a transcript reads "Mary" rather than the raw tag.
  • Regressions: scripts/regressions/chat-variables.regression.ts (lookup order, prototype guards, conditionals, naming rules) and scripts/regressions/chat-variables-persistence.regression.ts (merge and removal semantics against the real route), plus additions to prompt.regression.ts for history resolution and preview isolation.
  • Docs: docs/prompts/macros.md, docs/prompts/preset-variables.md, docs/chats/chat-settings.md, and a CHANGELOG.md [Unreleased] entry.

Behavior changes to be aware of

  1. The "unknown tags stay literal" promise narrows. docs/prompts/macros.md said any unknown {{name}} survives verbatim. A name matching a chat variable now resolves instead, so decorative {{mood}} text in a chat that also defines mood will expand. Documented in the same change.
  2. Assistant history goes through the same resolution pass. If a model emits a literal {{mood}} and a variable of that name exists, it expands next turn. The escape hatch, if it ever bites, is a resolve option that is on for prompt paths and off for assistant history — deliberately not built up front.
  3. {{setvar}} shares the same store, while newer editor changes win over a generation started from an older snapshot.

Validation

Final integration head: dfbdad7a5, based on staging 91163c901.

  • Full pnpm check and all four chat-variable regression files pass. Prompt regressions also passed for the macro/assembly changes.

  • 24/24 focused browser cases pass on the combined navigation base, across desktop Chromium, mobile Chromium and mobile WebKit. The seven-case UI smoke suite also passes for the final feature changes; required CI repeats smoke on each integration head.

  • Browser coverage includes successful and failed queued renames/deletions, keeping an independently recreated original name, and reverting a value while its earlier save is pending. Those failure cases were reproduced before their fixes.

  • The metadata regression observes the route's actual database read instead of relying on a timer. Restoring the old stale-metadata validation makes it fail with 200 instead of 400. A separate regression pins serialization of legacy prototype-key rename deletions.

  • Local CodeRabbit's full review returned five findings: four fixed (fresh metadata validation, redundant spreading, character-reference name collisions, and character-scoped preset deferral); the interpolation suggestion was rejected because EXAMPLE_TAG already supplies {{char1}} to the example token correctly. The persistence, queued-edit, and final rename follow-up reviews completed with zero findings. The hosted review of 9c150f2de raised three minor findings, all addressed: pristine draft validation, filtering the queued-save fixture to variable writes, and a shorter changelog. Supplemental local review of all four follow-up files completed with zero findings. Hosted review completed on dfbdad7a5 with no new findings, and all required checks passed before merge.

  • The full local Node run passed 419/420 files. The sole local failure is the unchanged Linux-specific decision-sidecar-runtime case on macOS; that case passed in Linux CI. The CI failure in open-issues was a stale source-pattern assertion: it now directly checks the bounded merge behavior and verifies the route uses it. The corrected file passes locally, and full Linux CI on dfbdad7a5 passed all 420/420 regression files.

  • 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

The automated browser runs and screenshots use isolated synthetic data. Real-provider generation and physical-device testing are not claimed by this integration pass. The contributor's existing checklist marks are preserved above.

Still to confirm in a real browser, per mode:

  1. Roleplay chat → Chat Settings → Chat Variables → add char1 = Mary. Reopen the drawer; the value persists.
  2. Send {{char1}} walks in. The bubble shows the raw tag by design; Peek Prompt shows "Mary walks in."
  3. Reload the app and send another message using {{char1}} — still resolves.
  4. Change the value to Anna, then swipe the last reply. Peek Prompt shows "Anna" for both turns, proving resolution happens at prompt-build time.
  5. Open a second chat: the section is empty and {{char1}} stays literal in Peek Prompt.
  6. Delete a variable while a generation streams. After the stream ends, reopen the drawer — the row is still gone.
  7. Put {{setvar::mood::tense}} in a lorebook entry, generate, reopen the drawer — mood appears as an editable row.
  8. Try to add a variable named char (refused as reserved) and my.var (refused on format).
  9. Repeat steps 1–3 in a Conversation chat and a Game chat — history resolution is not mode-gated, so all three must work.
  10. Export the chat as text: "Mary" appears, not the tag.
  11. With a preset that defines a preset variable named char1, the preset value wins in Peek Prompt.
  12. Light and dark mode, and a narrow viewport, for the new drawer section.

Container validation is supplied by the required GitHub container check; live-provider and human manual verification remain separate from the automated evidence above.

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed
  • Translated docs on the docs-i18n branch updated to match, or a [docs-i18n] follow-up issue opened (see CONTRIBUTING.md § Translated documentation)
  • Version/release files updated (only if this PR includes a version bump)

docs/prompts/macros.md, docs/prompts/preset-variables.md and docs/chats/chat-settings.md are updated here, along with a CHANGELOG.md [Unreleased] entry. No version bump. Translation follow-up: #6792 covers those three paths.

UI evidence (if applicable)

Before/after screenshots in dark and light themes, desktop Chromium and iPhone-sized WebKit. Download the self-contained HTML gallery from the gist to view its embedded original PNG captures. All screenshots use disposable synthetic data; browser emulation is not a physical-device test.

Summary by CodeRabbit

  • New Features
    • Add, edit, rename, and remove chat-specific variables in Chat Settings. Reference them with double-brace tags in prompts and messages; tags remain visible while the AI receives their values. Editing a variable also updates earlier turns that use its tag.
    • Variables persist across restarts and share storage with {{setvar}}, which can overwrite a matching name. Preset variables take precedence over chat variables, including in conditionals. Unmatched tags remain unchanged; built-in macro names are reserved, and each chat supports up to 500 variables.
  • Bug Fixes
    • Generation preserves newer edits and removals, and queued changes continue targeting the correct variable during renames.
  • Documentation
    • Updated guidance on chat variables, naming rules, resolution, and {{setvar}} storage.

🔄 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/6735 **Author:** [@kentarofujiy](https://github.com/kentarofujiy) **Created:** 9/26/2026 **Status:** ✅ Merged **Merged:** 9/28/2026 **Merged by:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Base:** `staging` ← **Head:** `feat/chat-variables` --- ### 📝 Commits (10+) - [`e0cb2fb`](https://github.com/Pasta-Devs/Marinara-Engine/commit/e0cb2fb67360f4b20b56edd369ceb5db9bd5e39d) feat(chat): resolve per-chat {{name}} variables in messages - [`6ad42bb`](https://github.com/Pasta-Devs/Marinara-Engine/commit/6ad42bb6f1ed0ea3f23ac46c267a78a234626b26) fix(chat): keep chat variable edits made while a save is in flight - [`519faad`](https://github.com/Pasta-Devs/Marinara-Engine/commit/519faad13cf206738f46a8f3fef373b77206e930) fix(chat): confirm chat variable writes and reset rows per chat - [`e3d39e4`](https://github.com/Pasta-Devs/Marinara-Engine/commit/e3d39e45556ec215d20634c9e2bf004d1a9850a7) Merge staging into feat/chat-variables and resolve conflicts - [`f97af84`](https://github.com/Pasta-Devs/Marinara-Engine/commit/f97af84ae0d55f79454d4ae40af8dc3955b0e1e0) Merge branch 'staging' into feat/chat-variables - [`39cde53`](https://github.com/Pasta-Devs/Marinara-Engine/commit/39cde53050c2a879215bab8aef2eb496dd243ee9) fix(chat): preset precedence, queued renames, and legacy variable names - [`5ece78a`](https://github.com/Pasta-Devs/Marinara-Engine/commit/5ece78a954aa89d61977bba25967ba61ef758ec8) Merge branch 'staging' into feat/chat-variables - [`21fd0b0`](https://github.com/Pasta-Devs/Marinara-Engine/commit/21fd0b0f5721389cba3f8ace0665468e6a36caef) refactor(prompt): read a dry run's preset parts once - [`2934ca0`](https://github.com/Pasta-Devs/Marinara-Engine/commit/2934ca0a91f44e2f9836a717141007e183e9080b) Merge branch 'staging' into feat/chat-variables - [`f979493`](https://github.com/Pasta-Devs/Marinara-Engine/commit/f9794937bdeffd0d231667a45a524a4d2415286a) Merge branch 'staging' into feat/chat-variables ### 📊 Changes **23 files changed** (+1947 additions, -33 deletions) <details> <summary>View changed files</summary> 📝 `CHANGELOG.md` (+2 -0) 📝 `docs/chats/chat-settings.md` (+14 -0) 📝 `docs/prompts/macros.md` (+16 -2) 📝 `docs/prompts/preset-variables.md` (+1 -1) ➕ `e2e/chat-variables.e2e.ts` (+258 -0) 📝 `packages/client/src/components/chat/ChatSettingsDrawer.tsx` (+21 -0) ➕ `packages/client/src/features/chat-settings/sections/ChatVariablesSection.tsx` (+239 -0) ➕ `packages/client/src/features/chat-settings/sections/chat-variables-rows.ts` (+119 -0) 📝 `packages/client/src/localization/locales/en.json` (+14 -0) 📝 `packages/server/src/routes/chats.routes.ts` (+75 -1) 📝 `packages/server/src/routes/generate.routes.ts` (+41 -7) 📝 `packages/server/src/routes/generate/dry-run-route.ts` (+46 -10) 📝 `packages/server/src/services/prompt/index.ts` (+3 -0) 📝 `packages/server/src/services/prompt/macro-context.ts` (+67 -2) 📝 `packages/shared/src/index.ts` (+1 -0) ➕ `packages/shared/src/utils/chat-variables.ts` (+100 -0) 📝 `packages/shared/src/utils/macro-engine.ts` (+68 -8) ➕ `scripts/regressions/chat-variables-persistence.regression.ts` (+290 -0) ➕ `scripts/regressions/chat-variables-preset-precedence.regression.ts` (+136 -0) ➕ `scripts/regressions/chat-variables-rows.regression.ts` (+149 -0) _...and 3 more files_ </details> ### 📄 Description ## Linked issue Closes #6734 ## Why this change - There was no way to give a name to a piece of text and reuse it in your own messages. Typing `{{char1}}` and having the model read "Mary" was not possible: `{{setvar}}` and `{{getvar}}` typed into a message both resolve to an empty string, because the client resolves macros before the message is stored with a context that carries no variable map, so the stored text is already blank and the server never sees the macro. - Preset variables do not help either — history is resolved before preset values are merged into the macro context, so a preset variable named `char1` leaves the literal tag in the prompt. - A chat already persisted `macroVariables`, written by `{{setvar}}` from prompt sections and lorebook entries, but nothing in the UI showed or edited them. That state was invisible. - The only working route was a regex script with **Apply To: User Input** and **Apply Mode: Only Prompt** — obscure for what reads like a basic feature, and not per chat. ## What changed - **Chat Variables section** in the Chat Settings drawer (`packages/client/src/features/chat-settings/sections/ChatVariablesSection.tsx`): name/value rows, add and remove, commit on blur or Enter, an atomic rename, and live name validation. It reuses the existing per-chat `macroVariables` store, so values a prompt or lorebook set show up as editable rows. - **`{{NAME}}` catch-all falls back to the chat's variables** after the preset variables (`packages/shared/src/utils/macro-engine.ts`). Every path that already passes that map starts working at once: typed messages, prompt sections, lorebooks, character cards, Peek Prompt. Preset variables keep precedence on a name clash. The `{{#if}}` operand paths get the same fallback. - **The lookup now requires an own string property**, which also fixes a pre-existing leak it would otherwise have widened: `{{toString}}` previously resolved to `"function toString() { [native code] }"` in any macro-enabled field. - **Naming rules** in a new shared helper (`packages/shared/src/utils/chat-variables.ts`), with the reserved set derived from `SUPPORTED_MACROS` rather than hand-maintained. A built-in macro name is refused, because a built-in always resolves first and such a variable could never be read. - **`PATCH /chats/:id/metadata` merges `macroVariables` instead of replacing them**, with a `null` value meaning removal. A generation persists its own `{{setvar}}` writes into the same key mid-request, so a whole-map write from the drawer would have dropped them. A combined patch is refused rather than silently skipping the other keys' handling. - **Chat export resolves them too**, so a transcript reads "Mary" rather than the raw tag. - Regressions: `scripts/regressions/chat-variables.regression.ts` (lookup order, prototype guards, conditionals, naming rules) and `scripts/regressions/chat-variables-persistence.regression.ts` (merge and removal semantics against the real route), plus additions to `prompt.regression.ts` for history resolution and preview isolation. - Docs: `docs/prompts/macros.md`, `docs/prompts/preset-variables.md`, `docs/chats/chat-settings.md`, and a `CHANGELOG.md` `[Unreleased]` entry. ### Behavior changes to be aware of 1. **The "unknown tags stay literal" promise narrows.** `docs/prompts/macros.md` said any unknown `{{name}}` survives verbatim. A name matching a chat variable now resolves instead, so decorative `{{mood}}` text in a chat that also defines `mood` will expand. Documented in the same change. 2. **Assistant history goes through the same resolution pass.** If a model emits a literal `{{mood}}` and a variable of that name exists, it expands next turn. The escape hatch, if it ever bites, is a resolve option that is on for prompt paths and off for assistant history — deliberately not built up front. 3. **`{{setvar}}` shares the same store**, while newer editor changes win over a generation started from an older snapshot. ## Validation Final integration head: `dfbdad7a5`, based on staging `91163c901`. - Full `pnpm check` and all four chat-variable regression files pass. Prompt regressions also passed for the macro/assembly changes. - **24/24 focused browser cases pass** on the combined navigation base, across desktop Chromium, mobile Chromium and mobile WebKit. The seven-case UI smoke suite also passes for the final feature changes; required CI repeats smoke on each integration head. - Browser coverage includes successful and failed queued renames/deletions, keeping an independently recreated original name, and reverting a value while its earlier save is pending. Those failure cases were reproduced before their fixes. - The metadata regression observes the route's actual database read instead of relying on a timer. Restoring the old stale-metadata validation makes it fail with 200 instead of 400. A separate regression pins serialization of legacy prototype-key rename deletions. - Local CodeRabbit's full review returned five findings: four fixed (fresh metadata validation, redundant spreading, character-reference name collisions, and character-scoped preset deferral); the interpolation suggestion was rejected because `EXAMPLE_TAG` already supplies `{{char1}}` to the `example` token correctly. The persistence, queued-edit, and final rename follow-up reviews completed with zero findings. The hosted review of `9c150f2de` raised three minor findings, all addressed: pristine draft validation, filtering the queued-save fixture to variable writes, and a shorter changelog. Supplemental local review of all four follow-up files completed with zero findings. Hosted review completed on `dfbdad7a5` with no new findings, and all required checks passed before merge. - The full local Node run passed 419/420 files. The sole local failure is the unchanged Linux-specific `decision-sidecar-runtime` case on macOS; that case passed in Linux CI. The CI failure in `open-issues` was a stale source-pattern assertion: it now directly checks the bounded merge behavior and verifies the route uses it. The corrected file passes locally, and full Linux CI on `dfbdad7a5` passed all 420/420 regression files. - [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 The automated browser runs and screenshots use isolated synthetic data. Real-provider generation and physical-device testing are not claimed by this integration pass. The contributor's existing checklist marks are preserved above. Still to confirm in a real browser, per mode: 1. Roleplay chat → Chat Settings → **Chat Variables** → add `char1` = `Mary`. Reopen the drawer; the value persists. 2. Send `{{char1}} walks in.` The bubble shows the raw tag by design; **Peek Prompt** shows "Mary walks in." 3. Reload the app and send another message using `{{char1}}` — still resolves. 4. Change the value to `Anna`, then swipe the last reply. Peek Prompt shows "Anna" for **both** turns, proving resolution happens at prompt-build time. 5. Open a second chat: the section is empty and `{{char1}}` stays literal in Peek Prompt. 6. Delete a variable while a generation streams. After the stream ends, reopen the drawer — the row is still gone. 7. Put `{{setvar::mood::tense}}` in a lorebook entry, generate, reopen the drawer — `mood` appears as an editable row. 8. Try to add a variable named `char` (refused as reserved) and `my.var` (refused on format). 9. Repeat steps 1–3 in a Conversation chat and a Game chat — history resolution is not mode-gated, so all three must work. 10. Export the chat as text: "Mary" appears, not the tag. 11. With a preset that defines a preset variable named `char1`, the preset value wins in Peek Prompt. 12. Light and dark mode, and a narrow viewport, for the new drawer section. Container validation is supplied by the required GitHub container check; live-provider and human manual verification remain separate from the automated evidence above. ## Docs and release impact - [x] No docs changes needed - [x] Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed - [x] Translated docs on the `docs-i18n` branch updated to match, or a `[docs-i18n]` follow-up issue opened (see CONTRIBUTING.md § Translated documentation) - [ ] Version/release files updated (only if this PR includes a version bump) `docs/prompts/macros.md`, `docs/prompts/preset-variables.md` and `docs/chats/chat-settings.md` are updated here, along with a `CHANGELOG.md` `[Unreleased]` entry. No version bump. Translation follow-up: #6792 covers those three paths. ## UI evidence (if applicable) [Before/after screenshots in dark and light themes, desktop Chromium and iPhone-sized WebKit](https://gist.github.com/SpicyMarinara/49f0a95825acca9473c0d6d7899633fe). Download the self-contained HTML gallery from the gist to view its embedded original PNG captures. All screenshots use disposable synthetic data; browser emulation is not a physical-device test. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Add, edit, rename, and remove chat-specific variables in Chat Settings. Reference them with double-brace tags in prompts and messages; tags remain visible while the AI receives their values. Editing a variable also updates earlier turns that use its tag. * Variables persist across restarts and share storage with `{{setvar}}`, which can overwrite a matching name. Preset variables take precedence over chat variables, including in conditionals. Unmatched tags remain unchanged; built-in macro names are reserved, and each chat supports up to 500 variables. * **Bug Fixes** * Generation preserves newer edits and removals, and queued changes continue targeting the correct variable during renames. * **Documentation** * Updated guidance on chat variables, naming rules, resolution, and `{{setvar}}` storage. <!-- 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:18:27 +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#7305
No description provided.