[PR #7555] [MERGED] feat(avatars): live faces and lip sync (director and streaming classifier) #7794

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

📋 Pull Request Information

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

Base: staging ← Head: feat/avatars-director


📝 Commits (10+)

  • 92d1ce1 feat(avatars): live faces and lip sync for avatars (director and classifier)
  • efc910c test(avatars): director regression, guide section, and dispose fixes
  • 2ecf763 Merge remote-tracking branch 'origin/feat/avatars-contract' into feat/avatars-director
  • 6838237 fix(avatars): Game lines reach a late stage, not while reviewing past turns
  • ffffb4c fix(avatars): a reset classifier load never becomes the model; plainer guide
  • 1a601fe Merge remote-tracking branch 'origin/staging' into feat/avatars-director
  • a85c132 fix(avatars): director review fixes and the opt-in mood reader download
  • 8f5655e fix(avatars): a text the emotion model does not answer in time stops its worker
  • 9bb959a fix(avatars): a late Game stage keeps the last face without speaking an old line
  • 3510bee docs(avatars): say the mood reader retries a failed download in about 10 minutes

📊 Changes

24 files changed (+3577 additions, -102 deletions)

View changed files

📝 docs/agents/avatars.md (+23 -1)
📝 packages/client/src/components/chat/SpriteOverlay.tsx (+8 -25)
📝 packages/client/src/components/game/GameNarration.tsx (+6 -0)
➕ packages/client/src/features/avatars/director/AvatarModelStatus.tsx (+54 -0)
📝 packages/client/src/features/avatars/director/avatar-director.ts (+642 -18)
➕ packages/client/src/features/avatars/director/game-line-feed.ts (+59 -0)
➕ packages/client/src/features/avatars/director/reply-text.ts (+179 -0)
➕ packages/client/src/features/avatars/director/speech-clock.ts (+214 -0)
📝 packages/client/src/features/avatars/setup/AvatarAgentSetup.tsx (+2 -0)
➕ packages/client/src/hooks/use-avatar-emotion-model.ts (+33 -0)
📝 packages/client/src/hooks/use-generate.ts (+17 -0)
📝 packages/client/src/localization/locales/en.json (+8 -0)
📝 packages/server/src/middleware/rate-limit.ts (+14 -0)
📝 packages/server/src/routes/avatar-classify.routes.ts (+61 -5)
📝 packages/server/src/routes/generate/expression-agent-utils.ts (+2 -40)
➕ packages/server/src/services/avatars/classifier/emotion-model.worker.ts (+46 -0)
➕ packages/server/src/services/avatars/classifier/local-emotion-model.ts (+190 -0)
📝 packages/server/src/services/avatars/emotion-classifier.ts (+322 -12)
📝 packages/server/src/services/local-embedder.ts (+1 -1)
📝 packages/shared/src/index.ts (+1 -0)

...and 4 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

Refs #7537 (lane: Director). Guide translation follow-up: #7540.

Depends on https://github.com/Pasta-Devs/Marinara-Engine/pull/7539, "feat(avatars): shared contract for the 2D and 3D avatar agents" (Refs #7537). It has now merged into staging, and this branch merged staging at 1a601fe43, so the diff shows only this lane. The TTS lane (#7547) and the avatar docs (#7551) are also on staging and in that merge. After the 2D lane (#7549) landed, the branch merged staging again at e481304aa. The only conflict was en.json, resolved by keeping both key blocks in sorted order.

Merge note for whichever of #7555 and #7556 merges second. The mood reader's status panel (AvatarModelStatus) is mounted by this PR since 5a467451c. The setup page stub features/avatars/setup/AvatarAgentSetup.tsx renders <AvatarModelStatus />, and avatar-director.regression.ts fails if the setup page stops importing or rendering it. That stub belongs to the base lane (#7556), so the second PR gets one conflict in that file. Resolve it by keeping #7556's page and adding import { AvatarModelStatus } from "../director/AvatarModelStatus"; plus <AvatarModelStatus /> as the first child of <div className="space-y-4" data-avatar-setup={agentId}>. That resolution was checked locally (see Validation). Earlier, the mount was only requested on #7556 (https://github.com/Pasta-Devs/Marinara-Engine/pull/7556#issuecomment-6154694561), and the integration check found that no merged page showed the panel.

Why this change

  • Avatars need a face that changes while a reply streams, and a mouth that moves with what the character says. Mari ruled out LLM-written tags and Decision models, because they run after the reply. So Roleplay needs a fast local classifier that reads each sentence as it appears. Game mode already has the Game Master's per-line expressions. The Expression Engine's pick should stay the final word.
  • The Engine had two separate mood word lists, the Roleplay sprite fallback and the Expression Engine's fallback pick. They disagreed and matched word prefixes, so "yellow" read as angry and "terrific" as scared. The classifier needs one good list, so all three uses now share it.
  • Mari's decision (2026-10-13, review thread on emotion-classifier.ts): the emotion model downloads only when an avatar agent is enabled, never on install or on the first classify request. The agent's page shows the progress and any error, and Lite and Termux keep skipping it.
  • Review of ffffb4c22 found several problems. A reply's last moods were lost while the typewriter caught up, and in group chats the wrong avatar spoke. A late Expression Engine pick froze the next reply's face. The model loaded and ran on the server's main thread during streaming. It could not load offline, and it left partial downloads behind.

What changed

  • Roleplay sprites without the Expression Engine, and the Expression Engine's fallback for a character it skipped, read mood words differently.
    • They share one word list that matches whole words, so "yellow", "terrific", "crypt", "museum", "considerable" or "concerning" no longer change a sprite.
    • Phrases the old Roleplay fallback caught still work: "wide eyes", "beams", "shyness", "ached" and "heart racing".
    • It knows more words, plus common mood words in German, Spanish, French, Italian, Portuguese, Polish, Russian, Japanese, Chinese and Korean. It ignores accents, and Korean syllables stay whole: 무성한, "overgrown", no longer reads as scared.
    • One ordering change: when a skipped character's text mentions both a general mood and a blush ("she blushes and smiles"), the fallback now tries the happy sprite before the blush sprite. That is the order the Roleplay fallback already used.
  • Avatars get live faces in Roleplay.
    • Each finished sentence of the visible reply is classified. The face changes only on a clear mood (a score of 0.45 with a 0.15 lead) and holds at least 2 s.
    • It needs two calm sentences to go back to calm, and it relaxes 4 s after the reply unless the Expression Engine settled it.
    • A reply now ends when its generation does, after the typewriter has shown all of it. A reply that streams faster than it is shown keeps sending whole sentences, never single letters.
    • Streaming off is read from the setting. A reply that arrives in one chunk with streaming on is mouthed once, as it types. With streaming off, including when a rewrite agent holds the reply, the whole reply is classified once and its dialogue is spoken within 8 s.
  • Game mode faces follow the Game Master's expression for the line on screen. A character's thought, or the player's own input, sets the face but not the mouth, as Game voices already treat them.
  • The Expression Engine's pick is the final face for the reply it was made for. A pick that arrives after you sent your next message no longer lands on the new reply. Agent results now keep their message id.
  • Group chats.
    • In an Individual group, the replying member speaks, and that includes swiping one member's message.
    • In a Merged group, each paragraph belongs to the character it names, including with streaming off: the server saves a Merged reply under the first character. While a paragraph that names nobody is still appearing, its dialogue waits until a name or the paragraph's end shows who says it. A speech tag after the quote ("Get out," Bob growls.) therefore never makes two avatars say the line.
  • Mouths move only for dialogue (quotes, [Name]: lines, speaker tags), at about 14 characters a second. They speed up to 1.5x and then skip ahead when the text outruns speech, and close 150 ms after the last word. Japanese kana pick the mouth shape by vowel row, and other scripts move rhythmically. While text-to-speech plays, the voice level moves the mouth instead.
  • Body states: thinking from send to the first words, talking, listening (others while someone talks, characters while you type), and idle.
  • The mood reader (local emotion model): Horizon-Labs/multilingual-emotions-small, Apache-2.0, 36 languages.
    • When it downloads. It downloads (about 289 MB) only when a Roleplay chat with 2D or 3D Avatars turned on opens: the stage's director sends POST /api/avatar-classify/model. The server accepts that only for a Roleplay chat with an installed avatar agent turned on, and answers 409 otherwise. Installing an agent never downloads it, a classify request never downloads or loads it, and Game mode never asks for it.
    • Progress. GET /api/avatar-classify/model reports the state for the agents' pages: not downloaded, downloading, loading, downloaded, failed, or kept on the word list. The new AvatarModelStatus shows it in plain, localized copy with a progress bar.
    • Retries. A failed download is tried again by itself 10 minutes later, the next time the stage asks. It asks again at most once a minute while it gets keyword answers.
    • Files. The four files are pinned by commit, size and SHA-256 and fetched straight from Horizon through the sidecars' checked download. A stopped download's leftover is replaced, never piled up. The model then loads from disk only, so it works offline.
    • Worker thread. It loads and runs in a worker thread, so the server never pauses while a reply streams. It unloads after 10 idle minutes, and a crashed worker is dropped and loaded again later.
    • Who keeps the word list. Lite installs, servers without onnxruntime-node's native binding (Termux) and machines with less than 3 GB of memory keep the word list.
    • Blending. When a word names a mood, the model's answer is averaged with it, because the model calls most narrated prose neutral. A text the model failed on is not cached as the model's answer.
  • Guide: the section "How faces and mouths follow the reply" in docs/agents/avatars.md covers the download rule, the progress on the agent page, offline use, memory, the Game thought rule and group chats.

Contract and shared-file changes (called out)

  • packages/shared/src/index.ts: one added export line for the new utils/expression-keywords.ts. This is additive, and types/avatars.ts is untouched.
  • packages/shared/src/types/agent.ts: AgentResult gains an optional messageId. It is additive, and existing results without it behave as before.
  • createAvatarDirector(options, hooks?): an optional second parameter that only regressions use (stubbed classify and prepare calls). The stage's one-argument call is unchanged.
  • Edits outside the lane's own folders:
    • the two keyword callers the lane was asked to merge (SpriteOverlay.tsx, expression-agent-utils.ts);
    • the route's rate-limit rule (middleware/rate-limit.ts);
    • one export on the existing ONNX binding check (local-embedder.ts);
    • the allowed one-line Game feed in GameNarration.tsx;
    • hooks/use-generate.ts: a swipe in an Individual group names its member as the streaming character, and both agent-result paths keep the result's message id;
    • a new hooks/use-avatar-emotion-model.ts for the status query;
    • the base lane's setup page stub features/avatars/setup/AvatarAgentSetup.tsx: it renders <AvatarModelStatus />, so the panel is on both avatar agents' pages whichever PR merges first (see the merge note above).
  • en.json: new flat keys under avatars.director.model.* only, placed after app.documentTitle. The base lane's avatars.setup.* block sorts after them.

Model choice (classifier research, 2026-10-13)

This model ranked first in the research. Its licence is permissive (Apache-2.0, on the MIT-licensed base mmBERT-small), and its ONNX q8 build runs unchanged in the Engine's installed @huggingface/transformers 4.3.0. It is multilingual: BRIGHTER 10-language top-1 is 0.69, against about 0.39 for the English-only models. It is on par with SamLowe on English GoEmotions. Its weakness is narrated roleplay prose, which the keyword blend covers.

Per Mari's decision, the commit is pinned and the files come from Horizon directly, with no mirror. On 42 roleplay lines written in 9 languages, the model alone got 20/42, keywords alone 28/42, and the blend 34/42. That set is small and self-written, so it is only a rough signal.

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

Commands run by the agent are listed below as results, not ticked boxes. They ran on a machine shared with other lanes, with a load average of 20–35. Final head: 5a467451c.

  • Integration fix on 5a467451c (the mood reader panel had no mount on the merged tree):

    • pnpm check: exit 0, with the same pre-existing lint warning in HomeProfessorMariChat.tsx. Main entry: 313 kB.
    • Regressions per filter, all passed: avatar- (10/10, now including the 2D lane's), agent-activation (2/2), spatial-context, open-issues, game-narration (2/2), roleplay-streaming, expression- (2/2), group- (7/7) and roleplay-vn-tts.
    • The new mount check in avatar-director.regression.ts fails on the old null stub and on #7556's page at 2b417feaa. It passes with the mount.
    • A local throwaway merge of #7556 (2b417feaa) into this branch, discarded afterwards: AvatarAgentSetup.tsx was the only conflicting file, resolved as in the merge note. On that tree, avatar- regressions passed 12/12. Playwright on private ports passed #7556's e2e/avatar-setup.e2e.ts and a temporary spec on desktop Chromium and mobile Chromium (6/6). The temporary spec has since been deleted. It showed the panel on the 2D and 3D Avatars pages with "Downloading the mood reader: 41%." and its progress bar, inside the phone's width, and confirmed that opening the page never starts the download.
    • Local CodeRabbit (coderabbit review --agent --committed --base-commit e481304aa): 0 findings, 2 files reviewed.
  • pnpm check on 3510bee81: exit 0. It covers format, localization, impeccable, lint, type checks and the production build. The one lint warning is pre-existing, in HomeProfessorMariChat.tsx. Main entry: 313 kB. It also passed on a85c132fc.

  • node scripts/run-regressions.mjs --filter <name>, run per filter, all passed:

    • on 3510bee81: avatar- (8/8, including avatar-classifier, avatar-director, the avatar-contract guard and avatar-tts-lipsync), open-issues, game-narration (2/2), roleplay-streaming and expression- (2/2);
    • on a85c132fc: agent-activation (2/2), spatial-context, roleplay-vn-tts and group- (7/7).
  • pnpm localization:check on 3510bee81: exit 0.

  • Proof that the new director checks catch the reported bugs. I copied avatar-director.regression.ts with every assertion turned into a logged check (a temporary copy, since deleted) and ran it against the old director files from ffffb4c22. Every new check failed there:

    • fragments ["t","o","h","e",…] reached the classifier after message-ready;
    • a one-chunk reply was mouthed for 5888 ms, with growing prefixes "Alic", "Alice smi", … sent to the classifier;
    • a held rewrite's dialogue was spoken for 1536 ms;
    • in a Merged reply with streaming off, only Alice spoke ({"alice":2992,"bob":0});
    • Alice mouthed Bob's tagged line;
    • a stale Expression Engine pick landed on the new reply;
    • a Game thought moved the mouth;
    • the model was never asked for.
  • The real pinned model, run outside CI through the worker, with DATA_DIR set to a temporary folder under the worktree that was deleted afterwards:

    • The first download and load took 45 s. The longest server event-loop pause was about 100–140 ms, which matches the idle baseline under this load (199 ms with nothing running). Before, the main thread stalled for 1.6–2.3 s.
    • A 16-text request took 2.0–3.5 s, with longest pauses of 13–100 ms. One short text took 68–134 ms.
    • Main-process RSS stayed at 350–560 MB, because the model's memory sits in the worker.
    • With fetch stubbed to throw, the model loaded from disk with no network request.
    • For comparison, loading the same files on the main thread took 17.8 s under the same load. The review measured single main-thread stalls of 1.6–2.3 s on a quiet machine.
  • A timed-out text, checked by hand. With the classify timeout lowered to 1 ms (by hand, then restored to 10 s), a 6-text request with the real model fell back to keywords in 43 ms in total. The model was dropped, and the next request answered from keywords at once.

  • pnpm smoke:ui on private ports, on a85c132fc: 7/7 passed, including Roleplay reasoning, stopped generations and Game narration.

  • Local CodeRabbit (coderabbit review --agent --committed --base-commit 797877c54, base = current staging):

    • on a85c132fc: 0 findings, reviewing 23 files;
    • on 8f5655ee9: 1 finding. A Game stage that mounted after narration still spoke the last dialogue line. Fixed in 9bb959a7f, with a regression;
    • on 9bb959a7f: 2 findings. The retry copy said "a few minutes" while the code waits 10. Fixed in 3510bee81. The other asked for a [docs-i18n] follow-up for docs/agents/avatars.md, and was not changed: #7540 already covers that file and is linked above.
    • No run was made after 3510bee81, which only changes copy.
    • Earlier, on 2ecf763e5, one run found 3 issues, all fixed in 68382373c.
  • GitHub review threads. All 8 are resolved; 5 were fixed or answered earlier.

    • Mari's decision on the download is implemented in a85c132fc, answered and resolved.
    • The PNGTuber file-path rule belongs to the merged contract and the 2D lane's data. It was answered and handed to #7549 (https://github.com/Pasta-Devs/Marinara-Engine/pull/7549#issuecomment-6154710680), then resolved here, because this PR no longer touches those files.
    • CodeRabbit on a85c132fc: a timed-out text left later texts waiting behind a busy worker. Fixed in 8f5655ee9, answered and resolved. That review used the last of the hourly included GitHub reviews, so the GitHub review of 3510bee81 may come late.
  • Not fixed here, follow-ups. With streaming off in an Individual group, only the last member's reply moves an avatar: the server sends one assistant_message_ready after the group loop, and text-to-speech autoplay reads only that message too. Impersonation still streams into the character's live row, which the Roleplay surface itself renders as the character, so the character's avatar mouths it. Both need a server event or chat-store signal outside this lane.

Manual verification needed

The director has no UI of its own beyond the mood reader panel. The rest shows once the base lane's stage and a renderer are on staging.

  • Desktop Chrome, Roleplay, one character with an avatar, default streaming: send a message. Check each of these:
    • the avatar thinks until the first words;
    • the mouth moves only while quoted dialogue appears, not during narration;
    • the face changes when the reply turns clearly happy or sad, including for sentences shown after the reply is saved but still typing;
    • the face relaxes about 4 s after the reply ends.
  • The same chat with the Expression Engine on, using a slow connection for it:
    • after a reply, the face switches to the Engine's pick and stays there;
    • send the next message before the Engine finishes, and confirm the old pick does not freeze the new reply's face.
  • Turn streaming off, then:
    • the reply's dialogue is mouthed within about 8 s, and the face matches the reply's overall mood;
    • repeat with Prose Guardian on, and confirm the dialogue is still spoken for several seconds.
  • With text-to-speech autoplay on, the mouth follows the voice instead of the text.
  • Game mode:
    • click through Game Master dialogue lines: the speaking character's avatar takes that line's expression and moves its mouth;
    • narration lines and [thought] lines leave the mouth still;
    • advance to a narration line, then turn the avatar agent on in the chat: the avatar shows the last speaker's face without speaking the old line.
  • Merged group with Alice and Bob:
    • stream a reply where a line ends …," Bob growls.: only Bob's mouth says it;
    • with streaming off, each paragraph's dialogue moves the named character's mouth.
  • Individual group: swipe Bob's message. Only Bob thinks and talks.
  • The mood reader (once #7556's setup page is on staging). Check each of these:
    • install 2D Avatars and open its Agent editor page: the panel says it downloads the first time a Roleplay chat with the agent on opens, and the server log shows no download;
    • turn the agent on in a Roleplay chat: the log shows "Downloading the local emotion model" once, the page's bar climbs to 100%, then shows "downloaded and works offline", and DATA_DIR/models/avatar-emotion/1bc9627f… holds about 289 MB;
    • stop the server mid-download and start it again: only one *.download leftover existed, and the next download replaces it;
    • with the network off after the download, restart and chat: faces still use the model, and the log shows no download;
    • a Game-only chat with the agent on never downloads it.
  • On a Lite install, Android (Termux), or a machine or container with less than 3 GB of memory: there is no download, the panel says moods come from common mood words, and faces still change.
  • With UI debug mode on, the server log shows [avatar-classify] … tier … lines with moods and timings, never chat text.
  • Roleplay without avatars or the Expression Engine: sprites still follow obvious mood words such as "wide eyes" and "beams", while "yellow" and "terrific" no longer change them.
  • Repeat the Roleplay and Game checks on desktop Firefox and Safari, Android Chrome, the Android app WebView, and iOS Safari. On phones, confirm that typing and streaming stay smooth and that the mood reader panel fits the screen.

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README) 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 note: docs/agents/avatars.md gets the updated section "How faces and mouths follow the reply". Its translation is covered by the existing follow-up #7540.

UI evidence (if applicable)

  • The mood reader panel shows on the agent page only once #7556's setup page is on staging. The local merged-tree run above checked it on desktop and phone widths. No screenshot is attached.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Avatars now respond to dialogue and game narration with expressions, emotions, and synchronized mouth movements.
    • In group chats, reactions can follow the speaking character. Game narration updates apply to the current turn, not past-turn reviews.
    • An optional local mood-reading model can enhance reactions. Avatar setup shows model availability and download progress; keyword-based reactions remain available when the model is unsupported or unavailable. Failed downloads retry after a delay.
  • Documentation
    • Expanded the avatar guide with details about reactions, model availability, and playback behavior.

🔄 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/7555 **Author:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Created:** 10/13/2026 **Status:** ✅ Merged **Merged:** 10/14/2026 **Merged by:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Base:** `staging` ← **Head:** `feat/avatars-director` --- ### 📝 Commits (10+) - [`92d1ce1`](https://github.com/Pasta-Devs/Marinara-Engine/commit/92d1ce1bcb269aa42b501c27ac442e46ad337ab4) feat(avatars): live faces and lip sync for avatars (director and classifier) - [`efc910c`](https://github.com/Pasta-Devs/Marinara-Engine/commit/efc910c7ba2b01ae86923931adc25d7f92b77ade) test(avatars): director regression, guide section, and dispose fixes - [`2ecf763`](https://github.com/Pasta-Devs/Marinara-Engine/commit/2ecf763e5c297afb2279c5f69a3cf02576bc1b6b) Merge remote-tracking branch 'origin/feat/avatars-contract' into feat/avatars-director - [`6838237`](https://github.com/Pasta-Devs/Marinara-Engine/commit/68382373cd51a3732f47843bab42a989c8d1a326) fix(avatars): Game lines reach a late stage, not while reviewing past turns - [`ffffb4c`](https://github.com/Pasta-Devs/Marinara-Engine/commit/ffffb4c22c354c7f78b9520245e85e4003ca6d58) fix(avatars): a reset classifier load never becomes the model; plainer guide - [`1a601fe`](https://github.com/Pasta-Devs/Marinara-Engine/commit/1a601fe43dfde2d6bf7cf8c04255b599c9c76d25) Merge remote-tracking branch 'origin/staging' into feat/avatars-director - [`a85c132`](https://github.com/Pasta-Devs/Marinara-Engine/commit/a85c132fcc872d03d76e0be7bda1d886f8ba18ab) fix(avatars): director review fixes and the opt-in mood reader download - [`8f5655e`](https://github.com/Pasta-Devs/Marinara-Engine/commit/8f5655ee9e2405e02f8886bcfabd2de3b6bbd975) fix(avatars): a text the emotion model does not answer in time stops its worker - [`9bb959a`](https://github.com/Pasta-Devs/Marinara-Engine/commit/9bb959a7f88214148467b4878f01afcf9d4c1409) fix(avatars): a late Game stage keeps the last face without speaking an old line - [`3510bee`](https://github.com/Pasta-Devs/Marinara-Engine/commit/3510bee81b44c5346d14e9c888380d48c29f2e12) docs(avatars): say the mood reader retries a failed download in about 10 minutes ### 📊 Changes **24 files changed** (+3577 additions, -102 deletions) <details> <summary>View changed files</summary> 📝 `docs/agents/avatars.md` (+23 -1) 📝 `packages/client/src/components/chat/SpriteOverlay.tsx` (+8 -25) 📝 `packages/client/src/components/game/GameNarration.tsx` (+6 -0) ➕ `packages/client/src/features/avatars/director/AvatarModelStatus.tsx` (+54 -0) 📝 `packages/client/src/features/avatars/director/avatar-director.ts` (+642 -18) ➕ `packages/client/src/features/avatars/director/game-line-feed.ts` (+59 -0) ➕ `packages/client/src/features/avatars/director/reply-text.ts` (+179 -0) ➕ `packages/client/src/features/avatars/director/speech-clock.ts` (+214 -0) 📝 `packages/client/src/features/avatars/setup/AvatarAgentSetup.tsx` (+2 -0) ➕ `packages/client/src/hooks/use-avatar-emotion-model.ts` (+33 -0) 📝 `packages/client/src/hooks/use-generate.ts` (+17 -0) 📝 `packages/client/src/localization/locales/en.json` (+8 -0) 📝 `packages/server/src/middleware/rate-limit.ts` (+14 -0) 📝 `packages/server/src/routes/avatar-classify.routes.ts` (+61 -5) 📝 `packages/server/src/routes/generate/expression-agent-utils.ts` (+2 -40) ➕ `packages/server/src/services/avatars/classifier/emotion-model.worker.ts` (+46 -0) ➕ `packages/server/src/services/avatars/classifier/local-emotion-model.ts` (+190 -0) 📝 `packages/server/src/services/avatars/emotion-classifier.ts` (+322 -12) 📝 `packages/server/src/services/local-embedder.ts` (+1 -1) 📝 `packages/shared/src/index.ts` (+1 -0) _...and 4 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`. ## Linked issue Refs #7537 (lane: Director). Guide translation follow-up: #7540. Depends on https://github.com/Pasta-Devs/Marinara-Engine/pull/7539, "feat(avatars): shared contract for the 2D and 3D avatar agents" (Refs #7537). It has now **merged into `staging`**, and this branch merged `staging` at `1a601fe43`, so the diff shows only this lane. The TTS lane (#7547) and the avatar docs (#7551) are also on `staging` and in that merge. After the 2D lane (#7549) landed, the branch merged `staging` again at `e481304aa`. The only conflict was `en.json`, resolved by keeping both key blocks in sorted order. **Merge note for whichever of #7555 and #7556 merges second.** The mood reader's status panel (`AvatarModelStatus`) is mounted by this PR since `5a467451c`. The setup page stub `features/avatars/setup/AvatarAgentSetup.tsx` renders `<AvatarModelStatus />`, and `avatar-director.regression.ts` fails if the setup page stops importing or rendering it. That stub belongs to the base lane (#7556), so the second PR gets one conflict in that file. Resolve it by keeping #7556's page and adding `import { AvatarModelStatus } from "../director/AvatarModelStatus";` plus `<AvatarModelStatus />` as the first child of `<div className="space-y-4" data-avatar-setup={agentId}>`. That resolution was checked locally (see Validation). Earlier, the mount was only requested on #7556 (https://github.com/Pasta-Devs/Marinara-Engine/pull/7556#issuecomment-6154694561), and the integration check found that no merged page showed the panel. ## Why this change - Avatars need a face that changes while a reply streams, and a mouth that moves with what the character says. Mari ruled out LLM-written tags and Decision models, because they run after the reply. So Roleplay needs a fast local classifier that reads each sentence as it appears. Game mode already has the Game Master's per-line expressions. The Expression Engine's pick should stay the final word. - The Engine had two separate mood word lists, the Roleplay sprite fallback and the Expression Engine's fallback pick. They disagreed and matched word prefixes, so "yellow" read as angry and "terrific" as scared. The classifier needs one good list, so all three uses now share it. - Mari's decision (2026-10-13, review thread on `emotion-classifier.ts`): the emotion model downloads only when an avatar agent is enabled, never on install or on the first classify request. The agent's page shows the progress and any error, and Lite and Termux keep skipping it. - Review of `ffffb4c22` found several problems. A reply's last moods were lost while the typewriter caught up, and in group chats the wrong avatar spoke. A late Expression Engine pick froze the next reply's face. The model loaded and ran on the server's main thread during streaming. It could not load offline, and it left partial downloads behind. ## What changed - **Roleplay sprites without the Expression Engine, and the Expression Engine's fallback for a character it skipped, read mood words differently.** - They share one word list that matches whole words, so "yellow", "terrific", "crypt", "museum", "considerable" or "concerning" no longer change a sprite. - Phrases the old Roleplay fallback caught still work: "wide eyes", "beams", "shyness", "ached" and "heart racing". - It knows more words, plus common mood words in German, Spanish, French, Italian, Portuguese, Polish, Russian, Japanese, Chinese and Korean. It ignores accents, and Korean syllables stay whole: 무성한, "overgrown", no longer reads as scared. - One ordering change: when a skipped character's text mentions both a general mood and a blush ("she blushes and smiles"), the fallback now tries the happy sprite before the blush sprite. That is the order the Roleplay fallback already used. - **Avatars get live faces in Roleplay.** - Each finished sentence of the visible reply is classified. The face changes only on a clear mood (a score of 0.45 with a 0.15 lead) and holds at least 2 s. - It needs two calm sentences to go back to calm, and it relaxes 4 s after the reply unless the Expression Engine settled it. - A reply now ends when its generation does, after the typewriter has shown all of it. A reply that streams faster than it is shown keeps sending whole sentences, never single letters. - Streaming off is read from the setting. A reply that arrives in one chunk with streaming on is mouthed once, as it types. With streaming off, including when a rewrite agent holds the reply, the whole reply is classified once and its dialogue is spoken within 8 s. - **Game mode faces** follow the Game Master's expression for the line on screen. A character's thought, or the player's own input, sets the face but not the mouth, as Game voices already treat them. - **The Expression Engine's pick** is the final face for the reply it was made for. A pick that arrives after you sent your next message no longer lands on the new reply. Agent results now keep their message id. - **Group chats.** - In an Individual group, the replying member speaks, and that includes swiping one member's message. - In a Merged group, each paragraph belongs to the character it names, including with streaming off: the server saves a Merged reply under the first character. While a paragraph that names nobody is still appearing, its dialogue waits until a name or the paragraph's end shows who says it. A speech tag after the quote (`"Get out," Bob growls.`) therefore never makes two avatars say the line. - **Mouths** move only for dialogue (quotes, `[Name]:` lines, speaker tags), at about 14 characters a second. They speed up to 1.5x and then skip ahead when the text outruns speech, and close 150 ms after the last word. Japanese kana pick the mouth shape by vowel row, and other scripts move rhythmically. While text-to-speech plays, the voice level moves the mouth instead. - **Body states**: thinking from send to the first words, talking, listening (others while someone talks, characters while you type), and idle. - **The mood reader (local emotion model)**: [Horizon-Labs/multilingual-emotions-small](https://huggingface.co/Horizon-Labs/multilingual-emotions-small), Apache-2.0, 36 languages. - **When it downloads.** It downloads (about 289 MB) only when a Roleplay chat with 2D or 3D Avatars turned on opens: the stage's director sends `POST /api/avatar-classify/model`. The server accepts that only for a Roleplay chat with an installed avatar agent turned on, and answers 409 otherwise. Installing an agent never downloads it, a classify request never downloads or loads it, and Game mode never asks for it. - **Progress.** `GET /api/avatar-classify/model` reports the state for the agents' pages: not downloaded, downloading, loading, downloaded, failed, or kept on the word list. The new `AvatarModelStatus` shows it in plain, localized copy with a progress bar. - **Retries.** A failed download is tried again by itself 10 minutes later, the next time the stage asks. It asks again at most once a minute while it gets keyword answers. - **Files.** The four files are pinned by commit, size and SHA-256 and fetched straight from Horizon through the sidecars' checked download. A stopped download's leftover is replaced, never piled up. The model then loads from disk only, so it works offline. - **Worker thread.** It loads and runs in a worker thread, so the server never pauses while a reply streams. It unloads after 10 idle minutes, and a crashed worker is dropped and loaded again later. - **Who keeps the word list.** Lite installs, servers without onnxruntime-node's native binding (Termux) and machines with less than 3 GB of memory keep the word list. - **Blending.** When a word names a mood, the model's answer is averaged with it, because the model calls most narrated prose neutral. A text the model failed on is not cached as the model's answer. - **Guide**: the section "How faces and mouths follow the reply" in `docs/agents/avatars.md` covers the download rule, the progress on the agent page, offline use, memory, the Game thought rule and group chats. ### Contract and shared-file changes (called out) - `packages/shared/src/index.ts`: one added export line for the new `utils/expression-keywords.ts`. This is additive, and `types/avatars.ts` is untouched. - `packages/shared/src/types/agent.ts`: `AgentResult` gains an optional `messageId`. It is additive, and existing results without it behave as before. - `createAvatarDirector(options, hooks?)`: an optional second parameter that only regressions use (stubbed classify and prepare calls). The stage's one-argument call is unchanged. - Edits outside the lane's own folders: - the two keyword callers the lane was asked to merge (`SpriteOverlay.tsx`, `expression-agent-utils.ts`); - the route's rate-limit rule (`middleware/rate-limit.ts`); - one `export` on the existing ONNX binding check (`local-embedder.ts`); - the allowed one-line Game feed in `GameNarration.tsx`; - `hooks/use-generate.ts`: a swipe in an Individual group names its member as the streaming character, and both agent-result paths keep the result's message id; - a new `hooks/use-avatar-emotion-model.ts` for the status query; - the base lane's setup page stub `features/avatars/setup/AvatarAgentSetup.tsx`: it renders `<AvatarModelStatus />`, so the panel is on both avatar agents' pages whichever PR merges first (see the merge note above). - `en.json`: new flat keys under `avatars.director.model.*` only, placed after `app.documentTitle`. The base lane's `avatars.setup.*` block sorts after them. ### Model choice (classifier research, 2026-10-13) This model ranked first in the research. Its licence is permissive (Apache-2.0, on the MIT-licensed base mmBERT-small), and its ONNX q8 build runs unchanged in the Engine's installed `@huggingface/transformers` 4.3.0. It is multilingual: BRIGHTER 10-language top-1 is 0.69, against about 0.39 for the English-only models. It is on par with SamLowe on English GoEmotions. Its weakness is narrated roleplay prose, which the keyword blend covers. Per Mari's decision, the commit is pinned and the files come from Horizon directly, with no mirror. On 42 roleplay lines written in 9 languages, the model alone got 20/42, keywords alone 28/42, and the blend 34/42. That set is small and self-written, so it is only a rough signal. ## 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` Commands run by the agent are listed below as results, not ticked boxes. They ran on a machine shared with other lanes, with a load average of 20–35. Final head: `5a467451c`. - **Integration fix on `5a467451c`** (the mood reader panel had no mount on the merged tree): - `pnpm check`: exit 0, with the same pre-existing lint warning in `HomeProfessorMariChat.tsx`. Main entry: 313 kB. - Regressions per filter, all passed: `avatar-` (10/10, now including the 2D lane's), `agent-activation` (2/2), `spatial-context`, `open-issues`, `game-narration` (2/2), `roleplay-streaming`, `expression-` (2/2), `group-` (7/7) and `roleplay-vn-tts`. - The new mount check in `avatar-director.regression.ts` fails on the old null stub and on #7556's page at `2b417feaa`. It passes with the mount. - A local throwaway merge of #7556 (`2b417feaa`) into this branch, discarded afterwards: `AvatarAgentSetup.tsx` was the only conflicting file, resolved as in the merge note. On that tree, `avatar-` regressions passed 12/12. Playwright on private ports passed #7556's `e2e/avatar-setup.e2e.ts` and a temporary spec on desktop Chromium and mobile Chromium (6/6). The temporary spec has since been deleted. It showed the panel on the 2D and 3D Avatars pages with "Downloading the mood reader: 41%." and its progress bar, inside the phone's width, and confirmed that opening the page never starts the download. - Local CodeRabbit (`coderabbit review --agent --committed --base-commit e481304aa`): 0 findings, 2 files reviewed. - `pnpm check` on `3510bee81`: exit 0. It covers format, localization, impeccable, lint, type checks and the production build. The one lint warning is pre-existing, in `HomeProfessorMariChat.tsx`. Main entry: 313 kB. It also passed on `a85c132fc`. - `node scripts/run-regressions.mjs --filter <name>`, run per filter, all passed: - on `3510bee81`: `avatar-` (8/8, including `avatar-classifier`, `avatar-director`, the `avatar-contract` guard and `avatar-tts-lipsync`), `open-issues`, `game-narration` (2/2), `roleplay-streaming` and `expression-` (2/2); - on `a85c132fc`: `agent-activation` (2/2), `spatial-context`, `roleplay-vn-tts` and `group-` (7/7). - `pnpm localization:check` on `3510bee81`: exit 0. - **Proof that the new director checks catch the reported bugs.** I copied `avatar-director.regression.ts` with every assertion turned into a logged check (a temporary copy, since deleted) and ran it against the old director files from `ffffb4c22`. Every new check failed there: - fragments `["t","o","h","e",…]` reached the classifier after message-ready; - a one-chunk reply was mouthed for 5888 ms, with growing prefixes `"Alic"`, `"Alice smi"`, … sent to the classifier; - a held rewrite's dialogue was spoken for 1536 ms; - in a Merged reply with streaming off, only Alice spoke (`{"alice":2992,"bob":0}`); - Alice mouthed Bob's tagged line; - a stale Expression Engine pick landed on the new reply; - a Game thought moved the mouth; - the model was never asked for. - **The real pinned model, run outside CI** through the worker, with `DATA_DIR` set to a temporary folder under the worktree that was deleted afterwards: - The first download and load took 45 s. The longest server event-loop pause was about 100–140 ms, which matches the idle baseline under this load (199 ms with nothing running). Before, the main thread stalled for 1.6–2.3 s. - A 16-text request took 2.0–3.5 s, with longest pauses of 13–100 ms. One short text took 68–134 ms. - Main-process RSS stayed at 350–560 MB, because the model's memory sits in the worker. - With `fetch` stubbed to throw, the model loaded from disk with no network request. - For comparison, loading the same files on the main thread took 17.8 s under the same load. The review measured single main-thread stalls of 1.6–2.3 s on a quiet machine. - **A timed-out text, checked by hand.** With the classify timeout lowered to 1 ms (by hand, then restored to 10 s), a 6-text request with the real model fell back to keywords in 43 ms in total. The model was dropped, and the next request answered from keywords at once. - `pnpm smoke:ui` on private ports, on `a85c132fc`: 7/7 passed, including Roleplay reasoning, stopped generations and Game narration. - **Local CodeRabbit** (`coderabbit review --agent --committed --base-commit 797877c54`, base = current `staging`): - on `a85c132fc`: **0 findings**, reviewing 23 files; - on `8f5655ee9`: 1 finding. A Game stage that mounted after narration still spoke the last dialogue line. Fixed in `9bb959a7f`, with a regression; - on `9bb959a7f`: 2 findings. The retry copy said "a few minutes" while the code waits 10. Fixed in `3510bee81`. The other asked for a `[docs-i18n]` follow-up for `docs/agents/avatars.md`, and was not changed: #7540 already covers that file and is linked above. - No run was made after `3510bee81`, which only changes copy. - Earlier, on `2ecf763e5`, one run found 3 issues, all fixed in `68382373c`. - **GitHub review threads.** All 8 are resolved; 5 were fixed or answered earlier. - Mari's decision on the download is implemented in `a85c132fc`, answered and resolved. - The PNGTuber `file`-path rule belongs to the merged contract and the 2D lane's data. It was answered and handed to #7549 (https://github.com/Pasta-Devs/Marinara-Engine/pull/7549#issuecomment-6154710680), then resolved here, because this PR no longer touches those files. - CodeRabbit on `a85c132fc`: a timed-out text left later texts waiting behind a busy worker. Fixed in `8f5655ee9`, answered and resolved. That review used the last of the hourly included GitHub reviews, so the GitHub review of `3510bee81` may come late. - **Not fixed here, follow-ups.** With streaming off in an Individual group, only the last member's reply moves an avatar: the server sends one `assistant_message_ready` after the group loop, and text-to-speech autoplay reads only that message too. Impersonation still streams into the character's live row, which the Roleplay surface itself renders as the character, so the character's avatar mouths it. Both need a server event or chat-store signal outside this lane. ### Manual verification needed The director has no UI of its own beyond the mood reader panel. The rest shows once the base lane's stage and a renderer are on `staging`. - Desktop Chrome, Roleplay, one character with an avatar, default streaming: send a message. Check each of these: - the avatar thinks until the first words; - the mouth moves only while quoted dialogue appears, not during narration; - the face changes when the reply turns clearly happy or sad, including for sentences shown after the reply is saved but still typing; - the face relaxes about 4 s after the reply ends. - The same chat with the Expression Engine on, using a slow connection for it: - after a reply, the face switches to the Engine's pick and stays there; - send the next message before the Engine finishes, and confirm the old pick does not freeze the new reply's face. - Turn streaming off, then: - the reply's dialogue is mouthed within about 8 s, and the face matches the reply's overall mood; - repeat with Prose Guardian on, and confirm the dialogue is still spoken for several seconds. - With text-to-speech autoplay on, the mouth follows the voice instead of the text. - Game mode: - click through Game Master dialogue lines: the speaking character's avatar takes that line's expression and moves its mouth; - narration lines and `[thought]` lines leave the mouth still; - advance to a narration line, then turn the avatar agent on in the chat: the avatar shows the last speaker's face without speaking the old line. - Merged group with Alice and Bob: - stream a reply where a line ends `…," Bob growls.`: only Bob's mouth says it; - with streaming off, each paragraph's dialogue moves the named character's mouth. - Individual group: swipe Bob's message. Only Bob thinks and talks. - **The mood reader** (once #7556's setup page is on `staging`). Check each of these: - install 2D Avatars and open its Agent editor page: the panel says it downloads the first time a Roleplay chat with the agent on opens, and the server log shows no download; - turn the agent on in a Roleplay chat: the log shows "Downloading the local emotion model" once, the page's bar climbs to 100%, then shows "downloaded and works offline", and `DATA_DIR/models/avatar-emotion/1bc9627f…` holds about 289 MB; - stop the server mid-download and start it again: only one `*.download` leftover existed, and the next download replaces it; - with the network off after the download, restart and chat: faces still use the model, and the log shows no download; - a Game-only chat with the agent on never downloads it. - On a Lite install, Android (Termux), or a machine or container with less than 3 GB of memory: there is no download, the panel says moods come from common mood words, and faces still change. - With UI debug mode on, the server log shows `[avatar-classify] … tier …` lines with moods and timings, never chat text. - Roleplay without avatars or the Expression Engine: sprites still follow obvious mood words such as "wide eyes" and "beams", while "yellow" and "terrific" no longer change them. - Repeat the Roleplay and Game checks on desktop Firefox and Safari, Android Chrome, the Android app WebView, and iOS Safari. On phones, confirm that typing and streaming stay smooth and that the mood reader panel fits the screen. ## Docs and release impact - [ ] No docs changes needed - [ ] Updated docs (README / CONTRIBUTING / android/README) 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 note: `docs/agents/avatars.md` gets the updated section "How faces and mouths follow the reply". Its translation is covered by the existing follow-up #7540. ## UI evidence (if applicable) - The mood reader panel shows on the agent page only once #7556's setup page is on `staging`. The local merged-tree run above checked it on desktop and phone widths. No screenshot is attached. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Avatars now respond to dialogue and game narration with expressions, emotions, and synchronized mouth movements. * In group chats, reactions can follow the speaking character. Game narration updates apply to the current turn, not past-turn reviews. * An optional local mood-reading model can enhance reactions. Avatar setup shows model availability and download progress; keyword-based reactions remain available when the model is unsupported or unavailable. Failed downloads retry after a delay. * **Documentation** * Expanded the avatar guide with details about reactions, model availability, and playback behavior. <!-- 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-24 04:07:34 +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#7794
No description provided.