[PR #7556] [MERGED] feat(avatars): storage, import, setup and chat stage for the avatar agents #7795

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

📋 Pull Request Information

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

Base: staging ← Head: feat/avatars-base


📝 Commits (9)

  • 82c6bba feat(avatars): storage, import, serving, setup and stage for the avatar agents
  • d2eba01 fix(avatars): keep a dragged avatar steady and mount PNGTuber avatars when sprites fail to load
  • 5fe461a test(avatars): browser check of the avatar setup and the chat stage
  • b082633 fix(avatars): show code scanning the model file containment and the routes' rate limit
  • 43427ac Merge remote-tracking branch 'origin/feat/avatars-contract' into feat/avatars-base
  • 298d994 fix(avatars): open the import picker in the same tap and free a renderer that fails to mount
  • b94c3ba fix(avatars): keep stored avatars intact on refused saves and pause covered chats
  • 701afe7 fix(avatars): clear the import picker when it returns without a file
  • 2b417fe Merge branch 'staging' into avatar lane

📊 Changes

31 files changed (+3412 additions, -66 deletions)

View changed files

📝 docs/agents/avatars.md (+25 -2)
➕ e2e/avatar-setup.e2e.ts (+156 -0)
➕ packages/client/public/sprites/avatar-demo/README.md (+8 -0)
➕ packages/client/public/sprites/avatar-demo/base.png (+0 -0)
➕ packages/client/public/sprites/avatar-demo/eyes-closed-mouth-open.png (+0 -0)
➕ packages/client/public/sprites/avatar-demo/eyes-closed.png (+0 -0)
➕ packages/client/public/sprites/avatar-demo/mouth-open.png (+0 -0)
📝 packages/client/src/components/agents/AgentEditor.tsx (+25 -1)
📝 packages/client/src/components/chat/ChatRoleplaySurface.tsx (+32 -0)
📝 packages/client/src/components/game/GameSurface.tsx (+27 -0)
📝 packages/client/src/features/avatars/setup/AvatarAgentSetup.tsx (+527 -5)
➕ packages/client/src/features/avatars/setup/AvatarSetupPreview.tsx (+149 -0)
➕ packages/client/src/features/avatars/setup/avatar-setup-logic.ts (+101 -0)
➕ packages/client/src/features/avatars/setup/demo-avatar.ts (+57 -0)
📝 packages/client/src/features/avatars/stage/AvatarStage.tsx (+440 -8)
➕ packages/client/src/features/avatars/stage/avatar-stage-logic.ts (+148 -0)
➕ packages/client/src/features/avatars/stage/use-avatar-pause.ts (+54 -0)
➕ packages/client/src/features/avatars/stage/use-avatar-renderer.ts (+109 -0)
➕ packages/client/src/features/avatars/stage/use-chat-avatar-agents.ts (+21 -0)
➕ packages/client/src/hooks/use-avatar-models.ts (+73 -0)

...and 11 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 (epic: 2D and 3D avatar agents). This is the base lane; the epic stays open for the other lanes.

Depends on https://github.com/Pasta-Devs/Marinara-Engine/pull/7539 (opened ready, base staging, "feat(avatars): shared contract for the 2D and 3D avatar agents", Refs #7537). All 4 GitHub CodeRabbit threads on 15af58f10 got replies and are resolved. Two were fixed in df538660f: Windows device names in stored paths, and the code comments now point at the developer notes. Two were answered: the docs-i18n issue is #7540, and the 1.73 bump stays, with a publish-order rule added to the developer notes. CI on df538660f was still running at hand-off, so mergeStateStatus was BLOCKED; on 15af58f10 every check had passed except complete-node-regressions, which was still pending. Not merged; no checkboxes ticked. (its commits show in this diff until it merges)

Update: #7539 has merged into staging, so the diff against staging now shows only this lane.

Why this change

  • The avatar agents need somewhere to keep each character's and persona's avatar, a way to import model files, a page to set avatars up, and a layer in chats that shows them. Every other lane (2D, 3D, director, TTS, generation, packages) plugs into these pieces.
  • Nothing shows to users until the 2D Avatars or 3D Avatars package is installed, and those packages are published only after this lane, the stage and a renderer are on staging. Until the renderer lanes land, set-up avatars draw nothing (the renderer stubs are inert).

What changed

  • Avatar setup on the agent's page. The 2D Avatars and 3D Avatars pages in the Agent editor get an Avatars section: choose a character or persona, turn its avatar on or off, choose the avatar type, build a PNGTuber avatar from the character's expression sprites (Use my sprites), or import a PNGTuber Plus .save, a mesh avatar .mavatar, a VRM model .vrm and a .vrma idle animation. Faces shows which face each feeling (and, for models, each mouth shape and the blink) uses, marked Found, Your choice or Missing, with a menu to change it. Movement has the lip sync, blinking and idle-motion switches. Preview draws the avatar through its lazily loaded renderer with Try a face and Talk; before anything is set up it shows an example PNGTuber. Remove deletes one avatar type. The kind panels and the generation panel of the other lanes load below it. The section loads only on these two pages.
  • Avatars in chats. Roleplay, Visual Novel and Game chats show the avatars of the chat's characters and persona when the chat has agents on and the matching avatar agent added (independent of the Expression Engine; the full-body sprite is never hidden for you). Avatars stand where the full-body sprite would, share its size and side, and move with the sprites' Arrange mode. The stage code loads only in such chats. It follows the budget: at most 2 avatars on phones and 4 on desktops, pixel ratio capped at 1.5×/2×, 30 fps talking, 30 fps idle on desktop and 20 (15 under load) on phones, and nothing drawn while the tab is hidden, the window is in the background, the Appearance settings are open (the app's existing "effects paused" state), the chat is off screen, or (on phones, where the chat stays mounted underneath) a panel or editor covers the chat. Reduced motion (system setting or Reduce Ambient Animations & Effects) and the idle-motion switch drop breathing and the waiting poses; one frame loop drives every renderer with frames from the director (the stub holds a neutral idle until the director lane lands).
  • Storage. DATA_DIR/avatar-models/<character|persona>/<id>/ holds avatar.json (validated against the shared schema on every write and read back only when valid) and each kind's files. Writes go through one queue per owner, and every path is checked to stay inside the owner's folder. A save is checked before any file is written, and all of its files are written before any stored file is replaced, so a refused import leaves the saved avatar as it was. Only files a write newly names must exist, so a file lost since it was saved (a skipped restore, a hand deletion) never blocks turning the avatar off, saving another kind or removing the broken kind; removing a kind writes the config before deleting that kind's files. Saving an import removes files of that kind the new data no longer names. Removing the last kind removes the folder.
  • Routes at /api/avatar-models: list, get, PUT (a partial update; files it names must exist), import (multipart; the file goes to the importer that recognises it, or to the importer of its extension so the person gets that importer's plain message, such as "VRM files can't be imported yet." while the stubs are in place), file serving (PNGTuber layers only as raster images; .mavatar only with ZIP bytes as application/zip; .vrm/.vrma only with glTF bytes as model/gltf-binary; symlinks may not leave the folder; ranges work), and removal of a kind or a whole avatar. Imports add no size limit below the global upload cap (256 MiB).
  • Lifecycle. Deleting a character or persona deletes its avatar, including when an import or settings save is still running at that moment (the route re-checks the owner after writing and removes the folder). Clearing all Characters (Professor Mari's avatar stays) or all Personas in the Danger Zone removes their avatars too. Backups and profile exports include avatar-models, and restored PNGTuber layers must be real images. Clearing Media & Assets in the Danger Zone empties the folder. Character card exports don't include avatars.
  • Docs. docs/agents/avatars.md: "Setting up an avatar" (including where files live and backups) and "Performance and devices".
  • Example avatar. Four small PNGs in packages/client/public/sprites/avatar-demo/ (generated with Codex image generation; provenance in its README), fetched only by the setup preview and skipped by the service worker.
  • Contract change (smallest possible, called out): scripts/regressions/avatar-contract.regression.ts asserted that GET /api/avatar-models answers 404 ("not served yet"). This lane serves it, so that one URL now asserts 200; the classify and generation routes keep their 404 check. AvatarStageProps is unchanged: the stage takes its sprite-layout props through its own AvatarStageLayout interface in stage/AvatarStage.tsx.
  • Contract change (additive, called out): packages/client/vite.config.ts. Workbox globIgnores now also skips {pngtuber,mesh-avatar,vrm}-renderer-*.js, vendor-three*.js and vendor-mesh-avatar*.js, so the service worker no longer downloads avatar renderer code for every PWA install; it loads only when an avatar is shown. The small AvatarStage/AvatarAgentSetup chunks stay precached.

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 (results as reported; boxes above are for the human reviewer):

  • pnpm install --frozen-lockfile --prefer-offline --store-dir <main checkout>/.pnpm-store and pnpm build:shared: done (no dependency or lockfile change in this lane).
  • pnpm check on the final head: passed (impeccable, localization, Prettier, ESLint with the one existing warning in HomeProfessorMariChat.tsx, e2e and token-estimation types, full build). pnpm localization:check on its own: passed.
  • Lazy chunks, from the built packages/client/dist (static-import walk from the entry in index.html): AvatarAgentSetup 15.7 KiB, AvatarStage 8.1 KiB, avatar-stage-logic 2.9 KiB, use-avatar-renderer 2.8 KiB, use-chat-avatar-agents 0.3 KiB and the renderer stubs are all lazy; none is reachable from the entry. No three, three-vrm or mesh-avatar chunk exists yet (the renderers are stubs).
  • New regressions: scripts/regressions/avatar-models.regression.ts (storage, routes, import dispatch with the stubs and with a working importer and a 12 MB upload, file serving and refusals, kind/owner removal, character and persona delete cascade, backup/restore coverage) and scripts/regressions/avatar-stage-logic.regression.ts (kind fallback, the 2/4 budget, fps and pixel-ratio caps, feature switches and reduced motion, PNGTuber picture lookup, "Use my sprites", participants and agent gating, lazy mounts). Both pass.
  • node scripts/run-regressions.mjs --filter for avatar- (7 files incl. the contract regression), agent-activation, spatial-context, open-issues, admin-preset-expunge, automatic-backup, backup-download, backup-folder, capability-package-lifecycle, character-delete-chat-membership, profile-import, profile-apply, sprite-list-security, sprite-background, zip-reader: all passed.
  • Full node scripts/run-regressions.mjs locally: 618/624. Not passed: termux-sharp (the known local-only store issue from #7539: offline install against this worktree's empty store) and five timing-sensitive files that timed out or missed a 1-second bound while the machine ran at load average ~30 with other lanes (advanced-memory-core, code-scanning-content-parsing, multiplayer-peer-server-security, native-export-memory, ruleset-combat-director); two of those passed on rerun, none touches code in this PR. CI complete-node-regressions passed on the first push (82c6bba9f).
  • Browser: npx playwright test e2e/avatar-setup.e2e.ts (own ports) passed on desktop Chromium (3 repeats), Android-sized Chromium and iPhone-sized WebKit. It mocks only the installed package and the sprite list; the avatar routes, storage and character delete are real.
  • Local CodeRabbit (coderabbit review --agent --committed --base-commit df538660f, Pasta-Devs org): 0 findings.
  • GitHub CodeRabbit on 43427acf8: 4 threads, all replied to and resolved. Fixed in 298d994da: the import picker now opens in the same tap (no frame callback; Safari keeps the click in the gesture), and a renderer whose mount() fails is disposed at once. Answered: personas do keep their sprites under the shared /api/sprites/:id route (the persona editor uses it), so Use my sprites stays available for them. The characters/personas expunge scopes first stayed as they were, matching sprite folders; that changed in b94c3ba20 (see the review round below), since those scopes already remove the deleted owners' profile pictures and an avatar folder can't be reached from the UI once its owner is gone. After the fixes: client typecheck, ESLint and Prettier clean; the e2e passed again on desktop Chromium and iPhone-sized WebKit.
  • GitHub CodeQL on 82c6bba9f: two alerts in avatar-models.routes.ts, both fixed in b082633d4. js/path-injection: the model file path was already contained by resolveAvatarFile; the route now repeats it as prefix checks CodeQL recognises, before and after resolving symlinks. js/missing-rate-limiting: every avatar-model route now declares the global default bucket (600 per minute, the limit that already applied).
  • Review round on 298d994da (b94c3ba20, 701afe79e):
    • Fixed: a file lost since it was saved no longer blocks turning the avatar off, saving another kind or Remove (which used to delete the kind's files and then fail, leaving both kinds listed with no files); a refused save no longer overwrites a stored file first; an import or save racing a character/persona delete no longer leaves an orphaned folder; the characters/personas expunge scopes remove their avatar folders (Professor Mari's stays); on phones the chat's avatars pause while a panel or editor covers the chat (it stays mounted underneath, so the setup preview no longer draws beside two hidden avatars); the setup preview idles at the budget rate (20 fps on phones); the Faces list links each menu to its Found / Your choice / Missing text (aria-describedby); the service worker skips avatar renderer chunks (contract file, above).
    • Not changed: every settings change still remounts the preview's and stage's renderer. The renderers read config.features when they mount (pngtuber blink, VRM copies the flags, mesh-avatar idleMotion), re-imports keep their file names, and config.updatedAt is the ?v= cache-buster for stored files, so the config object is the only signal that files changed. Avoiding the reload needs a contract addition (a renderer config update or a per-kind file revision); suggested as a follow-up on #7537.
    • Not changed: moving avatars still uses the Expression Engine's sprite Arrange mode. The Arrange control lives in ChatSettingsDrawer/ExpressionSpriteSettings, outside this lane's files; Game chats can't arrange full-body sprites either (no placements are passed there). Avatars without it stand where the full-body sprite's default place is. Suggested as a follow-up on #7537.
    • node scripts/run-regressions.mjs --filter scripts/regressions/avatar-models.regression.ts: passed. It now also covers a refused save keeping the stored bytes and leaving no temporary file, a deleted layer file not blocking PUT {enabled:false}, another kind's save and removal of both kinds, a character deleted during an import (404, no folder), and the characters+personas expunge (folders gone, Professor Mari's kept). Against the previous server code it fails on the import race (200 instead of 404) and, with only the route fix applied, on the refused save changing the stored bytes.
    • node scripts/run-regressions.mjs --filter avatar (7 files) and --filter for admin-preset-expunge, admin-server-restart, request-timeouts, speech-to-text-server, shutdown-deadline, termux-postmortem, termux-client-build, backup (4 files): all passed.
    • pnpm check: passed (exit 0; the one existing ESLint warning in HomeProfessorMariChat.tsx). pnpm localization:check: passed, no new keys.
    • npx playwright test e2e/avatar-setup.e2e.ts e2e/avatar-preview.e2e.ts (own ports) on desktop Chromium, Android-sized Chromium and iPhone-sized WebKit: avatar-setup passed on all three. It now opens the setup page over the active chat; on the phone projects it asserts the covered chat's stage is paused (data-avatar-paused="true"), and on every project that the uncovered chat's stage is not, plus the Faces descriptions. With the covered check disabled it fails on mobile Chromium as expected. avatar-preview's library-portraits test failed in that combined run but passed when run alone on desktop Chromium; it doesn't touch this lane's code.
    • Built packages/client/dist/sw.js: the precache list no longer has pngtuber-renderer, mesh-avatar-renderer or vrm-renderer; AvatarStage (8 KB), AvatarAgentSetup (16 KB) and use-avatar-renderer (3 KB) stay.
    • Local CodeRabbit (coderabbit review --agent --committed --base-commit 1e9e58776, the merge base with origin/staging): 2 findings. Fixed in 701afe79e: the import input is cleared when the picker returns without a file. Not changed: the "Try a face" menu's text-xs can't cause iOS focus zoom, because globals.css sets input, select, textarea { font-size: 1rem } under @media (pointer: coarse) outside any cascade layer, which overrides Tailwind's layered utilities (the same rule covers every menu in the app). Not rerun after the one-line fix.

Manual verification notes

The renderers are stubs until the 2D and 3D lanes land, so avatars and the preview draw nothing yet except where noted. To test before the packages are published, install a local build of the 2D Avatars or 3D Avatars package (or add 2d-avatars to a chat's agents with a package that declares that id).

  • Desktop Chrome, Firefox and Safari: open Agents → 2D Avatars. The Avatars section shows a character/persona picker; choose a character that has expression sprites and press Use my sprites. The type list shows PNGTuber sprites — Shown in chats, Faces lists the six feelings bound to sprite names, and changing one marks it Your choice. Toggle Show this avatar in chats and the three Movement switches and reload: the choices stay.
  • Same page: press Import a VRM model on the 3D Avatars page and pick any .vrm: the message "VRM files can't be imported yet." appears (until the 3D lane lands). Pick a .txt renamed to .save on the 2D page: "PNGTuber Plus files can't be imported yet."
  • Same page: Remove asks first, then the type shows Not set up and the files are gone from data/avatar-models/character/<id>/.
  • Desktop Chrome DevTools → Network: open a Roleplay chat without avatar agents; no AvatarStage, vendor-three* or vendor-mesh-avatar file is requested. Add 2D Avatars to the chat's agents: only the AvatarStage chunk (and, once a renderer lane lands, that renderer's chunk) loads.
  • Roleplay and Visual Novel: with avatars set up for two characters and the persona, three canvases appear where the full-body sprites stand (inspect [data-avatar-stage]). Turn on Arrange in the Expression Engine's sprite settings: each avatar shows a check button and can be dragged; the place stays after reload.
  • Game mode: an avatar canvas shows for each game character with an avatar, centred like the full-body sprite; it disappears while the overworld map is shown.
  • Delete a character that has an avatar: its data/avatar-models/character/<id>/ folder is gone. Download a backup: the zip contains avatar-models/.
  • Lost file: set up a PNGTuber avatar with a stored layer and a VRM model (once the import lanes land), delete one pngtuber/*.png by hand, then toggle Show this avatar in chats, remove the VRM type and remove the PNGTuber type: each works, and the folder is gone at the end.
  • Settings → Advanced → Danger Zone: clear only Characters (and separately only Personas): their data/avatar-models/character/* (except Professor Mari's) and data/avatar-models/persona/* folders are gone; Media & Assets still empties the whole folder.
  • Android Chrome and iOS Safari: open a Roleplay chat with an avatar, then open Agents → 2D Avatars (or the right panel). In remote DevTools, [data-avatar-stage] under the covered chat carries data-avatar-paused="true" and only the setup preview animates; closing the panel resumes the chat avatars.
  • Screen reader (VoiceOver or NVDA): tab through Faces; each menu reads its feeling, then Found, Your choice or Missing.
  • Android Chrome and the Android app WebView, iOS Safari: the Avatars section stacks (preview on top), menus are native pickers, and a Roleplay chat with avatars shows at most two canvases.
  • Light and dark mode, a custom theme and Accent Pulse: the error box uses the steady accent, nothing uses hard-coded colours.

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/agents/avatars.md changed; its translation is tracked in #7540, which already covers this guide. docs/data/where-data-is-stored.md does not list avatar-models yet (outside this lane's files); a follow-up can add the row.

UI evidence (if applicable)

None yet: the renderers are stubs, so there is nothing to capture beyond the setup form.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added avatar settings for characters and personas, including avatar-kind selection, expression bindings, feature options, and configuration management.
    • Added a demo avatar preview and sprite-based setup for PNGTuber avatars.
    • Avatar configurations are included in full backups and removed when the associated character or persona is deleted.
  • Documentation
    • Added a guide to 2D and 3D avatars and linked it from the agents overview.
    • Updated capability package documentation for avatar agents and API version 1.73.
  • Limitations
    • Importing avatar files and generating avatars are not yet available.

🔄 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/7556 **Author:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Created:** 10/13/2026 **Status:** ✅ Merged **Merged:** 10/13/2026 **Merged by:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Base:** `staging` ← **Head:** `feat/avatars-base` --- ### 📝 Commits (9) - [`82c6bba`](https://github.com/Pasta-Devs/Marinara-Engine/commit/82c6bba9ff905099fe5d02fec066778830841943) feat(avatars): storage, import, serving, setup and stage for the avatar agents - [`d2eba01`](https://github.com/Pasta-Devs/Marinara-Engine/commit/d2eba01080a73166b7c3fa8027bb2baaa523c7a0) fix(avatars): keep a dragged avatar steady and mount PNGTuber avatars when sprites fail to load - [`5fe461a`](https://github.com/Pasta-Devs/Marinara-Engine/commit/5fe461a692743c1db028341a57cf14be07e1fcb4) test(avatars): browser check of the avatar setup and the chat stage - [`b082633`](https://github.com/Pasta-Devs/Marinara-Engine/commit/b082633d4556470b885c19c120cc7b3abcb6c5ad) fix(avatars): show code scanning the model file containment and the routes' rate limit - [`43427ac`](https://github.com/Pasta-Devs/Marinara-Engine/commit/43427acf89d2fe5afbdf125261a06c4c5f891c67) Merge remote-tracking branch 'origin/feat/avatars-contract' into feat/avatars-base - [`298d994`](https://github.com/Pasta-Devs/Marinara-Engine/commit/298d994dac63632b315d6b5c6a5f280b0819609c) fix(avatars): open the import picker in the same tap and free a renderer that fails to mount - [`b94c3ba`](https://github.com/Pasta-Devs/Marinara-Engine/commit/b94c3ba20b886c28485ba3083b6ffc43735bd6fe) fix(avatars): keep stored avatars intact on refused saves and pause covered chats - [`701afe7`](https://github.com/Pasta-Devs/Marinara-Engine/commit/701afe79eed75a8d0ed3af4b2cfa6778f30774e3) fix(avatars): clear the import picker when it returns without a file - [`2b417fe`](https://github.com/Pasta-Devs/Marinara-Engine/commit/2b417feaa3c05fb34ee674fa68b738359ae039a0) Merge branch 'staging' into avatar lane ### 📊 Changes **31 files changed** (+3412 additions, -66 deletions) <details> <summary>View changed files</summary> 📝 `docs/agents/avatars.md` (+25 -2) ➕ `e2e/avatar-setup.e2e.ts` (+156 -0) ➕ `packages/client/public/sprites/avatar-demo/README.md` (+8 -0) ➕ `packages/client/public/sprites/avatar-demo/base.png` (+0 -0) ➕ `packages/client/public/sprites/avatar-demo/eyes-closed-mouth-open.png` (+0 -0) ➕ `packages/client/public/sprites/avatar-demo/eyes-closed.png` (+0 -0) ➕ `packages/client/public/sprites/avatar-demo/mouth-open.png` (+0 -0) 📝 `packages/client/src/components/agents/AgentEditor.tsx` (+25 -1) 📝 `packages/client/src/components/chat/ChatRoleplaySurface.tsx` (+32 -0) 📝 `packages/client/src/components/game/GameSurface.tsx` (+27 -0) 📝 `packages/client/src/features/avatars/setup/AvatarAgentSetup.tsx` (+527 -5) ➕ `packages/client/src/features/avatars/setup/AvatarSetupPreview.tsx` (+149 -0) ➕ `packages/client/src/features/avatars/setup/avatar-setup-logic.ts` (+101 -0) ➕ `packages/client/src/features/avatars/setup/demo-avatar.ts` (+57 -0) 📝 `packages/client/src/features/avatars/stage/AvatarStage.tsx` (+440 -8) ➕ `packages/client/src/features/avatars/stage/avatar-stage-logic.ts` (+148 -0) ➕ `packages/client/src/features/avatars/stage/use-avatar-pause.ts` (+54 -0) ➕ `packages/client/src/features/avatars/stage/use-avatar-renderer.ts` (+109 -0) ➕ `packages/client/src/features/avatars/stage/use-chat-avatar-agents.ts` (+21 -0) ➕ `packages/client/src/hooks/use-avatar-models.ts` (+73 -0) _...and 11 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 Refs #7537 (epic: 2D and 3D avatar agents). This is the **base** lane; the epic stays open for the other lanes. Depends on https://github.com/Pasta-Devs/Marinara-Engine/pull/7539 (opened ready, base staging, "feat(avatars): shared contract for the 2D and 3D avatar agents", Refs #7537). All 4 GitHub CodeRabbit threads on 15af58f10 got replies and are resolved. Two were fixed in df538660f: Windows device names in stored paths, and the code comments now point at the developer notes. Two were answered: the docs-i18n issue is #7540, and the 1.73 bump stays, with a publish-order rule added to the developer notes. CI on df538660f was still running at hand-off, so mergeStateStatus was BLOCKED; on 15af58f10 every check had passed except complete-node-regressions, which was still pending. Not merged; no checkboxes ticked. (its commits show in this diff until it merges) Update: #7539 has merged into `staging`, so the diff against `staging` now shows only this lane. ## Why this change - The avatar agents need somewhere to keep each character's and persona's avatar, a way to import model files, a page to set avatars up, and a layer in chats that shows them. Every other lane (2D, 3D, director, TTS, generation, packages) plugs into these pieces. - Nothing shows to users until the 2D Avatars or 3D Avatars package is installed, and those packages are published only after this lane, the stage and a renderer are on `staging`. Until the renderer lanes land, set-up avatars draw nothing (the renderer stubs are inert). ## What changed - **Avatar setup on the agent's page.** The 2D Avatars and 3D Avatars pages in the Agent editor get an **Avatars** section: choose a character or persona, turn its avatar on or off, choose the avatar type, build a PNGTuber avatar from the character's expression sprites (**Use my sprites**), or import a PNGTuber Plus `.save`, a mesh avatar `.mavatar`, a VRM model `.vrm` and a `.vrma` idle animation. **Faces** shows which face each feeling (and, for models, each mouth shape and the blink) uses, marked Found, Your choice or Missing, with a menu to change it. **Movement** has the lip sync, blinking and idle-motion switches. **Preview** draws the avatar through its lazily loaded renderer with **Try a face** and **Talk**; before anything is set up it shows an example PNGTuber. **Remove** deletes one avatar type. The kind panels and the generation panel of the other lanes load below it. The section loads only on these two pages. - **Avatars in chats.** Roleplay, Visual Novel and Game chats show the avatars of the chat's characters and persona when the chat has agents on and the matching avatar agent added (independent of the Expression Engine; the full-body sprite is never hidden for you). Avatars stand where the full-body sprite would, share its size and side, and move with the sprites' **Arrange** mode. The stage code loads only in such chats. It follows the budget: at most 2 avatars on phones and 4 on desktops, pixel ratio capped at 1.5×/2×, 30 fps talking, 30 fps idle on desktop and 20 (15 under load) on phones, and nothing drawn while the tab is hidden, the window is in the background, the Appearance settings are open (the app's existing "effects paused" state), the chat is off screen, or (on phones, where the chat stays mounted underneath) a panel or editor covers the chat. Reduced motion (system setting or **Reduce Ambient Animations & Effects**) and the idle-motion switch drop breathing and the waiting poses; one frame loop drives every renderer with frames from the director (the stub holds a neutral idle until the director lane lands). - **Storage.** `DATA_DIR/avatar-models/<character|persona>/<id>/` holds `avatar.json` (validated against the shared schema on every write and read back only when valid) and each kind's files. Writes go through one queue per owner, and every path is checked to stay inside the owner's folder. A save is checked before any file is written, and all of its files are written before any stored file is replaced, so a refused import leaves the saved avatar as it was. Only files a write newly names must exist, so a file lost since it was saved (a skipped restore, a hand deletion) never blocks turning the avatar off, saving another kind or removing the broken kind; removing a kind writes the config before deleting that kind's files. Saving an import removes files of that kind the new data no longer names. Removing the last kind removes the folder. - **Routes** at `/api/avatar-models`: list, get, `PUT` (a partial update; files it names must exist), import (multipart; the file goes to the importer that recognises it, or to the importer of its extension so the person gets that importer's plain message, such as "VRM files can't be imported yet." while the stubs are in place), file serving (PNGTuber layers only as raster images; `.mavatar` only with ZIP bytes as `application/zip`; `.vrm`/`.vrma` only with glTF bytes as `model/gltf-binary`; symlinks may not leave the folder; ranges work), and removal of a kind or a whole avatar. Imports add **no** size limit below the global upload cap (256 MiB). - **Lifecycle.** Deleting a character or persona deletes its avatar, including when an import or settings save is still running at that moment (the route re-checks the owner after writing and removes the folder). Clearing all **Characters** (Professor Mari's avatar stays) or all **Personas** in the Danger Zone removes their avatars too. Backups and profile exports include `avatar-models`, and restored PNGTuber layers must be real images. Clearing **Media & Assets** in the Danger Zone empties the folder. Character card exports don't include avatars. - **Docs.** `docs/agents/avatars.md`: "Setting up an avatar" (including where files live and backups) and "Performance and devices". - **Example avatar.** Four small PNGs in `packages/client/public/sprites/avatar-demo/` (generated with Codex image generation; provenance in its README), fetched only by the setup preview and skipped by the service worker. - **Contract change (smallest possible, called out):** `scripts/regressions/avatar-contract.regression.ts` asserted that `GET /api/avatar-models` answers 404 ("not served yet"). This lane serves it, so that one URL now asserts 200; the classify and generation routes keep their 404 check. `AvatarStageProps` is unchanged: the stage takes its sprite-layout props through its own `AvatarStageLayout` interface in `stage/AvatarStage.tsx`. - **Contract change (additive, called out): `packages/client/vite.config.ts`.** Workbox `globIgnores` now also skips `{pngtuber,mesh-avatar,vrm}-renderer-*.js`, `vendor-three*.js` and `vendor-mesh-avatar*.js`, so the service worker no longer downloads avatar renderer code for every PWA install; it loads only when an avatar is shown. The small `AvatarStage`/`AvatarAgentSetup` chunks stay precached. ## 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 (results as reported; boxes above are for the human reviewer): - `pnpm install --frozen-lockfile --prefer-offline --store-dir <main checkout>/.pnpm-store` and `pnpm build:shared`: done (no dependency or lockfile change in this lane). - `pnpm check` on the final head: passed (impeccable, localization, Prettier, ESLint with the one existing warning in `HomeProfessorMariChat.tsx`, e2e and token-estimation types, full build). `pnpm localization:check` on its own: passed. - Lazy chunks, from the built `packages/client/dist` (static-import walk from the entry in `index.html`): `AvatarAgentSetup` 15.7 KiB, `AvatarStage` 8.1 KiB, `avatar-stage-logic` 2.9 KiB, `use-avatar-renderer` 2.8 KiB, `use-chat-avatar-agents` 0.3 KiB and the renderer stubs are all lazy; none is reachable from the entry. No three, three-vrm or mesh-avatar chunk exists yet (the renderers are stubs). - New regressions: `scripts/regressions/avatar-models.regression.ts` (storage, routes, import dispatch with the stubs and with a working importer and a 12 MB upload, file serving and refusals, kind/owner removal, character and persona delete cascade, backup/restore coverage) and `scripts/regressions/avatar-stage-logic.regression.ts` (kind fallback, the 2/4 budget, fps and pixel-ratio caps, feature switches and reduced motion, PNGTuber picture lookup, "Use my sprites", participants and agent gating, lazy mounts). Both pass. - `node scripts/run-regressions.mjs --filter` for `avatar-` (7 files incl. the contract regression), `agent-activation`, `spatial-context`, `open-issues`, `admin-preset-expunge`, `automatic-backup`, `backup-download`, `backup-folder`, `capability-package-lifecycle`, `character-delete-chat-membership`, `profile-import`, `profile-apply`, `sprite-list-security`, `sprite-background`, `zip-reader`: all passed. - Full `node scripts/run-regressions.mjs` locally: 618/624. Not passed: `termux-sharp` (the known local-only store issue from #7539: offline install against this worktree's empty store) and five timing-sensitive files that timed out or missed a 1-second bound while the machine ran at load average ~30 with other lanes (`advanced-memory-core`, `code-scanning-content-parsing`, `multiplayer-peer-server-security`, `native-export-memory`, `ruleset-combat-director`); two of those passed on rerun, none touches code in this PR. CI `complete-node-regressions` passed on the first push (82c6bba9f). - Browser: `npx playwright test e2e/avatar-setup.e2e.ts` (own ports) passed on desktop Chromium (3 repeats), Android-sized Chromium and iPhone-sized WebKit. It mocks only the installed package and the sprite list; the avatar routes, storage and character delete are real. - Local CodeRabbit (`coderabbit review --agent --committed --base-commit df538660f`, Pasta-Devs org): 0 findings. - GitHub CodeRabbit on 43427acf8: 4 threads, all replied to and resolved. Fixed in 298d994da: the import picker now opens in the same tap (no frame callback; Safari keeps the click in the gesture), and a renderer whose `mount()` fails is disposed at once. Answered: personas do keep their sprites under the shared `/api/sprites/:id` route (the persona editor uses it), so **Use my sprites** stays available for them. The `characters`/`personas` expunge scopes first stayed as they were, matching sprite folders; that changed in b94c3ba20 (see the review round below), since those scopes already remove the deleted owners' profile pictures and an avatar folder can't be reached from the UI once its owner is gone. After the fixes: client typecheck, ESLint and Prettier clean; the e2e passed again on desktop Chromium and iPhone-sized WebKit. - GitHub CodeQL on 82c6bba9f: two alerts in `avatar-models.routes.ts`, both fixed in b082633d4. `js/path-injection`: the model file path was already contained by `resolveAvatarFile`; the route now repeats it as prefix checks CodeQL recognises, before and after resolving symlinks. `js/missing-rate-limiting`: every avatar-model route now declares the global default bucket (600 per minute, the limit that already applied). - Review round on 298d994da (b94c3ba20, 701afe79e): - Fixed: a file lost since it was saved no longer blocks turning the avatar off, saving another kind or **Remove** (which used to delete the kind's files and then fail, leaving both kinds listed with no files); a refused save no longer overwrites a stored file first; an import or save racing a character/persona delete no longer leaves an orphaned folder; the `characters`/`personas` expunge scopes remove their avatar folders (Professor Mari's stays); on phones the chat's avatars pause while a panel or editor covers the chat (it stays mounted underneath, so the setup preview no longer draws beside two hidden avatars); the setup preview idles at the budget rate (20 fps on phones); the Faces list links each menu to its Found / Your choice / Missing text (`aria-describedby`); the service worker skips avatar renderer chunks (contract file, above). - Not changed: every settings change still remounts the preview's and stage's renderer. The renderers read `config.features` when they mount (pngtuber `blink`, VRM copies the flags, mesh-avatar `idleMotion`), re-imports keep their file names, and `config.updatedAt` is the `?v=` cache-buster for stored files, so the config object is the only signal that files changed. Avoiding the reload needs a contract addition (a renderer config update or a per-kind file revision); suggested as a follow-up on #7537. - Not changed: moving avatars still uses the Expression Engine's sprite **Arrange** mode. The Arrange control lives in `ChatSettingsDrawer`/`ExpressionSpriteSettings`, outside this lane's files; Game chats can't arrange full-body sprites either (no placements are passed there). Avatars without it stand where the full-body sprite's default place is. Suggested as a follow-up on #7537. - `node scripts/run-regressions.mjs --filter scripts/regressions/avatar-models.regression.ts`: passed. It now also covers a refused save keeping the stored bytes and leaving no temporary file, a deleted layer file not blocking `PUT {enabled:false}`, another kind's save and removal of both kinds, a character deleted during an import (404, no folder), and the `characters`+`personas` expunge (folders gone, Professor Mari's kept). Against the previous server code it fails on the import race (200 instead of 404) and, with only the route fix applied, on the refused save changing the stored bytes. - `node scripts/run-regressions.mjs --filter avatar` (7 files) and `--filter` for `admin-preset-expunge`, `admin-server-restart`, `request-timeouts`, `speech-to-text-server`, `shutdown-deadline`, `termux-postmortem`, `termux-client-build`, `backup` (4 files): all passed. - `pnpm check`: passed (exit 0; the one existing ESLint warning in `HomeProfessorMariChat.tsx`). `pnpm localization:check`: passed, no new keys. - `npx playwright test e2e/avatar-setup.e2e.ts e2e/avatar-preview.e2e.ts` (own ports) on desktop Chromium, Android-sized Chromium and iPhone-sized WebKit: `avatar-setup` passed on all three. It now opens the setup page over the active chat; on the phone projects it asserts the covered chat's stage is paused (`data-avatar-paused="true"`), and on every project that the uncovered chat's stage is not, plus the Faces descriptions. With the covered check disabled it fails on mobile Chromium as expected. `avatar-preview`'s library-portraits test failed in that combined run but passed when run alone on desktop Chromium; it doesn't touch this lane's code. - Built `packages/client/dist/sw.js`: the precache list no longer has `pngtuber-renderer`, `mesh-avatar-renderer` or `vrm-renderer`; `AvatarStage` (8 KB), `AvatarAgentSetup` (16 KB) and `use-avatar-renderer` (3 KB) stay. - Local CodeRabbit (`coderabbit review --agent --committed --base-commit 1e9e58776`, the merge base with `origin/staging`): 2 findings. Fixed in 701afe79e: the import input is cleared when the picker returns without a file. Not changed: the "Try a face" menu's `text-xs` can't cause iOS focus zoom, because `globals.css` sets `input, select, textarea { font-size: 1rem }` under `@media (pointer: coarse)` outside any cascade layer, which overrides Tailwind's layered utilities (the same rule covers every menu in the app). Not rerun after the one-line fix. ### Manual verification notes The renderers are stubs until the 2D and 3D lanes land, so avatars and the preview draw nothing yet except where noted. To test before the packages are published, install a local build of the 2D Avatars or 3D Avatars package (or add `2d-avatars` to a chat's agents with a package that declares that id). - Desktop Chrome, Firefox and Safari: open **Agents → 2D Avatars**. The **Avatars** section shows a character/persona picker; choose a character that has expression sprites and press **Use my sprites**. The type list shows **PNGTuber sprites — Shown in chats**, **Faces** lists the six feelings bound to sprite names, and changing one marks it **Your choice**. Toggle **Show this avatar in chats** and the three **Movement** switches and reload: the choices stay. - Same page: press **Import a VRM model** on the 3D Avatars page and pick any `.vrm`: the message "VRM files can't be imported yet." appears (until the 3D lane lands). Pick a `.txt` renamed to `.save` on the 2D page: "PNGTuber Plus files can't be imported yet." - Same page: **Remove** asks first, then the type shows **Not set up** and the files are gone from `data/avatar-models/character/<id>/`. - Desktop Chrome DevTools → Network: open a Roleplay chat without avatar agents; no `AvatarStage`, `vendor-three*` or `vendor-mesh-avatar` file is requested. Add 2D Avatars to the chat's agents: only the `AvatarStage` chunk (and, once a renderer lane lands, that renderer's chunk) loads. - Roleplay and Visual Novel: with avatars set up for two characters and the persona, three canvases appear where the full-body sprites stand (inspect `[data-avatar-stage]`). Turn on **Arrange** in the Expression Engine's sprite settings: each avatar shows a check button and can be dragged; the place stays after reload. - Game mode: an avatar canvas shows for each game character with an avatar, centred like the full-body sprite; it disappears while the overworld map is shown. - Delete a character that has an avatar: its `data/avatar-models/character/<id>/` folder is gone. Download a backup: the zip contains `avatar-models/`. - Lost file: set up a PNGTuber avatar with a stored layer and a VRM model (once the import lanes land), delete one `pngtuber/*.png` by hand, then toggle **Show this avatar in chats**, remove the VRM type and remove the PNGTuber type: each works, and the folder is gone at the end. - Settings → Advanced → Danger Zone: clear only **Characters** (and separately only **Personas**): their `data/avatar-models/character/*` (except Professor Mari's) and `data/avatar-models/persona/*` folders are gone; **Media & Assets** still empties the whole folder. - Android Chrome and iOS Safari: open a Roleplay chat with an avatar, then open **Agents → 2D Avatars** (or the right panel). In remote DevTools, `[data-avatar-stage]` under the covered chat carries `data-avatar-paused="true"` and only the setup preview animates; closing the panel resumes the chat avatars. - Screen reader (VoiceOver or NVDA): tab through **Faces**; each menu reads its feeling, then Found, Your choice or Missing. - Android Chrome and the Android app WebView, iOS Safari: the Avatars section stacks (preview on top), menus are native pickers, and a Roleplay chat with avatars shows at most two canvases. - Light and dark mode, a custom theme and Accent Pulse: the error box uses the steady accent, nothing uses hard-coded colours. ## 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/agents/avatars.md` changed; its translation is tracked in #7540, which already covers this guide. `docs/data/where-data-is-stored.md` does not list `avatar-models` yet (outside this lane's files); a follow-up can add the row. ## UI evidence (if applicable) None yet: the renderers are stubs, so there is nothing to capture beyond the setup form. 🤖 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** * Added avatar settings for characters and personas, including avatar-kind selection, expression bindings, feature options, and configuration management. * Added a demo avatar preview and sprite-based setup for PNGTuber avatars. * Avatar configurations are included in full backups and removed when the associated character or persona is deleted. * **Documentation** * Added a guide to 2D and 3D avatars and linked it from the agents overview. * Updated capability package documentation for avatar agents and API version 1.73. * **Limitations** * Importing avatar files and generating avatars are not yet available. <!-- 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:35 +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#7795
No description provided.