[PR #3166] [MERGED] fix(client,shared): stop regex-script macro replacements freezing the UI (#3164) #5826

Closed
opened 2026-10-22 04:19:54 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/3166
Author: @kolacheee
Created: 7/3/2026
Status: ✅ Merged
Merged: 7/3/2026
Merged by: @SpicyMarinara

Base: staging ← Head: fix/3164-regex-macro-display-cost


📝 Commits (1)

  • fb16c96 fix(client,shared): stop regex-script macro replacements freezing the UI (#3164)

📊 Changes

6 files changed (+151 additions, -25 deletions)

View changed files

📝 packages/client/src/components/chat/ChatArea.tsx (+62 -6)
📝 packages/client/src/components/chat/ChatMessage.tsx (+5 -1)
📝 packages/client/src/components/chat/ConversationMessage.tsx (+20 -4)
📝 packages/client/src/components/game/GameNarration.tsx (+21 -5)
📝 packages/client/src/lib/chat-macros.ts (+30 -2)
📝 packages/shared/src/utils/macro-engine.ts (+13 -7)

📄 Description

Linked issue

Relates to #3164 — please have the reporter confirm on this branch before closing (their profiler produced the 702–3000ms numbers; the benchmarks below reproduce the mechanism, not their exact hardware).

Why this change

#3164 reports severe UI freezes with regex scripts whose replacements contain macros (e.g. replace the with a weighted {{random::…}}). Verified legitimate, with the repro benchmarked against current staging. Two compounding causes:

  1. Multiplication (primary). The per-message display pipeline (regex scripts + macro resolution) is individually cheap (~1.2ms for 5 scripts, desktop), but it re-ran for every mounted message on every ChatArea render. useQueries returns a fresh result-array identity each render, so chatCharacterRows → characterMap were rebuilt — new Map, new value objects — on every re-render, plus a guaranteed rebuild every 60s (presence clock) and on every chat metadata write (constant on agent chats). The new identity defeats memo(ChatMessage) and invalidates every message's displayContent memo. 160 mounted messages × 5 scripts ≈ 200–610ms per storm on a fast desktop — the reported 702–3000ms on slower hardware — re-paid on chat open, mid-stream agent-store flips, message invalidations, and the idle 60s tick (the reporter's "lag even outside of generation, bafflingly").
  2. Fixed per-resolution cost + streaming churn. Every macro-bearing replacement resolution paid an unconditional Intl.DateTimeFormat(...).formatToParts() (~45% of the pipeline's fixed cost) even with no date macro present, and N scripts sharing one replacement did N identical resolutions. During streaming, the display random seed included message content, so every streamed chunk re-rolled every {{random}}/{{roll}} — the visible text churn in the report.

What changed

Four coordinated fixes:

  • ChatArea identity stabilization (ChatArea.tsx): chatCharIds keys on the raw characterIds field; chatCharacterRows reuses the previous array when every element is reference-unchanged; characterMap reuses its previous identity when a rebuild is value-equal (comparator covers all 14 value fields; avatarCrop compared by value). Unrelated re-renders, presence ticks, and metadata writes that don't change displayed character data no longer re-run the display pipeline for any message, across all three chat surfaces. Genuine changes still propagate.
  • Lazy date/time in the macro engine (packages/shared/.../macro-engine.ts): the six date/time parts are built only when a date/time macro is present; now is still captured once per invocation so all six agree on the instant. Output identical (date strings can't contain $ sequences).
  • Per-resolver template cache (chat-macros.ts): one resolver instance serves all of a message's replacement/trim/pattern strings; identical templates with a fixed (context, seed) resolve identically, so repeats are cache hits. The cache hard-disables from the first variable-op macro onward — conditionals and the {{name}} catch-all can read variables without matching the var-op pattern, so any write poisons cachability for the rest of the instance.
  • Identity-based display random seeds (ChatMessage.tsx, GameNarration.tsx, ConversationMessage.tsx): seed by message.id + active swipe index (+ segment/part index where applicable) instead of content. Streaming stops re-rolling picks every chunk; swipes keep distinct picks; regenerations (new swipe index) roll fresh. ConversationMessage previously passed no seed at all (Math.random()), re-rolling finished messages on every recompute — it now gains stability it never had.

Deliberately not done (so reviewers don't ask): per-script RegExp/isPatternSafe caching — measured at 0.00007ms/0.0005ms per application, three orders of magnitude below the resolver cost; throttling or freezing regex application during streaming — skipping application would leak content that display scripts exist to hide (scripts keep applying to every streamed frame); the deep ChatArea presence-overlay/combine refactor — follow-up scope, the comparator shims already deliver the identity stability.

Measured (tsx harness against this branch vs staging)

Scenario Before After
One {{random::…}} replacement resolution (fresh resolver) 0.172 ms 0.012 ms
Message with 5 scripts sharing one replacement ~0.86 ms ~0.013 ms
Message with 5 distinct replacements ~0.86 ms ~0.06 ms
Whole-window storm (160 msgs × 5 scripts) on unrelated re-render 200–610 ms desktop / 702–3000 ms reported does not occur (identity stable)

Documented behavior deltas

  • Historical messages re-roll their displayed {{random}} picks once on upgrade (picks are render-time only, never persisted; edit/copy paths use raw content). Worth a release-note line.
  • Identical unseeded templates within one resolution pass now give one consistent pick instead of independent Math.random() rolls (affects multi-script user-input paths; arguably the desired consistency).
  • All in-flight streams share the streaming placeholder seed until finalization, then settle once on the real message id.

Validation

  • 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

  • Lint (all three packages), shared build, and client build pass. The full pnpm check server build step fails on clean staging on Windows (pre-existing v2.1.0 build.mjs unquoted-execPath spawn bug, reproduced with this branch's changes stashed — separate fix needed; not caused by this PR).
  • 20-case local regression matrix passes (15 macro-engine + 5 chat-macros), including: the stale-cache-after-setvar case (a cached conditional re-reads correctly after a later variable write), variable write/read sequencing through the cached resolver, same-seed {{random}} determinism across resolver instances, and date/time macros resolving after the lazy Intl construction. (*.test.ts is gitignored per repo convention — matrix kept local.)
  • Benchmarks above.

Still needs manual verification:

  • The #3164 reporter re-tests their regex setup on this branch (their repro: several scripts replacing common words with weighted {{random::…}}) and confirms the freeze is gone during streaming and idle.
  • Spot-check in a real browser: regex scripts still apply to streamed text as it arrives; {{random}} picks hold steady during a stream and settle once at completion; swiping shows different picks per swipe; presence dots still update (60s schedule transitions and status changes); character edits (name/avatar/colors) still propagate to open chats in all three modes.

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed
  • Version/release files updated (only if this PR includes a version bump)

Suggested release-note line: "Displayed {{random}}/{{roll}} results are now stable per message/swipe instead of re-rolling on every render or streamed chunk; existing messages will re-roll their displayed picks once after updating."

UI evidence (if applicable)

No visual change — displayed content is identical except that {{random}}/{{roll}} picks are now stable during streaming instead of flickering per chunk.


🔄 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/3166 **Author:** [@kolacheee](https://github.com/kolacheee) **Created:** 7/3/2026 **Status:** ✅ Merged **Merged:** 7/3/2026 **Merged by:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Base:** `staging` ← **Head:** `fix/3164-regex-macro-display-cost` --- ### 📝 Commits (1) - [`fb16c96`](https://github.com/Pasta-Devs/Marinara-Engine/commit/fb16c96e49594d6aff50aec3629c6799ad368266) fix(client,shared): stop regex-script macro replacements freezing the UI (#3164) ### 📊 Changes **6 files changed** (+151 additions, -25 deletions) <details> <summary>View changed files</summary> 📝 `packages/client/src/components/chat/ChatArea.tsx` (+62 -6) 📝 `packages/client/src/components/chat/ChatMessage.tsx` (+5 -1) 📝 `packages/client/src/components/chat/ConversationMessage.tsx` (+20 -4) 📝 `packages/client/src/components/game/GameNarration.tsx` (+21 -5) 📝 `packages/client/src/lib/chat-macros.ts` (+30 -2) 📝 `packages/shared/src/utils/macro-engine.ts` (+13 -7) </details> ### 📄 Description ## Linked issue Relates to #3164 — please have the reporter confirm on this branch before closing (their profiler produced the 702–3000ms numbers; the benchmarks below reproduce the mechanism, not their exact hardware). ## Why this change #3164 reports severe UI freezes with regex scripts whose replacements contain macros (e.g. replace `the` with a weighted `{{random::…}}`). Verified legitimate, with the repro benchmarked against current staging. Two compounding causes: 1. **Multiplication (primary).** The per-message display pipeline (regex scripts + macro resolution) is individually cheap (~1.2ms for 5 scripts, desktop), but it re-ran for **every mounted message on every ChatArea render**. `useQueries` returns a fresh result-array identity each render, so `chatCharacterRows` → `characterMap` were rebuilt — new Map, new value objects — on every re-render, plus a guaranteed rebuild every 60s (presence clock) and on every chat metadata write (constant on agent chats). The new identity defeats `memo(ChatMessage)` and invalidates every message's `displayContent` memo. 160 mounted messages × 5 scripts ≈ 200–610ms per storm on a fast desktop — the reported 702–3000ms on slower hardware — re-paid on chat open, mid-stream agent-store flips, message invalidations, and the idle 60s tick (the reporter's "lag even outside of generation, bafflingly"). 2. **Fixed per-resolution cost + streaming churn.** Every macro-bearing replacement resolution paid an unconditional `Intl.DateTimeFormat(...).formatToParts()` (~45% of the pipeline's fixed cost) even with no date macro present, and N scripts sharing one replacement did N identical resolutions. During streaming, the display random seed included message content, so every streamed chunk re-rolled every `{{random}}`/`{{roll}}` — the visible text churn in the report. ## What changed Four coordinated fixes: - **ChatArea identity stabilization** (`ChatArea.tsx`): `chatCharIds` keys on the raw `characterIds` field; `chatCharacterRows` reuses the previous array when every element is reference-unchanged; `characterMap` reuses its previous identity when a rebuild is value-equal (comparator covers all 14 value fields; `avatarCrop` compared by value). Unrelated re-renders, presence ticks, and metadata writes that don't change displayed character data no longer re-run the display pipeline for any message, across all three chat surfaces. Genuine changes still propagate. - **Lazy date/time in the macro engine** (`packages/shared/.../macro-engine.ts`): the six date/time parts are built only when a date/time macro is present; `now` is still captured once per invocation so all six agree on the instant. Output identical (date strings can't contain `$` sequences). - **Per-resolver template cache** (`chat-macros.ts`): one resolver instance serves all of a message's replacement/trim/pattern strings; identical templates with a fixed (context, seed) resolve identically, so repeats are cache hits. The cache **hard-disables from the first variable-op macro onward** — conditionals and the `{{name}}` catch-all can read variables without matching the var-op pattern, so any write poisons cachability for the rest of the instance. - **Identity-based display random seeds** (`ChatMessage.tsx`, `GameNarration.tsx`, `ConversationMessage.tsx`): seed by `message.id` + active swipe index (+ segment/part index where applicable) instead of content. Streaming stops re-rolling picks every chunk; swipes keep distinct picks; regenerations (new swipe index) roll fresh. `ConversationMessage` previously passed **no seed at all** (`Math.random()`), re-rolling finished messages on every recompute — it now gains stability it never had. **Deliberately not done** (so reviewers don't ask): per-script `RegExp`/`isPatternSafe` caching — measured at 0.00007ms/0.0005ms per application, three orders of magnitude below the resolver cost; throttling or freezing regex application during streaming — skipping application would leak content that display scripts exist to hide (scripts keep applying to every streamed frame); the deep ChatArea presence-overlay/`combine` refactor — follow-up scope, the comparator shims already deliver the identity stability. ### Measured (tsx harness against this branch vs staging) | Scenario | Before | After | | --- | --- | --- | | One `{{random::…}}` replacement resolution (fresh resolver) | 0.172 ms | 0.012 ms | | Message with 5 scripts sharing one replacement | ~0.86 ms | ~0.013 ms | | Message with 5 distinct replacements | ~0.86 ms | ~0.06 ms | | Whole-window storm (160 msgs × 5 scripts) on unrelated re-render | 200–610 ms desktop / 702–3000 ms reported | does not occur (identity stable) | ### Documented behavior deltas - Historical messages re-roll their displayed `{{random}}` picks **once** on upgrade (picks are render-time only, never persisted; edit/copy paths use raw content). Worth a release-note line. - Identical unseeded templates within one resolution pass now give one consistent pick instead of independent `Math.random()` rolls (affects multi-script user-input paths; arguably the desired consistency). - All in-flight streams share the streaming placeholder seed until finalization, then settle once on the real message id. ## Validation - [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 - Lint (all three packages), shared build, and client build pass. The full `pnpm check` **server build step fails on clean staging on Windows** (pre-existing v2.1.0 `build.mjs` unquoted-`execPath` spawn bug, reproduced with this branch's changes stashed — separate fix needed; not caused by this PR). - 20-case local regression matrix passes (15 macro-engine + 5 chat-macros), including: the stale-cache-after-`setvar` case (a cached conditional re-reads correctly after a later variable write), variable write/read sequencing through the cached resolver, same-seed `{{random}}` determinism across resolver instances, and date/time macros resolving after the lazy Intl construction. (`*.test.ts` is gitignored per repo convention — matrix kept local.) - Benchmarks above. Still needs manual verification: - **The #3164 reporter re-tests their regex setup on this branch** (their repro: several scripts replacing common words with weighted `{{random::…}}`) and confirms the freeze is gone during streaming and idle. - Spot-check in a real browser: regex scripts still apply to streamed text as it arrives; `{{random}}` picks hold steady during a stream and settle once at completion; swiping shows different picks per swipe; presence dots still update (60s schedule transitions and status changes); character edits (name/avatar/colors) still propagate to open chats in all three modes. ## Docs and release impact - [x] No docs changes needed - [ ] Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed - [ ] Version/release files updated (only if this PR includes a version bump) Suggested release-note line: "Displayed {{random}}/{{roll}} results are now stable per message/swipe instead of re-rolling on every render or streamed chunk; existing messages will re-roll their displayed picks once after updating." ## UI evidence (if applicable) No visual change — displayed content is identical except that `{{random}}`/`{{roll}}` picks are now stable during streaming instead of flickering per chunk. --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-22 04:19:54 +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#5826
No description provided.