[PR #6164] [MERGED] Improve CJK token estimation and prompt token count display #7072

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

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/6164
Author: @minikkeuen
Created: 9/13/2026
Status: ✅ Merged
Merged: 9/13/2026
Merged by: @SpicyMarinara

Base: staging ← Head: feature/cjk-token-estimation


📝 Commits (8)

  • d97ed9d Improve lightweight token estimates for CJK text
  • 853e2c1 Unify token counts for prompt and context inputs
  • 58ed50d Preserve aggregate token estimate rounding
  • f16394f Document token estimation and counter improvements
  • 5ef9bc7 Merge branch 'staging' into feature/cjk-token-estimation
  • 81a582c fix(tokens): honor CJK budgets and harden prompt counters
  • f1ea1ac test(ui): provide valid locale metadata for token counters
  • fdcf10e fix(ui): refresh saved translations and loading token counts

📊 Changes

49 files changed (+974 additions, -349 deletions)

View changed files

📝 CHANGELOG.md (+5 -0)
📝 e2e/chat-sweep.e2e.ts (+13 -0)
📝 e2e/core-flows.e2e.ts (+137 -3)
📝 package.json (+2 -1)
📝 packages/client/src/components/agents/AgentEditor.tsx (+20 -7)
📝 packages/client/src/components/characters/CardLibraryPreview.tsx (+1 -1)
📝 packages/client/src/components/characters/CharacterEditor.tsx (+37 -34)
📝 packages/client/src/components/characters/CharacterLibraryView.tsx (+4 -4)
📝 packages/client/src/components/chat/AgentSuiteModal.tsx (+7 -3)
📝 packages/client/src/components/chat/ChatArea.tsx (+2 -5)
📝 packages/client/src/components/chat/ChatRoleplayPanels.tsx (+22 -17)
📝 packages/client/src/components/chat/ChatSettingsDrawer.tsx (+3 -3)
📝 packages/client/src/components/chat/MariChatHistoryPicker.tsx (+3 -3)
📝 packages/client/src/components/chat/PeekPromptModal.tsx (+2 -2)
📝 packages/client/src/components/chat/SummariesEditorModal.tsx (+8 -2)
📝 packages/client/src/components/chat/SummaryPopover.tsx (+2 -1)
📝 packages/client/src/components/lorebooks/LorebookFormFields.tsx (+2 -1)
📝 packages/client/src/components/panels/CharactersPanel.tsx (+2 -2)
📝 packages/client/src/components/panels/PersonasPanel.tsx (+2 -2)
📝 packages/client/src/components/panels/settings/PromptOverridesEditor.tsx (+3 -1)

...and 29 more files

📄 Description

Important

Contributions target staging. Only SpicyMarinara may promote this repository's staging branch or a same-repository hotfix/* branch to main.
Outside and first-time contributors also require an approving review from SpicyMarinara.

Linked issue

Closes #6161

Why this change

  • The existing lightweight token estimator can substantially underestimate Korean, Japanese, and Chinese text.
  • Prompt and context inputs currently use inconsistent size indicators: some show character counts, some estimated token counts, and others no count.

What changed

  • Added lightweight CJK-aware token estimation for Hangul, Han characters, and Hiragana/Katakana.
  • Preserved the existing lightweight estimation behavior for other text.
  • Reused the shared token estimator across relevant prompt and context inputs.
  • Replaced character-only counters with estimated token counts where appropriate.
  • Added estimated token counts to relevant prompt/context fields that previously had no count.

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

  • Verified token estimates with English, Korean, Japanese, Chinese, and mixed-language text.
  • Verified updated token counters while editing prompt/context fields in the app.
  • Token estimator, UI token display, existing prompt regression, and legacy export compatibility tests pass.

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)

UI evidence (if applicable)

Before

No token count was displayed for this prompt field.

스크린샷 2026-09-13 23 17 12

After

The prompt field now displays an estimated token count.

스크린샷 2026-09-13 23 17 33

Summary by CodeRabbit

  • New Features

    • Added estimated token counts throughout prompt, character, persona, preset, translation, lorebook, memory, and context editors.
    • Token counters now appear consistently in text-editor footers, including expanded editors.
    • Added more accurate estimates for Korean, Chinese, and Japanese text.
    • Context and attached-source totals now display estimated token counts.
  • Bug Fixes

    • Replaced character-based approximations with consistent token estimates across chat, generation, summaries, and lorebook calculations.
    • Improved memory and context trimming to preserve Unicode characters and stay within token budgets.
    • Fixed localized token-counter labels and preset editing with malformed marker settings.

Maintainer review fixes

The contributor's implementation and commits are preserved. The follow-up fixes malformed saved preset markers through the existing safe parser and uses the existing localized token label across counter callers. A shared Unicode-safe token-budget cutter keeps CJK recall, provider trimming, retrieval chunks, Game transcripts, and Advanced Memory preparation within the new estimates; short lorebook previews stop at their budget instead of scanning the full entry.

The counter also clears stale values while a prompt loads. Full CI exposed a delayed translation-save race when returning to a chat; message-cache updates now refresh saved translations, with a deterministic held-response browser regression. Two unrelated browser assertions now wait for smooth scrolling or measure both rectangles in one animation frame, preserving their original focus and non-overlap requirements.

The estimator and counter regressions, plus the new CJK budget regression, now receive TypeScript checking during pnpm check. The lorebook fixture uses real schema defaults instead of an unchecked partial entry. No new dependency or storage migration is introduced.

Maintainer automated validation:

  • pnpm check, pnpm regression:prompt, and pnpm version:check passed.
  • Estimator/counter regressions, CJK budget regression, and Advanced Memory summary/core regressions passed. Failing-before controls reproduced dropped CJK recall, oversized retrieval/provider cuts, and rejected summary/classifier requests.
  • The real Astra adapter against a local fixture preserves every summarized CJK/emoji source fragment exactly once and keeps classification/summary requests within their configured context limits. No paid remote generation was used.
  • Focused browser regression passed 3/3: desktop Chromium light, mobile Chromium dark, and mobile WebKit dark. It covers invalid/null/missing marker settings, existing position controls, partial-language-pack localization, live inline/expanded counts, saved CJK edits, and horizontal fit. Screenshots were inspected. The initial synthetic locale fixture lacked required direction metadata; it was corrected and all assertions passed. Final E2E type-check and localization check passed.
  • Follow-up pnpm check passed. The delayed-translation, editor-navigation, and category-header checks passed 9/9 across desktop Chromium, mobile Chromium, and mobile WebKit; final E2E type checking and formatting passed.
  • Final hosted required checks passed, including 266 Node regressions, all 10 browser matrix shards, container build, Windows launchers, audit, and CodeQL. CodeRabbit completed its review of final head fdcf10e57; all review threads are resolved.

Original contributor checkboxes and manual verification notes above are unchanged. Physical-device and model-specific tokenizer calibration were not performed by this maintainer follow-up; these remain intentionally approximate token estimates.


🔄 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/6164 **Author:** [@minikkeuen](https://github.com/minikkeuen) **Created:** 9/13/2026 **Status:** ✅ Merged **Merged:** 9/13/2026 **Merged by:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Base:** `staging` ← **Head:** `feature/cjk-token-estimation` --- ### 📝 Commits (8) - [`d97ed9d`](https://github.com/Pasta-Devs/Marinara-Engine/commit/d97ed9d31693b3d6609a0a072d515dc5b1c71146) Improve lightweight token estimates for CJK text - [`853e2c1`](https://github.com/Pasta-Devs/Marinara-Engine/commit/853e2c19f61fd0205d23a62cb2abbc6762eb82cb) Unify token counts for prompt and context inputs - [`58ed50d`](https://github.com/Pasta-Devs/Marinara-Engine/commit/58ed50d36ee469eb653103caffabc9667e80a094) Preserve aggregate token estimate rounding - [`f16394f`](https://github.com/Pasta-Devs/Marinara-Engine/commit/f16394f545a17784dc898415319054145742df3c) Document token estimation and counter improvements - [`5ef9bc7`](https://github.com/Pasta-Devs/Marinara-Engine/commit/5ef9bc775dbff717686b3f78b7cdae6606989096) Merge branch 'staging' into feature/cjk-token-estimation - [`81a582c`](https://github.com/Pasta-Devs/Marinara-Engine/commit/81a582cbd2580b6d114197a463eeafd9b6fdbb99) fix(tokens): honor CJK budgets and harden prompt counters - [`f1ea1ac`](https://github.com/Pasta-Devs/Marinara-Engine/commit/f1ea1ac1ec633b0f2903ad0857b730494575da14) test(ui): provide valid locale metadata for token counters - [`fdcf10e`](https://github.com/Pasta-Devs/Marinara-Engine/commit/fdcf10e57b0f27a797ef7cf6968422c668c9b7f2) fix(ui): refresh saved translations and loading token counts ### 📊 Changes **49 files changed** (+974 additions, -349 deletions) <details> <summary>View changed files</summary> 📝 `CHANGELOG.md` (+5 -0) 📝 `e2e/chat-sweep.e2e.ts` (+13 -0) 📝 `e2e/core-flows.e2e.ts` (+137 -3) 📝 `package.json` (+2 -1) 📝 `packages/client/src/components/agents/AgentEditor.tsx` (+20 -7) 📝 `packages/client/src/components/characters/CardLibraryPreview.tsx` (+1 -1) 📝 `packages/client/src/components/characters/CharacterEditor.tsx` (+37 -34) 📝 `packages/client/src/components/characters/CharacterLibraryView.tsx` (+4 -4) 📝 `packages/client/src/components/chat/AgentSuiteModal.tsx` (+7 -3) 📝 `packages/client/src/components/chat/ChatArea.tsx` (+2 -5) 📝 `packages/client/src/components/chat/ChatRoleplayPanels.tsx` (+22 -17) 📝 `packages/client/src/components/chat/ChatSettingsDrawer.tsx` (+3 -3) 📝 `packages/client/src/components/chat/MariChatHistoryPicker.tsx` (+3 -3) 📝 `packages/client/src/components/chat/PeekPromptModal.tsx` (+2 -2) 📝 `packages/client/src/components/chat/SummariesEditorModal.tsx` (+8 -2) 📝 `packages/client/src/components/chat/SummaryPopover.tsx` (+2 -1) 📝 `packages/client/src/components/lorebooks/LorebookFormFields.tsx` (+2 -1) 📝 `packages/client/src/components/panels/CharactersPanel.tsx` (+2 -2) 📝 `packages/client/src/components/panels/PersonasPanel.tsx` (+2 -2) 📝 `packages/client/src/components/panels/settings/PromptOverridesEditor.tsx` (+3 -1) _...and 29 more files_ </details> ### 📄 Description > [!IMPORTANT] > Contributions target `staging`. Only `SpicyMarinara` may promote this repository's `staging` branch or a same-repository `hotfix/*` branch to `main`. > Outside and first-time contributors also require an approving review from `SpicyMarinara`. <!-- See CONTRIBUTING.md § Branches. --> ## Linked issue Closes #6161 ## Why this change - The existing lightweight token estimator can substantially underestimate Korean, Japanese, and Chinese text. - Prompt and context inputs currently use inconsistent size indicators: some show character counts, some estimated token counts, and others no count. ## What changed - Added lightweight CJK-aware token estimation for Hangul, Han characters, and Hiragana/Katakana. - Preserved the existing lightweight estimation behavior for other text. - Reused the shared token estimator across relevant prompt and context inputs. - Replaced character-only counters with estimated token counts where appropriate. - Added estimated token counts to relevant prompt/context fields that previously had no count. ## Validation - [x] `pnpm check` passes locally - [ ] Container (Docker / Podman) built and ran without issue - [x] Ran the app, clicked through the changes manually - [ ] 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 - Verified token estimates with English, Korean, Japanese, Chinese, and mixed-language text. - Verified updated token counters while editing prompt/context fields in the app. - Token estimator, UI token display, existing prompt regression, and legacy export compatibility tests pass. ## Docs and release impact - [ ] No docs changes needed - [x] 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) ## UI evidence (if applicable) ### Before No token count was displayed for this prompt field. <img width="728" height="325" alt="스크린샷 2026-09-13 23 17 12" src="https://github.com/user-attachments/assets/c96dea88-5851-44de-8d19-102630fbc565" /> ### After The prompt field now displays an estimated token count. <img width="723" height="317" alt="스크린샷 2026-09-13 23 17 33" src="https://github.com/user-attachments/assets/15909411-5b12-4e47-9514-8804d747507b" /> <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Added estimated token counts throughout prompt, character, persona, preset, translation, lorebook, memory, and context editors. - Token counters now appear consistently in text-editor footers, including expanded editors. - Added more accurate estimates for Korean, Chinese, and Japanese text. - Context and attached-source totals now display estimated token counts. - **Bug Fixes** - Replaced character-based approximations with consistent token estimates across chat, generation, summaries, and lorebook calculations. - Improved memory and context trimming to preserve Unicode characters and stay within token budgets. - Fixed localized token-counter labels and preset editing with malformed marker settings. <!-- end of auto-generated comment: release notes by coderabbit.ai --> ## Maintainer review fixes The contributor's implementation and commits are preserved. The follow-up fixes malformed saved preset markers through the existing safe parser and uses the existing localized token label across counter callers. A shared Unicode-safe token-budget cutter keeps CJK recall, provider trimming, retrieval chunks, Game transcripts, and Advanced Memory preparation within the new estimates; short lorebook previews stop at their budget instead of scanning the full entry. The counter also clears stale values while a prompt loads. Full CI exposed a delayed translation-save race when returning to a chat; message-cache updates now refresh saved translations, with a deterministic held-response browser regression. Two unrelated browser assertions now wait for smooth scrolling or measure both rectangles in one animation frame, preserving their original focus and non-overlap requirements. The estimator and counter regressions, plus the new CJK budget regression, now receive TypeScript checking during `pnpm check`. The lorebook fixture uses real schema defaults instead of an unchecked partial entry. No new dependency or storage migration is introduced. Maintainer automated validation: - `pnpm check`, `pnpm regression:prompt`, and `pnpm version:check` passed. - Estimator/counter regressions, CJK budget regression, and Advanced Memory summary/core regressions passed. Failing-before controls reproduced dropped CJK recall, oversized retrieval/provider cuts, and rejected summary/classifier requests. - The real Astra adapter against a local fixture preserves every summarized CJK/emoji source fragment exactly once and keeps classification/summary requests within their configured context limits. No paid remote generation was used. - Focused browser regression passed 3/3: desktop Chromium light, mobile Chromium dark, and mobile WebKit dark. It covers invalid/null/missing marker settings, existing position controls, partial-language-pack localization, live inline/expanded counts, saved CJK edits, and horizontal fit. Screenshots were inspected. The initial synthetic locale fixture lacked required direction metadata; it was corrected and all assertions passed. Final E2E type-check and localization check passed. - Follow-up `pnpm check` passed. The delayed-translation, editor-navigation, and category-header checks passed 9/9 across desktop Chromium, mobile Chromium, and mobile WebKit; final E2E type checking and formatting passed. - Final hosted required checks passed, including 266 Node regressions, all 10 browser matrix shards, container build, Windows launchers, audit, and CodeQL. CodeRabbit completed its review of final head `fdcf10e57`; all review threads are resolved. Original contributor checkboxes and manual verification notes above are unchanged. Physical-device and model-specific tokenizer calibration were not performed by this maintainer follow-up; these remain intentionally approximate token estimates. --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-23 04:16:17 +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#7072
No description provided.