diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c4c7df7ad..b7efef0607 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,10 +5,15 @@ Notable changes to DeepSeekBot are recorded here. See the ## [Unreleased] -Pixel Avatars can be an elf, dwarf, orc or talking flower with beards, medieval outfits and headwear, and new PersonaBots start from a face seeded across every species. +Pixel Avatars can be an elf, dwarf, orc or talking flower with beards, medieval outfits and headwear, you can draw your own headpiece into a Part Library, and new PersonaBots start from a face seeded across every species. + +### Breaking Changes + +- The Part Library adds Profile schema Generation 73. Back up before upgrading; reopening an upgraded Profile requires a compatible binary or restoration of the pre-upgrade backup ([#1211](https://github.com/BotHarness/DeepSeekBot/issues/1211)). ### Added +- You can draw your own headpiece for a pixel Avatar: pencil, eraser, fill, mirroring across the face, a front layer over the hair and a back layer behind it, undo and redo, and a 1× preview on the real Avatar. Colors can follow the Avatar's hair, skin, eye or outfit color in five tones, or be fixed. Saved parts go into a Part Library in your Profile and can be worn by any PersonaBot. The worn copy turns and speaks with the Window Companion and travels with an exported Bot, and editing a library part saves a new part without changing Avatars that already wear the old one ([#1211](https://github.com/BotHarness/DeepSeekBot/issues/1211)). - Pixel Avatars can be an elf, dwarf, orc or talking flower. Beards always leave the speaking mouth visible. Armor, robe, tunic and cloak outfits are available, and a helmet or hood hides the hair underneath. Flowers have bead eyes, five petal styles and a stem or pot. Choices a species or headwear doesn't show stay saved, with a note, and return when switched back ([#1212](https://github.com/BotHarness/DeepSeekBot/issues/1212), [#1213](https://github.com/BotHarness/DeepSeekBot/issues/1213)). - A new PersonaBot starts with a random face from every species, part and outfit, based on its name. Existing PersonaBots keep their current face ([#1214](https://github.com/BotHarness/DeepSeekBot/issues/1214)). diff --git a/CHANGELOG.zh.md b/CHANGELOG.zh.md index b0df14d313..ff623abd12 100644 --- a/CHANGELOG.zh.md +++ b/CHANGELOG.zh.md @@ -5,10 +5,15 @@ ## [Unreleased] -像素头像新增精灵、矮人、兽人和会说话的花,以及胡子、中世纪服装和头饰;新建的 PersonaBot 会从全部物种中随机生成初始形象。 +像素头像新增精灵、矮人、兽人和会说话的花,以及胡子、中世纪服装和头饰;可以自己画头饰并存入部件库;新建的 PersonaBot 会从全部物种中随机生成初始形象。 + +### Breaking Changes + +- 部件库新增 Profile schema Generation 73。升级前请备份;升级后的 Profile 需要兼容的程序版本才能重新打开,否则请恢复升级前的备份([#1211](https://github.com/BotHarness/DeepSeekBot/issues/1211))。 ### Added +- 可以为像素头像自己画头饰:铅笔、橡皮、填充、沿脸部中线镜像,前层盖在头发上、后层在头发后面,支持撤销重做,并在真实头像上显示 1× 预览。颜色可以跟随头像的发色、肤色、眼睛或衣服颜色(五档明暗),也可以是固定色。保存的部件进入 Profile 里的部件库,任何 PersonaBot 都能戴上;戴上的副本会在窗口伙伴里随头部转动和说话,并随导出的 Bot 一起带走;修改库里的部件会另存为新部件,不会改变已经戴着旧部件的头像([#1211](https://github.com/BotHarness/DeepSeekBot/issues/1211))。 - 像素头像新增精灵、矮人、兽人和会说话的花。胡子始终露出说话的嘴,新增盔甲、法袍、束腰外衣和斗篷,戴上头盔或兜帽会遮住下面的头发。花有豆豆眼、五种花瓣样式,以及茎叶或花盆。当前物种或头饰不显示的选择会保留并给出提示,换回后恢复([#1212](https://github.com/BotHarness/DeepSeekBot/issues/1212)、[#1213](https://github.com/BotHarness/DeepSeekBot/issues/1213))。 - 新建的 PersonaBot 会按名字从全部物种、部件和服装中随机生成初始形象,已有的 PersonaBot 保持原来的样子([#1214](https://github.com/BotHarness/DeepSeekBot/issues/1214))。 diff --git a/docs/architecture/botharness-architecture.en.md b/docs/architecture/botharness-architecture.en.md index a39fdb7d79..b80f0d9693 100644 --- a/docs/architecture/botharness-architecture.en.md +++ b/docs/architecture/botharness-architecture.en.md @@ -400,7 +400,7 @@ First selection and Client/Host restart establish a Host-consistent future-messa Each Bot has one updating Activity card and parallel typewriter message cards, with defaults of 3 collapsed layers and at most 20 unexpired retained cards, adjustable through shared settings. Hover/focus expands a stable list, pauses roaming/expiry, continues visible typing and counts new arrivals until leaving; previews, scrolling and basic bubble avoidance preserve reading. No automatic +N fold or companion selection cap is imposed; Humans drag, pause walking or remove companions. Archive retains a static marked companion; deletion removes selection. Existing motion, freshness, static-image and missing-version fallback contracts apply. First validate one real Host→Client pixel companion Activity/DM interaction/recovery slice with Human feedback, then extend multiple Bots, groups and all visibility modes. A compatible text-paced closed/half-open/open BotPixel mouth follows separately. Independent desktop windows, fork distribution and full-body animation stay outside this target. -### 5.4 · Avatar Species and Custom Parts (accepted design, not yet implemented) +### 5.4 · Avatar Species and Custom Parts (partly implemented) [ADR-0148](../adr/0148-avatar-species-and-custom-parts-extend-one-pixel-rig.md) extends the pixel Avatar Family without a new rig. An Avatar Species (human, elf, goblin, dwarf, orc, cat, dog, fox, rabbit, bear, flower) is a base on the pixel bust skeleton: silhouette, ears, nose or muzzle, suggested body colors and accepted parts; motion, anchors, the speech mouth and the transparent companion silhouette stay shared. Hair splits into separately colored pieces and a through-hair headpiece slot adds front and back layers. Choices a species cannot show stay saved and hidden instead of being replaced. @@ -408,6 +408,8 @@ Custom Parts are bounded pixel grids whose cells reference appearance colors or New PersonaBots record a full-domain name-seed version; PersonaBots without it keep the human-only seed. Recipes using species, new slots or Custom Parts raise the asset/schema version and fall back to the saved snapshot on older Clients; existing recipes render unchanged. The first slice proves goblin, split side hair and one drawn headpiece from editor to Part Library to a Window Companion and through export/import. +Implemented so far: goblin, elf, dwarf, orc and flower species, split side hair, beards, medieval outfits and headwear, the full-domain seed (#1210, #1212–#1214), and the first Custom Part path (#1211). A drawn headpiece is an asset version 3 recipe. The Part Library is the `avatar-part-library` module's `avatar_part_library` table (schema generation 73), keyed by the part's content hash and holding name, origins and parent. The `partLibraryList` and `partLibraryAdd` bridge methods expose it to the Client editor (pencil, eraser, 4-connected fill, centerline mirror, front and back layers, undo and redo, and a 1× preview). The appearance embeds a copy of the part, so it travels in `.botharness/bot.json` and Bot Zips. Animal species, imported parts, PNG part files and further drawing tools are still to come. + ## 6 · Persistence, export, and restore boundaries ```mermaid diff --git a/docs/architecture/botharness-architecture.md b/docs/architecture/botharness-architecture.md index 9c28fd242b..aedce1a1cc 100644 --- a/docs/architecture/botharness-architecture.md +++ b/docs/architecture/botharness-architecture.md @@ -506,7 +506,7 @@ Tool detail Capability 默认拒绝所有 Consumer。部署 Human 在 `botharnes 每 Bot 一张当前活动卡加独立并行逐字消息卡,默认折叠 3 层、最多保留 20 张未到期卡;全局设置可调整。hover/focus 展开稳定列表,暂停漫游与到期,已显示文字继续播放,新增内容只计数、退出后有界合并;长文预览、列表滚动,基本气泡避让。无自动 +N 折叠或钉选数量上限,Human 通过拖动、暂停漫游、移除调整。归档保留静态伙伴与标记、删除清选择;reduced motion、freshness、上传图片静态 media 和版本快照降级沿既有 Avatar 合同。先完成真实 Host→Client 的一个像素伙伴 Activity/DM 与操作/恢复切片,Human 验证后扩展多个 Bot、群聊与三档范围;闭合/半开/张开文字节奏嘴型作为随后 BotPixel 兼容扩展。独立桌面窗口、fork 分发与全身动作不属于此目标。 -### 5.4 · 形象物种与自绘部件(已接受设计,待实现) +### 5.4 · 形象物种与自绘部件(部分已实现) [ADR-0148](../adr/0148-avatar-species-and-custom-parts-extend-one-pixel-rig.md) 在不新增 rig 的前提下扩展像素 Avatar Family。Avatar Species(人类、精灵、哥布林、矮人、兽人、猫、狗、狐狸、兔子、熊、花)是像素胸像骨架上的基底:轮廓、耳朵、鼻子或吻部、建议身体色与可接受部件;动作、锚点、说话嘴型与伙伴透明轮廓保持共享。头发拆为可分别上色的分片,新增穿过头发的头饰槽(前后两层)。当前物种无法显示的选择保存并隐藏,不被替换。 @@ -514,6 +514,8 @@ Custom Part 是有界像素网格,每格引用外形颜色或固定色并带 新 PersonaBot 记录全域名字种子版本;没有该记录的 PersonaBot 保持仅人类的种子。使用物种、新槽位或 Custom Part 的 recipe 提升 asset/schema 版本,旧 Client 显示保存的快照;既有 recipe 渲染不变。首个切片验证哥布林、左右侧发分片与一个自绘头饰,从编辑器到 Part Library、再到 Window Companion,并经过导出/导入。 +目前已实现:哥布林、精灵、矮人、兽人和花物种,左右侧发分片,胡子,中世纪服装与头饰,全域种子(#1210、#1212–#1214),以及第一条 Custom Part 路径(#1211)。自绘头饰的 recipe 是 asset version 3。Part Library 是 `avatar-part-library` 模块的 `avatar_part_library` 表(schema generation 73),以部件内容哈希为键,并保存名称、来源和父部件。Client 编辑器通过 `partLibraryList` 和 `partLibraryAdd` 两个桥接方法使用它;编辑器提供铅笔、橡皮、四连通填充、中线镜像、前后两层、撤销重做和 1× 预览。外形嵌入部件副本,因此部件会随 `.botharness/bot.json` 和 Bot Zip 一起带走。动物物种、导入部件、PNG 部件文件和更多绘制工具尚未实现。 + ## 6 · 持久化、导出与恢复边界 ```mermaid diff --git a/docs/architecture/diagrams/02-modules.mmd b/docs/architecture/diagrams/02-modules.mmd index b44cdd3dd5..b84230fed0 100644 --- a/docs/architecture/diagrams/02-modules.mmd +++ b/docs/architecture/diagrams/02-modules.mmd @@ -4,6 +4,7 @@ flowchart TB subgraph Modules["BotHarness deep modules"] Bots["PersonaBot
identity · lifecycle · Session ownership"] + PartLibrary["Avatar Part Library
content-hash parts · origins · parent"] Memory["Optional Memory Service
repositories · Git commits · events"] Msg["Messaging
events · channels · inbox · triggers
grants · outbox"] Assignments["Assignments
directory · capacity · requests · reports"] @@ -13,12 +14,14 @@ flowchart TB Root --> DB Root --> Bots + Root --> PartLibrary Root -. optional Provider .-> Memory Root --> Msg Root --> Assignments Root --> Portable Root --> Views DB --> Bots + DB --> PartLibrary DB --> Msg DB --> Assignments DB --> Portable @@ -26,6 +29,7 @@ flowchart TB Bots --> Assignments Msg --> Assignments Bots --> Views + PartLibrary --> Views Msg --> Views Assignments -. scoped Consumer .-> Memory Memory --> Views diff --git a/docs/architecture/diagrams/en/02-modules.mmd b/docs/architecture/diagrams/en/02-modules.mmd index b44cdd3dd5..b84230fed0 100644 --- a/docs/architecture/diagrams/en/02-modules.mmd +++ b/docs/architecture/diagrams/en/02-modules.mmd @@ -4,6 +4,7 @@ flowchart TB subgraph Modules["BotHarness deep modules"] Bots["PersonaBot
identity · lifecycle · Session ownership"] + PartLibrary["Avatar Part Library
content-hash parts · origins · parent"] Memory["Optional Memory Service
repositories · Git commits · events"] Msg["Messaging
events · channels · inbox · triggers
grants · outbox"] Assignments["Assignments
directory · capacity · requests · reports"] @@ -13,12 +14,14 @@ flowchart TB Root --> DB Root --> Bots + Root --> PartLibrary Root -. optional Provider .-> Memory Root --> Msg Root --> Assignments Root --> Portable Root --> Views DB --> Bots + DB --> PartLibrary DB --> Msg DB --> Assignments DB --> Portable @@ -26,6 +29,7 @@ flowchart TB Bots --> Assignments Msg --> Assignments Bots --> Views + PartLibrary --> Views Msg --> Views Assignments -. scoped Consumer .-> Memory Memory --> Views diff --git a/docs/architecture/diagrams/rendered/02-modules.dark.svg b/docs/architecture/diagrams/rendered/02-modules.dark.svg index fb97b5a899..b4cb1de4d8 100644 --- a/docs/architecture/diagrams/rendered/02-modules.dark.svg +++ b/docs/architecture/diagrams/rendered/02-modules.dark.svg @@ -1 +1 @@ -

BotHarness deep modules

optional Provider

attachment

scoped Consumer

Host composition root
lifecycle · dependency wiring

Operational Database Owner
writer lease · schema generation · transaction

PersonaBot
identity · lifecycle · Session ownership

Optional Memory Service
repositories · Git commits · events

Messaging
events · channels · inbox · triggers
grants · outbox

Assignments
directory · capacity · requests · reports

Portability
Soul · export · backup · restore

Read models
RPC · UI projections

\ No newline at end of file +

BotHarness deep modules

optional Provider

attachment

scoped Consumer

Host composition root
lifecycle · dependency wiring

Operational Database Owner
writer lease · schema generation · transaction

PersonaBot
identity · lifecycle · Session ownership

Avatar Part Library
content-hash parts · origins · parent

Optional Memory Service
repositories · Git commits · events

Messaging
events · channels · inbox · triggers
grants · outbox

Assignments
directory · capacity · requests · reports

Portability
Soul · export · backup · restore

Read models
RPC · UI projections

\ No newline at end of file diff --git a/docs/architecture/diagrams/rendered/02-modules.svg b/docs/architecture/diagrams/rendered/02-modules.svg index 348e637611..77cec80db2 100644 --- a/docs/architecture/diagrams/rendered/02-modules.svg +++ b/docs/architecture/diagrams/rendered/02-modules.svg @@ -1 +1 @@ -

BotHarness deep modules

optional Provider

attachment

scoped Consumer

Host composition root
lifecycle · dependency wiring

Operational Database Owner
writer lease · schema generation · transaction

PersonaBot
identity · lifecycle · Session ownership

Optional Memory Service
repositories · Git commits · events

Messaging
events · channels · inbox · triggers
grants · outbox

Assignments
directory · capacity · requests · reports

Portability
Soul · export · backup · restore

Read models
RPC · UI projections

\ No newline at end of file +

BotHarness deep modules

optional Provider

attachment

scoped Consumer

Host composition root
lifecycle · dependency wiring

Operational Database Owner
writer lease · schema generation · transaction

PersonaBot
identity · lifecycle · Session ownership

Avatar Part Library
content-hash parts · origins · parent

Optional Memory Service
repositories · Git commits · events

Messaging
events · channels · inbox · triggers
grants · outbox

Assignments
directory · capacity · requests · reports

Portability
Soul · export · backup · restore

Read models
RPC · UI projections

\ No newline at end of file diff --git a/docs/architecture/diagrams/rendered/en/02-modules.dark.svg b/docs/architecture/diagrams/rendered/en/02-modules.dark.svg index fb97b5a899..b4cb1de4d8 100644 --- a/docs/architecture/diagrams/rendered/en/02-modules.dark.svg +++ b/docs/architecture/diagrams/rendered/en/02-modules.dark.svg @@ -1 +1 @@ -

BotHarness deep modules

optional Provider

attachment

scoped Consumer

Host composition root
lifecycle · dependency wiring

Operational Database Owner
writer lease · schema generation · transaction

PersonaBot
identity · lifecycle · Session ownership

Optional Memory Service
repositories · Git commits · events

Messaging
events · channels · inbox · triggers
grants · outbox

Assignments
directory · capacity · requests · reports

Portability
Soul · export · backup · restore

Read models
RPC · UI projections

\ No newline at end of file +

BotHarness deep modules

optional Provider

attachment

scoped Consumer

Host composition root
lifecycle · dependency wiring

Operational Database Owner
writer lease · schema generation · transaction

PersonaBot
identity · lifecycle · Session ownership

Avatar Part Library
content-hash parts · origins · parent

Optional Memory Service
repositories · Git commits · events

Messaging
events · channels · inbox · triggers
grants · outbox

Assignments
directory · capacity · requests · reports

Portability
Soul · export · backup · restore

Read models
RPC · UI projections

\ No newline at end of file diff --git a/docs/architecture/diagrams/rendered/en/02-modules.svg b/docs/architecture/diagrams/rendered/en/02-modules.svg index 348e637611..77cec80db2 100644 --- a/docs/architecture/diagrams/rendered/en/02-modules.svg +++ b/docs/architecture/diagrams/rendered/en/02-modules.svg @@ -1 +1 @@ -

BotHarness deep modules

optional Provider

attachment

scoped Consumer

Host composition root
lifecycle · dependency wiring

Operational Database Owner
writer lease · schema generation · transaction

PersonaBot
identity · lifecycle · Session ownership

Optional Memory Service
repositories · Git commits · events

Messaging
events · channels · inbox · triggers
grants · outbox

Assignments
directory · capacity · requests · reports

Portability
Soul · export · backup · restore

Read models
RPC · UI projections

\ No newline at end of file +

BotHarness deep modules

optional Provider

attachment

scoped Consumer

Host composition root
lifecycle · dependency wiring

Operational Database Owner
writer lease · schema generation · transaction

PersonaBot
identity · lifecycle · Session ownership

Avatar Part Library
content-hash parts · origins · parent

Optional Memory Service
repositories · Git commits · events

Messaging
events · channels · inbox · triggers
grants · outbox

Assignments
directory · capacity · requests · reports

Portability
Soul · export · backup · restore

Read models
RPC · UI projections

\ No newline at end of file diff --git a/docs/assets/pr/1211-custom-parts/README.md b/docs/assets/pr/1211-custom-parts/README.md new file mode 100644 index 0000000000..0b05f13487 --- /dev/null +++ b/docs/assets/pr/1211-custom-parts/README.md @@ -0,0 +1,29 @@ +# #1211 Custom Parts 1: draw a headpiece into the Part Library and wear it + +Captured on an isolated DSH instance built from this branch, with `@botharness/pixel-avatar` 0.5.0 (BotHarness/BotPixel#11) built in. + +## Drawing + +| Front layer: a mirrored gold crown with a gem, drawn with pencil, tones and mirror | Back layer: hair-colored side pieces behind the hair, seen through the dimmed Avatar | +| ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | +| ![front layer](part-front-en-light.webp) | ![back layer](part-back-en-light.webp) | + +## Library and color + +| Saved to the Part Library and worn | Changing the hair color recolors the hair-colored back pieces | +| ---------------------------------- | ------------------------------------------------------------- | +| ![saved](part-saved-en-light.webp) | ![recolor](part-recolor-en-light.webp) | + +## Window Companion + +The speech is simulated. A test script drives the companion's own closed, half-open and open mouth layers; no model reply was involved. + +| Speaking companion wearing the drawn part | Close-up (×4, cropped from the screenshot) | +| ----------------------------------------- | -------------------------------------------- | +| ![speaking](part-speaking-en-light.webp) | ![close-up](companion-closeup-en-light.webp) | + +## Full flow + +![full flow](custom-part-flow.gif) + +The same recording as video: [custom-part-flow.mp4](custom-part-flow.mp4) diff --git a/docs/assets/pr/1211-custom-parts/companion-closeup-en-light.webp b/docs/assets/pr/1211-custom-parts/companion-closeup-en-light.webp new file mode 100644 index 0000000000..e5059cad29 Binary files /dev/null and b/docs/assets/pr/1211-custom-parts/companion-closeup-en-light.webp differ diff --git a/docs/assets/pr/1211-custom-parts/custom-part-flow.gif b/docs/assets/pr/1211-custom-parts/custom-part-flow.gif new file mode 100644 index 0000000000..59b1c902aa Binary files /dev/null and b/docs/assets/pr/1211-custom-parts/custom-part-flow.gif differ diff --git a/docs/assets/pr/1211-custom-parts/custom-part-flow.mp4 b/docs/assets/pr/1211-custom-parts/custom-part-flow.mp4 new file mode 100644 index 0000000000..88e6f60449 Binary files /dev/null and b/docs/assets/pr/1211-custom-parts/custom-part-flow.mp4 differ diff --git a/docs/assets/pr/1211-custom-parts/part-back-en-light.webp b/docs/assets/pr/1211-custom-parts/part-back-en-light.webp new file mode 100644 index 0000000000..57eb9c70bb Binary files /dev/null and b/docs/assets/pr/1211-custom-parts/part-back-en-light.webp differ diff --git a/docs/assets/pr/1211-custom-parts/part-front-en-light.webp b/docs/assets/pr/1211-custom-parts/part-front-en-light.webp new file mode 100644 index 0000000000..b64ae05516 Binary files /dev/null and b/docs/assets/pr/1211-custom-parts/part-front-en-light.webp differ diff --git a/docs/assets/pr/1211-custom-parts/part-recolor-en-light.webp b/docs/assets/pr/1211-custom-parts/part-recolor-en-light.webp new file mode 100644 index 0000000000..dbee9c07c9 Binary files /dev/null and b/docs/assets/pr/1211-custom-parts/part-recolor-en-light.webp differ diff --git a/docs/assets/pr/1211-custom-parts/part-saved-en-light.webp b/docs/assets/pr/1211-custom-parts/part-saved-en-light.webp new file mode 100644 index 0000000000..97386d0518 Binary files /dev/null and b/docs/assets/pr/1211-custom-parts/part-saved-en-light.webp differ diff --git a/docs/assets/pr/1211-custom-parts/part-speaking-en-light.webp b/docs/assets/pr/1211-custom-parts/part-speaking-en-light.webp new file mode 100644 index 0000000000..bff60c5d9f Binary files /dev/null and b/docs/assets/pr/1211-custom-parts/part-speaking-en-light.webp differ diff --git a/packages/client/src/client/actions.ts b/packages/client/src/client/actions.ts index d0177802cf..9c31449e66 100644 --- a/packages/client/src/client/actions.ts +++ b/packages/client/src/client/actions.ts @@ -94,6 +94,8 @@ import { setBotBanner as setBotBannerViaBridge, updateBotProfile as updateBotProfileViaBridge, setBotAppearance as setBotAppearanceViaBridge, + loadPartLibrary as loadPartLibraryViaBridge, + addLibraryPart as addLibraryPartViaBridge, cancelGroupInvitation, decideGroupJoin, removeGroupMember, @@ -582,6 +584,14 @@ export interface BridgeActions { channelId: string, recipe: import('../../../core/src/bots/avatar-appearance.js').AvatarRecipe, ): Promise; + loadPartLibrary(): Promise< + import('../../../core/src/bots/part-library.js').PartLibraryEntry[] | undefined + >; + addLibraryPart( + part: import('../../../core/src/bots/avatar-appearance.js').PixelCustomPart, + name: string, + parent?: string, + ): Promise; inviteGroupBot(channelId: string, botSlug: string): Promise; cancelGroupInvitation(channelId: string, invitationId: string): Promise; decideGroupJoin(channelId: string, requestId: string, accept: boolean): Promise; @@ -2255,6 +2265,20 @@ export function createActions( return false; } }, + async loadPartLibrary() { + try { + return await loadPartLibraryViaBridge(call); + } catch { + return undefined; + } + }, + async addLibraryPart(part, name, parent) { + try { + return await addLibraryPartViaBridge(call, part, name, parent); + } catch { + return undefined; + } + }, async updateBotProfile(slug, patch) { try { const bot = await updateBotProfileViaBridge(call, slug, patch); diff --git a/packages/client/src/client/avatar-appearance-editor.tsx b/packages/client/src/client/avatar-appearance-editor.tsx index 795d7f9587..306b2e8a80 100644 --- a/packages/client/src/client/avatar-appearance-editor.tsx +++ b/packages/client/src/client/avatar-appearance-editor.tsx @@ -16,6 +16,9 @@ import { type IllustratedAvatarRecipe, AVATAR_SWATCHES, withAvatarSpecies, + withAvatarHeadpiece, + customPartId, + type PixelCustomPart, avatarSvg, seededAvatarFor, type AvatarFamily, @@ -31,6 +34,8 @@ import { } from '../../../core/src/bots/avatar-line.js'; import { Tag } from '@deepseek-ai/dsh-client-ui-primitives'; +import type { PartLibraryEntry } from '../../../core/src/bots/part-library.js'; +import { CustomPartEditor } from './custom-part-editor.js'; import { PersonaBotAvatar, PersonaBotStatusBadges, normalizePersonaBotActivity } from './avatar.js'; import { SidebarCardList, SidebarCardRow } from './sidebar-card.js'; import type { BotSummary } from './store.js'; @@ -80,6 +85,7 @@ const FAMILIES: Record = { 'flowerBase', ...Object.keys(AVATAR_PARTS).filter((part) => part !== 'backdrop' && part !== 'hair'), 'beard', + 'headpiece', 'shape', 'colors', ], @@ -184,14 +190,29 @@ function shuffled(recipe: AvatarRecipe): AvatarRecipe { } as IllustratedAvatarRecipe; } -function categoriesFor(spec: FamilySpec, recipe: AvatarRecipe | undefined): readonly string[] { +function categoriesFor( + spec: FamilySpec, + recipe: AvatarRecipe | undefined, + library = true, +): readonly string[] { if (recipe?.family !== 'illustrated') return spec.categories; const flower = recipe.species === 'flower'; return spec.categories.filter((key) => - key === 'petals' || key === 'flowerBase' ? flower : key === 'beard' ? !flower : true, + key === 'petals' || key === 'flowerBase' + ? flower + : key === 'beard' + ? !flower + : key === 'headpiece' + ? library + : true, ); } +export interface PartLibraryActions { + load(): Promise; + add(part: PixelCustomPart, name: string, parent?: string): Promise; +} + function hiddenFor(recipe: AvatarRecipe | undefined, category: string): boolean { if (recipe?.family !== 'illustrated') return false; const hidden = hiddenAvatarChoices(recipe); @@ -241,6 +262,7 @@ export function AvatarAppearanceEditor({ onUpload, onRemoveImage, imageBusy = false, + library, t, }: { bot: BotSummary; @@ -249,8 +271,15 @@ export function AvatarAppearanceEditor({ onUpload?: (() => void) | undefined; onRemoveImage?: (() => void) | undefined; imageBusy?: boolean | undefined; + library?: PartLibraryActions | undefined; t: BotHarnessTranslate; }): ReactElement { + const [parts, setParts] = useState(); + const [drawing, setDrawing] = useState<{ + base: IllustratedAvatarRecipe; + initial?: PixelCustomPart; + parent?: string; + }>(); const [drafts, setDrafts] = useState>>(); const [family, setFamily] = useState('illustrated'); const [category, setCategory] = useState('hair'); @@ -261,6 +290,7 @@ export function AvatarAppearanceEditor({ const seed = bot.displayName || bot.slug; const start = () => { const saved = bot.appearance?.recipe ?? seededAvatarFor(seed, bot.avatarSeed); + setDrawing(undefined); setDrafts({ [saved.family]: { ...saved } }); setFamily(saved.family); setCategory(saved.family === 'line' ? 'eyes' : 'hair'); @@ -417,7 +447,7 @@ export function AvatarAppearanceEditor({
- {categoriesFor(spec, draft).map((key) => ( + {categoriesFor(spec, draft, library !== undefined).map((key) => (
))}
+ ) : category === 'headpiece' && draft.family === 'illustrated' ? ( +
+ {drawing ? ( + update(withAvatarHeadpiece(drawing.base, part))} + onSave={async (part, name) => { + const entry = await library?.add(part, name, drawing.parent); + if (!entry) return false; + setParts((current) => [ + entry, + ...(current ?? []).filter((item) => item.id !== entry.id), + ]); + update(withAvatarHeadpiece(drawing.base, entry.part)); + setDrawing(undefined); + return true; + }} + onCancel={() => { + update(drawing.base); + setDrawing(undefined); + }} + t={t} + /> + ) : ( + <> +
+ + {draft.assetVersion === 3 ? ( + + ) : null} +
+ update(withAvatarHeadpiece(draft, undefined))} + /> + {(parts ?? []).map((entry) => ( + + t( + `profile.avatar.part.origin.${origin === 'imported-bot' ? 'importedBot' : origin === 'imported-file' ? 'importedFile' : 'drawn'}`, + ), + ) + .join(', ')}`} + onSelect={() => update(withAvatarHeadpiece(draft, entry.part))} + /> + ))} + {parts !== undefined && parts.length === 0 ? ( +

+ {t('profile.avatar.part.libraryEmpty')} +

+ ) : null} + + )} +
) : category === 'presets' ? (
void save()} > {t('profile.save')} @@ -585,6 +711,7 @@ export function AvatarAppearanceEditor({ disabled={busy} onClick={() => { setDrafts(undefined); + setDrawing(undefined); setFailed(false); }} > diff --git a/packages/client/src/client/bridge.ts b/packages/client/src/client/bridge.ts index 6891bd225d..ea6b3810b2 100644 --- a/packages/client/src/client/bridge.ts +++ b/packages/client/src/client/bridge.ts @@ -51,6 +51,8 @@ import type { UsageOverviewPeriod } from '../../../core/src/usage/overview.js'; import type { ChannelActivityToday } from '../../../core/src/channels/activity-today.js'; import type { GroupReceptionInput } from '../../../core/src/messaging/group-policy.js'; import type { MessagingConversationInput } from '../../../core/src/messaging/conversations.js'; +import { isPartLibraryEntry, type PartLibraryEntry } from '../../../core/src/bots/part-library.js'; +import type { PixelCustomPart } from '../../../core/src/bots/avatar-appearance.js'; import type { ActivityOverview } from '../../../core/src/bridge/methods.js'; import type { ExternalSource } from '../../../core/src/messaging/inbound.js'; import type { @@ -1954,6 +1956,25 @@ export async function setBotAppearance( return bot; } +export async function loadPartLibrary(call: BridgeCall): Promise { + const parts = asRecord(await unwrap(call, 'partLibraryList', {}))?.['parts']; + if (!Array.isArray(parts)) throw new Error('invalid partLibraryList response'); + return parts.filter(isPartLibraryEntry); +} + +export async function addLibraryPart( + call: BridgeCall, + part: PixelCustomPart, + name: string, + parent?: string, +): Promise { + const entry = asRecord( + await unwrap(call, 'partLibraryAdd', { part, name, ...(parent ? { parent } : {}) }), + )?.['entry']; + if (!isPartLibraryEntry(entry)) throw new Error('invalid partLibraryAdd response'); + return entry; +} + export async function inviteGroupBot( call: BridgeCall, channelId: string, diff --git a/packages/client/src/client/custom-part-editor.tsx b/packages/client/src/client/custom-part-editor.tsx new file mode 100644 index 0000000000..19b531e3c9 --- /dev/null +++ b/packages/client/src/client/custom-part-editor.tsx @@ -0,0 +1,310 @@ +import { useMemo, useRef, useState, type ReactElement } from 'react'; +import { + AVATAR_COLORS, + PART_SLOTS, + PART_TONES, + avatarSvg, + createCustomPart, + emptyPartLayer, + fillPartLayer, + paintPartLayer, + partLayer, + partToneColor, + withAvatarHeadpiece, + type IllustratedAvatarRecipe, + type PartColor, + type PartInk, + type PartLayer, + type PartLayerName, + type PixelCustomPart, +} from '../../../core/src/bots/avatar-appearance.js'; +import type { BotHarnessTranslate } from './locale.js'; + +type Key = Parameters[0]; +type Tool = 'pencil' | 'eraser' | 'fill'; +type Layers = Record; + +const SLOT = 'headpiece'; +const { width: W, height: H } = PART_SLOTS[SLOT]; +const FIXED_COLORS: readonly PartColor[] = [ + '#efb93f', + '#f4f1ec', + '#1d1b22', + '#e2565f', + '#f06292', + '#5a7be0', + '#3d9970', + '#8a5ad0', +]; +const TOOLS: readonly Tool[] = ['pencil', 'eraser', 'fill']; +const MIN_ZOOM = 6; +const MAX_ZOOM = 16; + +function inkColor(recipe: IllustratedAvatarRecipe, ink: PartInk): string { + const base = ink.color.startsWith('#') ? ink.color : recipe[ink.color as 'hairColor']; + return partToneColor(base, ink.tone); +} + +export function CustomPartEditor({ + recipe, + initial, + onChange, + onSave, + onCancel, + t, +}: { + recipe: IllustratedAvatarRecipe; + initial?: PixelCustomPart | undefined; + onChange(part: PixelCustomPart): void; + onSave(part: PixelCustomPart, name: string): Promise; + onCancel(): void; + t: BotHarnessTranslate; +}): ReactElement { + const [layers, setLayers] = useState(() => ({ + front: initial ? partLayer(SLOT, initial.front) : emptyPartLayer(SLOT), + back: initial ? partLayer(SLOT, initial.back) : emptyPartLayer(SLOT), + })); + const [past, setPast] = useState([]); + const [future, setFuture] = useState([]); + const [layer, setLayer] = useState('front'); + const [tool, setTool] = useState('pencil'); + const [mirror, setMirror] = useState(true); + const [ink, setInk] = useState({ color: 'hairColor', tone: 0 }); + const [zoom, setZoom] = useState(10); + const [name, setName] = useState(''); + const [busy, setBusy] = useState(false); + const [failed, setFailed] = useState(false); + const drawing = useRef(undefined); + const bare = useMemo(() => withAvatarHeadpiece(recipe, undefined), [recipe]); + const part = useMemo(() => createCustomPart(SLOT, layers), [layers]); + const wearing = useMemo(() => withAvatarHeadpiece(recipe, part), [recipe, part]); + const backdrop = useMemo(() => avatarSvg(bare), [bare]); + const preview = useMemo(() => avatarSvg(wearing), [wearing]); + const empty = part.front.length === 0 && part.back.length === 0; + + const commit = (next: Layers) => { + setLayers(next); + onChange(createCustomPart(SLOT, next)); + }; + const applyAt = (base: Layers, x: number, y: number): Layers => { + const value = tool === 'eraser' ? null : ink; + const target = + tool === 'fill' + ? fillPartLayer(SLOT, base[layer], x, y, value, mirror) + : paintPartLayer(SLOT, base[layer], [[x, y]], value, mirror); + return { ...base, [layer]: target }; + }; + const start = (x: number, y: number) => { + setPast((stack) => [...stack, layers]); + setFuture([]); + const next = applyAt(layers, x, y); + drawing.current = tool === 'fill' ? undefined : next; + commit(next); + }; + const extend = (x: number, y: number) => { + if (!drawing.current) return; + const next = applyAt(drawing.current, x, y); + drawing.current = next; + commit(next); + }; + const stop = () => { + drawing.current = undefined; + }; + const undo = () => { + const previous = past.at(-1); + if (!previous) return; + setPast(past.slice(0, -1)); + setFuture([layers, ...future]); + commit(previous); + }; + const redo = () => { + const [next, ...rest] = future; + if (!next) return; + setFuture(rest); + setPast([...past, layers]); + commit(next); + }; + const save = async () => { + if (empty || busy) return; + setBusy(true); + const saved = await onSave(part, name.trim()); + setBusy(false); + setFailed(!saved); + }; + + const cells: ReactElement[] = []; + for (let y = 0; y < H; y++) + for (let x = 0; x < W; x++) { + const own = layers[layer][y]![x]; + const other = layers[layer === 'front' ? 'back' : 'front'][y]![x]; + const shown = own ?? other; + cells.push( + { + event.preventDefault(); + start(x, y); + }} + onPointerEnter={() => extend(x, y)} + />, + ); + } + + const rows: { key: string; label: string; color: PartColor }[] = [ + ...AVATAR_COLORS.map((color) => ({ + key: color, + label: t(`profile.avatar.${color}` as Key), + color: color as PartColor, + })), + ...FIXED_COLORS.map((color) => ({ key: color, label: color, color })), + ]; + + return ( +
+
+ {TOOLS.map((value) => ( + + ))} + +
+
+
+
+
+
+
+
+ {rows.map((row) => ( +
+ {PART_TONES.map((tone) => { + const value = { color: row.color, tone }; + return ( +
+ ))} +
+
+
+ + {failed ?

{t('profile.avatar.part.saveFailed')}

: null} +
+ + +
+
+ ); +} diff --git a/packages/client/src/client/locale.ts b/packages/client/src/client/locale.ts index c8e239d6ab..b7b468b536 100644 --- a/packages/client/src/client/locale.ts +++ b/packages/client/src/client/locale.ts @@ -1729,6 +1729,33 @@ export const zh = { 'profile.avatar.option.accessory.helmet': '头盔', 'profile.avatar.option.accessory.hood': '兜帽', 'profile.avatar.hiddenNote': '当前物种或头饰不显示这项;选择会保留,换回后恢复。', + 'profile.avatar.headpiece': '自绘头饰', + 'profile.avatar.part.none': '不戴', + 'profile.avatar.part.draw': '绘制新部件', + 'profile.avatar.part.edit': '在当前部件上修改', + 'profile.avatar.part.libraryEmpty': '部件库还是空的,画一个吧。', + 'profile.avatar.part.origin.drawn': '在这里绘制', + 'profile.avatar.part.origin.importedBot': '来自导入的 Bot', + 'profile.avatar.part.origin.importedFile': '来自导入的文件', + 'profile.avatar.part.tools': '绘制工具', + 'profile.avatar.part.tool.pencil': '铅笔', + 'profile.avatar.part.tool.eraser': '橡皮', + 'profile.avatar.part.tool.fill': '填充', + 'profile.avatar.part.mirror': '镜像', + 'profile.avatar.part.layer.front': '前层(盖住头发)', + 'profile.avatar.part.layer.back': '后层(在头发后面)', + 'profile.avatar.part.undo': '撤销', + 'profile.avatar.part.redo': '重做', + 'profile.avatar.part.zoomIn': '放大', + 'profile.avatar.part.zoomOut': '缩小', + 'profile.avatar.part.preview': '1× 实际大小', + 'profile.avatar.part.colors': '颜色与明暗', + 'profile.avatar.part.name': '名称', + 'profile.avatar.part.namePlaceholder': '例如:小皇冠', + 'profile.avatar.part.save': '保存到部件库并戴上', + 'profile.avatar.part.cancel': '取消绘制', + 'profile.avatar.part.saveFailed': '部件保存失败,请重试。', + 'profile.avatar.part.untitled': '未命名部件', 'profile.avatar.leftSideHairColor': '左侧发色', 'profile.avatar.rightSideHairColor': '右侧发色', 'profile.avatar.followHairColor': '跟随发色', @@ -4264,6 +4291,33 @@ My relationship with you, established lore and topics to avoid: [fill in]. 'profile.avatar.option.accessory.hood': 'Hood', 'profile.avatar.hiddenNote': 'Not shown with this species or headwear. Your choice is kept and returns when you switch back.', + 'profile.avatar.headpiece': 'Drawn headpiece', + 'profile.avatar.part.none': 'None', + 'profile.avatar.part.draw': 'Draw a new part', + 'profile.avatar.part.edit': 'Edit the worn part', + 'profile.avatar.part.libraryEmpty': 'Your Part Library is empty. Draw one!', + 'profile.avatar.part.origin.drawn': 'Drawn here', + 'profile.avatar.part.origin.importedBot': 'From an imported Bot', + 'profile.avatar.part.origin.importedFile': 'From an imported file', + 'profile.avatar.part.tools': 'Drawing tools', + 'profile.avatar.part.tool.pencil': 'Pencil', + 'profile.avatar.part.tool.eraser': 'Eraser', + 'profile.avatar.part.tool.fill': 'Fill', + 'profile.avatar.part.mirror': 'Mirror', + 'profile.avatar.part.layer.front': 'Front (over hair)', + 'profile.avatar.part.layer.back': 'Back (behind hair)', + 'profile.avatar.part.undo': 'Undo', + 'profile.avatar.part.redo': 'Redo', + 'profile.avatar.part.zoomIn': 'Zoom in', + 'profile.avatar.part.zoomOut': 'Zoom out', + 'profile.avatar.part.preview': '1× actual size', + 'profile.avatar.part.colors': 'Colors and tones', + 'profile.avatar.part.name': 'Name', + 'profile.avatar.part.namePlaceholder': 'e.g. Little crown', + 'profile.avatar.part.save': 'Save to library and wear', + 'profile.avatar.part.cancel': 'Stop drawing', + 'profile.avatar.part.saveFailed': "Couldn't save the part. Try again.", + 'profile.avatar.part.untitled': 'Untitled part', 'profile.avatar.leftSideHairColor': 'Left side hair color', 'profile.avatar.rightSideHairColor': 'Right side hair color', 'profile.avatar.followHairColor': 'Follow hair color', diff --git a/packages/client/src/client/profile-header.tsx b/packages/client/src/client/profile-header.tsx index 36398ce4de..f5f83f4733 100644 --- a/packages/client/src/client/profile-header.tsx +++ b/packages/client/src/client/profile-header.tsx @@ -189,7 +189,10 @@ function AvatarModal({ }: { bot: BotSummary; channel: ChannelSummary; - actions: Pick; + actions: Pick< + BridgeActions, + 'setBotAppearance' | 'setBotAvatar' | 'loadPartLibrary' | 'addLibraryPart' + >; t: BotHarnessTranslate; onClose(): void; }): ReactElement { @@ -216,6 +219,7 @@ function AvatarModal({ bot={bot} channelId={channel.id} onSave={actions.setBotAppearance} + library={{ load: actions.loadPartLibrary, add: actions.addLibraryPart }} onUpload={() => input.current?.click()} onRemoveImage={() => void removeImage()} imageBusy={busy} diff --git a/packages/client/src/client/styles.ts b/packages/client/src/client/styles.ts index fa0e82479a..f8b2b8458a 100644 --- a/packages/client/src/client/styles.ts +++ b/packages/client/src/client/styles.ts @@ -2424,6 +2424,28 @@ html[data-botharness-motion='full'] .bh-skeleton-line { .bh-avatar-option:hover { border-color: var(--dsw-alias-border-l2); } .bh-avatar-option[aria-pressed='true'] { border-color: var(--dsw-alias-label-primary); } .bh-avatar-hidden-note { grid-column: 1 / -1; margin: 0; color: var(--dsw-alias-label-secondary); font-size: 13px; } +.bh-part-editor { grid-column: 1 / -1; display: flex; flex-direction: column; gap: 10px; } +.bh-part-toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; } +.bh-part-toolbar > button:not(.bh-avatar-category) { min-height: 28px; padding: 0 10px; border: 1px solid var(--dsw-alias-border-l2); border-radius: 6px; background: transparent; color: var(--dsw-alias-label-primary); font: inherit; font-size: 13px; cursor: pointer; } +.bh-part-toolbar > button:disabled { opacity: 0.45; cursor: default; } +.bh-part-divider { width: 1px; height: 20px; background: var(--dsw-alias-border-l2); } +.bh-part-workspace { display: flex; flex-wrap: wrap; gap: 14px; align-items: flex-start; } +.bh-part-canvas { position: relative; flex: none; max-width: 100%; overflow: hidden; border-radius: 8px; touch-action: none; user-select: none; } +.bh-part-backdrop { position: absolute; inset: 0; opacity: 0.38; pointer-events: none; } +.bh-part-backdrop svg { display: block; width: 100%; height: 100%; image-rendering: pixelated; } +.bh-part-grid { position: absolute; inset: 0 0 auto 0; display: grid; outline: 2px dashed var(--dsw-alias-label-secondary); outline-offset: -1px; } +.bh-part-cell { box-shadow: inset 0 0 0 0.5px var(--dsw-alias-border-l2); cursor: crosshair; } +.bh-part-cell[data-part-other='true'] { opacity: 0.45; } +.bh-part-side { display: flex; flex-direction: column; gap: 10px; } +.bh-part-preview { display: flex; align-items: center; gap: 8px; color: var(--dsw-alias-label-secondary); font-size: 12px; } +.bh-part-preview svg { display: block; width: 32px; height: 32px; image-rendering: pixelated; } +.bh-part-palette { display: grid; grid-template-columns: repeat(2, auto); gap: 4px 10px; } +.bh-part-palette-row { display: flex; gap: 2px; } +.bh-part-swatch { width: 18px; height: 18px; padding: 0; border: 1px solid var(--dsw-alias-border-l2); border-radius: 3px; cursor: pointer; } +.bh-part-swatch[aria-pressed='true'] { outline: 2px solid var(--dsw-alias-label-primary); outline-offset: 1px; } +.bh-part-name { display: flex; align-items: center; gap: 8px; font-size: 13px; } +.bh-part-name input { flex: 1; min-height: 30px; padding: 0 8px; border: 1px solid var(--dsw-alias-border-l2); border-radius: 6px; background: var(--dsw-alias-bg-base); color: inherit; font: inherit; } +.bh-part-library-actions { grid-column: 1 / -1; display: flex; flex-wrap: wrap; gap: 6px; } .bh-avatar-color-reset { min-height: 26px; padding: 0 8px; border: 1px solid var(--dsw-alias-border-l2); border-radius: 6px; background: transparent; color: var(--dsw-alias-label-secondary); font: inherit; font-size: 12px; cursor: pointer; } .bh-avatar-colors { display: flex; flex-direction: column; gap: 10px; } .bh-avatar-color-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; font-size: 13px; } diff --git a/packages/client/test/avatar-appearance-editor.test.ts b/packages/client/test/avatar-appearance-editor.test.ts index 3a52c8be23..5ba26153fc 100644 --- a/packages/client/test/avatar-appearance-editor.test.ts +++ b/packages/client/test/avatar-appearance-editor.test.ts @@ -18,7 +18,11 @@ import { isIllustratedAvatarRecipe, seededAvatarRecipe, seededAvatarRecipeV2, + canonicalCustomPart, + customPartId, + type PixelCustomPart, } from '../../core/src/bots/avatar-appearance.js'; +import type { PartLibraryEntry } from '../../core/src/bots/part-library.js'; import { LINE_PARTS, LINE_PRESETS, seededLineRecipe } from '../../core/src/bots/avatar-line.js'; import { zhTranslate } from '../src/client/locale.js'; @@ -419,6 +423,179 @@ describe('Profile Avatar Appearance editing', () => { } }); + it('draws a mirrored headpiece, saves it to the Part Library and wears it', async () => { + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + const save = vi.fn(async () => true); + const add = vi.fn( + async (part: PixelCustomPart, name: string, parent?: string): Promise => ({ + id: customPartId(part), + part: canonicalCustomPart(part), + name, + origins: ['drawn'], + ...(parent ? { parent } : {}), + addedAt: '2026-10-08T00:00:00.000Z', + }), + ); + const load = vi.fn(async (): Promise => []); + const container = document.createElement('div'); + document.body.append(container); + const root = createRoot(container); + const bot = { + slug: 'ada', + displayName: 'Ada', + roles: [], + aggregateState: 'idle', + workspaces: [], + createdAt: '', + }; + const $ = (selector: string) => container.querySelector(selector); + const click = async (selector: string) => act(() => $(selector)!.click()); + const press = async (x: number, y: number) => + act(() => { + $(`[data-part-cell="${x},${y}"]`)!.dispatchEvent( + new Event('pointerdown', { bubbles: true, cancelable: true }), + ); + $('[data-part-canvas]')!.dispatchEvent(new Event('pointerup', { bubbles: true })); + }); + const ink = (x: number, y: number) => + $(`[data-part-cell="${x},${y}"]`)?.getAttribute('data-part-ink'); + try { + await act(() => + root.render( + createElement(AvatarAppearanceEditor, { + bot, + channelId: 'dm-ada', + onSave: save, + library: { load, add }, + t: zhTranslate, + }), + ), + ); + await click('[data-avatar-edit]'); + await click('[data-avatar-category="headpiece"]'); + expect(load).toHaveBeenCalledTimes(1); + expect($('[data-avatar-option="headpiece:none"]')?.getAttribute('aria-pressed')).toBe('true'); + await click('[data-part-draw]'); + expect($('[data-avatar-save]')?.hasAttribute('disabled')).toBe(true); + + await press(10, 2); + expect(ink(10, 2)).toBe('hairColor:0'); + expect(ink(21, 2)).toBe('hairColor:0'); + expect(ink(11, 2)).toBeNull(); + + for (let x = 0; x <= 15; x++) await press(x, 6); + expect(ink(31, 6)).toBe('hairColor:0'); + await click('[data-part-mirror]'); + await click('[data-part-tool="fill"]'); + await click('[data-part-ink="#efb93f:1"]'); + await press(6, 0); + expect(ink(6, 0)).toBe('#efb93f:1'); + expect(ink(6, 7)).toBeNull(); + expect(ink(25, 0)).toBe('#efb93f:1'); + await click('[data-part-undo]'); + expect(ink(6, 0)).toBeNull(); + await click('[data-part-redo]'); + expect(ink(6, 0)).toBe('#efb93f:1'); + await click('[data-part-undo]'); + + await click('[data-part-tool="pencil"]'); + await click('[data-part-layer="back"]'); + await press(15, 8); + expect(ink(15, 8)).toBe('#efb93f:1'); + await click('[data-part-layer="front"]'); + expect($('[data-part-cell="15,8"]')?.getAttribute('data-part-other')).toBe('true'); + expect($('[data-part-preview] svg')).not.toBeNull(); + + const name = $('[data-part-name]') as HTMLInputElement; + await act(() => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call( + name, + 'Gold band', + ); + name.dispatchEvent(new Event('input', { bubbles: true })); + }); + await click('[data-part-save]'); + expect(add).toHaveBeenCalledTimes(1); + const [part, saved, parent] = add.mock.calls[0]!; + expect(saved).toBe('Gold band'); + expect(parent).toBeUndefined(); + expect(part.back).toEqual([[15, 8, '#efb93f', 1]]); + expect(part.front.filter(([, y]) => y === 6)).toHaveLength(32); + expect(part.front).toContainEqual([10, 2, 'hairColor', 0]); + expect(part.front).toContainEqual([21, 2, 'hairColor', 0]); + expect(part.front.some(([x, y]) => x === 6 && y === 0)).toBe(false); + expect($('[data-part-editor]')).toBeNull(); + const id = customPartId(part); + expect($(`[data-avatar-option="headpiece:${id}"]`)?.getAttribute('aria-pressed')).toBe( + 'true', + ); + + await click('[data-part-edit]'); + await click('[data-part-tool="eraser"]'); + await press(10, 2); + await click('[data-part-save]'); + const [edited, , editedParent] = add.mock.calls[1]!; + expect(editedParent).toBe(id); + expect(edited.front).toHaveLength(32); + expect(edited.front.some(([, y]) => y === 2)).toBe(false); + expect(edited.back).toEqual(part.back); + + await click(`[data-avatar-option="headpiece:${id}"]`); + await click('[data-avatar-save]'); + expect(save).toHaveBeenCalledWith( + 'dm-ada', + expect.objectContaining({ assetVersion: 3, headpiece: canonicalCustomPart(part) }), + ); + } finally { + await act(() => root.unmount()); + container.remove(); + } + }); + + it('retries loading the Part Library after a failed load', async () => { + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + const load = vi + .fn<() => Promise>() + .mockResolvedValueOnce(undefined) + .mockResolvedValueOnce([]); + const container = document.createElement('div'); + document.body.append(container); + const root = createRoot(container); + const bot = { + slug: 'ada', + displayName: 'Ada', + roles: [], + aggregateState: 'idle', + workspaces: [], + createdAt: '', + }; + const click = async (selector: string) => + act(() => container.querySelector(selector)!.click()); + try { + await act(() => + root.render( + createElement(AvatarAppearanceEditor, { + bot, + channelId: 'dm-ada', + onSave: vi.fn(async () => true), + library: { load, add: vi.fn(async () => undefined) }, + t: zhTranslate, + }), + ), + ); + await click('[data-avatar-edit]'); + await click('[data-avatar-category="headpiece"]'); + expect(container.textContent).not.toContain(zhTranslate('profile.avatar.part.libraryEmpty')); + await click('[data-avatar-category="hair"]'); + await click('[data-avatar-category="headpiece"]'); + expect(load).toHaveBeenCalledTimes(2); + expect(container.textContent).toContain(zhTranslate('profile.avatar.part.libraryEmpty')); + } finally { + await act(() => root.unmount()); + container.remove(); + } + }); + it('switches families without substituting parts and saves a bounded line recipe', async () => { Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); const save = vi.fn(async () => true); diff --git a/packages/client/test/bot-sidebar.test.ts b/packages/client/test/bot-sidebar.test.ts index 439d834483..42c88aeeb2 100644 --- a/packages/client/test/bot-sidebar.test.ts +++ b/packages/client/test/bot-sidebar.test.ts @@ -298,6 +298,8 @@ function stubActions(): BridgeActions { setBotBanner: vi.fn(async () => true), updateBotProfile: vi.fn(async () => true), setBotAppearance: vi.fn(async () => true), + loadPartLibrary: vi.fn(async () => []), + addLibraryPart: vi.fn(async () => undefined), profileUsage: vi.fn(), profileActivity: vi.fn(async () => ({ slug: '', diff --git a/packages/core/package.json b/packages/core/package.json index f30974ec30..ef70e5c01d 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -14,7 +14,7 @@ "./package.json": "./package.json" }, "dependencies": { - "@botharness/pixel-avatar": "0.4.0", + "@botharness/pixel-avatar": "0.5.0", "@botharness/pixel-banner": "0.1.0", "@resvg/resvg-js": "2.6.2", "silk-wasm": "3.7.1" diff --git a/packages/core/src/bots/avatar-appearance.ts b/packages/core/src/bots/avatar-appearance.ts index eeb37eda24..52177a8690 100644 --- a/packages/core/src/bots/avatar-appearance.ts +++ b/packages/core/src/bots/avatar-appearance.ts @@ -40,6 +40,28 @@ export { seededRecipe as seededAvatarRecipe, seededRecipeV2 as seededAvatarRecipeV2, withSpecies as withAvatarSpecies, + withHeadpiece as withAvatarHeadpiece, + PART_SLOTS, + PART_TONES, + MAX_PART_FIXED_COLORS, + canonicalCustomPart, + createCustomPart, + customPartId, + emptyPartLayer, + fillPartLayer, + isPixelCustomPart, + mirrorPartX, + paintPartLayer, + partCells, + partLayer, + partToneColor, + type PartColor, + type PartInk, + type PartLayer, + type PartLayerName, + type PartSlot, + type PartTone, + type PixelCustomPart, type AvatarColor, type AvatarHairPart, type AvatarPart, diff --git a/packages/core/src/bots/part-library.ts b/packages/core/src/bots/part-library.ts new file mode 100644 index 0000000000..b0de4670b6 --- /dev/null +++ b/packages/core/src/bots/part-library.ts @@ -0,0 +1,110 @@ +import type { OperationalDatabaseModulePort } from '../database/owner.js'; +import { + canonicalCustomPart, + customPartId, + isPixelCustomPart, + type PixelCustomPart, +} from './avatar-appearance.js'; + +export const PART_ORIGINS = ['drawn', 'imported-bot', 'imported-file'] as const; +export type PartOrigin = (typeof PART_ORIGINS)[number]; +export const MAX_PART_NAME = 60; + +export interface PartLibraryEntry { + id: string; + part: PixelCustomPart; + name: string; + origins: PartOrigin[]; + parent?: string; + author?: string; + addedAt: string; +} + +export interface PartLibraryInput { + part: PixelCustomPart; + name: string; + origin: PartOrigin; + parent?: string | undefined; + author?: string | undefined; +} + +export interface PartLibrary { + list(): PartLibraryEntry[]; + add(input: PartLibraryInput): PartLibraryEntry; +} + +const ID = /^[\da-f]{64}$/u; + +export function isPartLibraryEntry(value: unknown): value is PartLibraryEntry { + if (typeof value !== 'object' || value === null || Array.isArray(value)) return false; + const r = value as Record; + return ( + typeof r['id'] === 'string' && + isPixelCustomPart(r['part']) && + customPartId(r['part']) === r['id'] && + typeof r['name'] === 'string' && + r['name'].length <= MAX_PART_NAME && + Array.isArray(r['origins']) && + r['origins'].length > 0 && + r['origins'].every((origin) => (PART_ORIGINS as readonly unknown[]).includes(origin)) && + (r['parent'] === undefined || (typeof r['parent'] === 'string' && ID.test(r['parent']))) && + (r['author'] === undefined || + (typeof r['author'] === 'string' && r['author'].length <= MAX_PART_NAME)) && + typeof r['addedAt'] === 'string' + ); +} + +export function createPartLibrary(options: { + database: OperationalDatabaseModulePort; + now?: () => Date; +}): PartLibrary { + const { database } = options; + const now = options.now ?? (() => new Date()); + const read = (id?: string): PartLibraryEntry[] => + database.read((db) => { + const rows = + id === undefined + ? db.prepare('SELECT body FROM avatar_part_library ORDER BY rowid DESC').all() + : db.prepare('SELECT body FROM avatar_part_library WHERE id = ?').all(id); + return rows.flatMap((row) => { + const parsed: unknown = JSON.parse(String(row['body'])); + return isPartLibraryEntry(parsed) ? [parsed] : []; + }); + }); + return { + list: () => read(), + add(input) { + const part = canonicalCustomPart(input.part); + const id = customPartId(part); + const name = input.name.trim().slice(0, MAX_PART_NAME); + const [existing] = read(id); + const entry: PartLibraryEntry = existing + ? { + ...existing, + name: existing.name || name, + origins: existing.origins.includes(input.origin) + ? existing.origins + : [...existing.origins, input.origin], + } + : { + id, + part, + name, + origins: [input.origin], + ...(input.parent !== undefined && input.parent !== id ? { parent: input.parent } : {}), + ...(input.author ? { author: input.author.slice(0, MAX_PART_NAME) } : {}), + addedAt: now().toISOString(), + }; + database.transaction( + (db) => { + db.prepare( + `INSERT INTO avatar_part_library (id, body) VALUES (?, ?) + ON CONFLICT (id) DO UPDATE SET body = excluded.body`, + ).run(id, JSON.stringify(entry)); + }, + ['avatar-part-library'], + ); + return entry; + }, + }; +} diff --git a/packages/core/src/bridge/methods.ts b/packages/core/src/bridge/methods.ts index 2dd0171fc7..c7e94e53d9 100644 --- a/packages/core/src/bridge/methods.ts +++ b/packages/core/src/bridge/methods.ts @@ -90,6 +90,8 @@ import { import { botAvatarUrl } from '../bots/avatar-http.js'; import { botBannerSummary, type BotBannerSummary } from '../bots/banner-http.js'; import { isBotBanner, seededBotBanner } from '../bots/bot-banner.js'; +import { isPixelCustomPart } from '../bots/avatar-appearance.js'; +import { MAX_PART_NAME, type PartLibrary, type PartLibraryEntry } from '../bots/part-library.js'; import type { AvatarAppearance, RetainedAvatarAppearance } from '../bots/avatar-appearance.js'; import { ChannelMentionTargetError, ChannelReplyTargetError } from '../channels/store.js'; import { ChannelAttachmentError } from '../attachments/store.js'; @@ -510,6 +512,8 @@ export interface BridgeMethods { botAvatarSet(payload: unknown): BridgeResult<{ bot: PersonaBotDetail }>; botBannerSet(payload: unknown): BridgeResult<{ bot: PersonaBotDetail }>; botAppearanceSet(payload: unknown): BridgeResult<{ bot: PersonaBotDetail }>; + partLibraryList(): BridgeResult<{ parts: PartLibraryEntry[] }>; + partLibraryAdd(payload: unknown): BridgeResult<{ entry: PartLibraryEntry }>; marketplaceList(payload: unknown): Promise>; marketplaceSubmit(payload: unknown): Promise>; marketplaceTopics(): Promise>; @@ -543,6 +547,7 @@ export interface BridgeMethodsDeps { modelCatalog?: ModelCatalog; modelReadiness?: ModelRouteReadiness; onboarding?: BotOnboarding; + partLibrary?: PartLibrary; onboardingNews?: (slug?: string) => Promise; defaultModel?: { currentSelection(): ModelRoute; @@ -2189,6 +2194,34 @@ export function createBridgeMethods(deps: BridgeMethodsDeps): BridgeMethods { : invalidInput('invalid Avatar Appearance'); return { ok: true, value: detailOf(result.record) }; }, + partLibraryList() { + if (!deps.partLibrary) return unavailable(); + try { + return { ok: true, value: { parts: deps.partLibrary.list() } }; + } catch (error) { + if (error instanceof OperationalDatabaseError) return unavailable(); + throw error; + } + }, + partLibraryAdd(payload) { + if (!deps.partLibrary) return unavailable(); + const input = asObject(payload); + const part = input['part']; + const name = input['name'] ?? ''; + const parent = input['parent']; + if (!isPixelCustomPart(part)) return invalidInput('part must be a valid Custom Part'); + if (typeof name !== 'string' || name.length > MAX_PART_NAME) + return invalidInput(`name must be a string of at most ${MAX_PART_NAME} characters`); + if (parent !== undefined && (typeof parent !== 'string' || !/^[\da-f]{64}$/u.test(parent))) + return invalidInput('parent must be a Custom Part id'); + try { + const entry = deps.partLibrary.add({ part, name, origin: 'drawn', parent }); + return { ok: true, value: { entry } }; + } catch (error) { + if (error instanceof OperationalDatabaseError) return unavailable(); + throw error; + } + }, botBannerSet(payload) { const scope = dmMemory(payload); if (!('botSlug' in scope)) return scope; diff --git a/packages/core/src/bridge/rpc.ts b/packages/core/src/bridge/rpc.ts index 8d93bbe3d1..30b5d1b1fb 100644 --- a/packages/core/src/bridge/rpc.ts +++ b/packages/core/src/bridge/rpc.ts @@ -1,3 +1,4 @@ +import type { PartLibraryEntry } from '../bots/part-library.js'; import type { OnboardingSnapshot, TutorialAction } from '../onboarding/service.js'; import type { HttpsFallback } from '../memory/clone.js'; import type { PairingRequest, PairingReviewInput } from '../messaging/pairing.js'; @@ -487,6 +488,14 @@ export class BotharnessBridgeService extends TypertRemoteService { return unwrap(this.methods.botAvatarSet({ channelId, avatar })); } + partLibraryList(): { parts: PartLibraryEntry[] } { + return unwrap(this.methods.partLibraryList()); + } + + partLibraryAdd(part: unknown, name: string, parent?: string): { entry: PartLibraryEntry } { + return unwrap(this.methods.partLibraryAdd({ part, name, parent })); + } + botBannerSet(channelId: string, banner: unknown): { bot: PersonaBotDetail } { return unwrap(this.methods.botBannerSet({ channelId, banner })); } @@ -1228,6 +1237,8 @@ markRemoteMethods(BotharnessBridgeService.prototype, [ 'standingLimitsSet', 'botAvatarSet', 'botAppearanceSet', + 'partLibraryList', + 'partLibraryAdd', 'botBannerSet', 'marketplaceList', 'marketplaceSubmit', diff --git a/packages/core/src/database/schema-plan.ts b/packages/core/src/database/schema-plan.ts index b7ce1239f6..51896e7ee1 100644 --- a/packages/core/src/database/schema-plan.ts +++ b/packages/core/src/database/schema-plan.ts @@ -1916,6 +1916,20 @@ const PROFILE_RECOVERY_MIGRATION: SchemaMigration = { }, }; +const AVATAR_PART_LIBRARY_MIGRATION: SchemaMigration = { + generation: 73, + module: 'avatar-part-library', + description: 'Persist the Profile Part Library of Human-drawn Avatar Custom Parts', + migrate(database) { + database.exec(` + CREATE TABLE avatar_part_library ( + id TEXT PRIMARY KEY CHECK (length(id) = 64), + body TEXT NOT NULL CHECK (json_valid(body)) + ); + `); + }, +}; + export const BOT_HARNESS_SCHEMA_PLAN = defineSchemaPlan([ SESSION_OWNERSHIP_MIGRATION, MESSAGING_TRACER_MIGRATION, @@ -1988,4 +2002,5 @@ export const BOT_HARNESS_SCHEMA_PLAN = defineSchemaPlan([ COMPLETE_CONTENT_PURGE_MIGRATION, BOT_ONBOARDING_MIGRATION, PROFILE_RECOVERY_MIGRATION, + AVATAR_PART_LIBRARY_MIGRATION, ]); diff --git a/packages/core/src/plugin.ts b/packages/core/src/plugin.ts index 4bed5e45ff..b68c63132e 100644 --- a/packages/core/src/plugin.ts +++ b/packages/core/src/plugin.ts @@ -1,6 +1,7 @@ import { onboardingNewsAvailable } from './onboarding/search.js'; import { nativeTimedQuestions } from './channels/native-timed-questions.js'; import { createBotOnboarding, type BotOnboarding } from './onboarding/service.js'; +import { createPartLibrary, type PartLibrary } from './bots/part-library.js'; import { createOutboundMessaging, type OutboundMessaging } from './messaging/outbound.js'; import { createProfileRecovery, type ProfileRecovery } from './portability/recovery.js'; import { createProfileBackupHttp, PROFILE_BACKUP_PATH } from './portability/http.js'; @@ -229,6 +230,7 @@ export interface BotHarnessCore { profileRecovery: ProfileRecovery; rootDir: string; onboarding: BotOnboarding; + partLibrary: PartLibrary; operationalDatabase: OperationalDatabaseOwner; registry: PersonaBotRegistry; deletions: PersonaBotDeletions; @@ -721,12 +723,16 @@ export function createCore( registry, channels, }); + const partLibrary = createPartLibrary({ + database: attachOperationalModule(operationalDatabase, 'avatar-part-library'), + }); if (operationalDatabase.mode === 'ready') schedules.start(); return { deletions, profileRecovery, contentPurge, onboarding, + partLibrary, rootDir, operationalDatabase, externalMessaging, @@ -1270,6 +1276,7 @@ export function apply(ctx: Context, config: BotHarnessConfig): void { modelCatalog, modelReadiness, onboarding: core.onboarding, + partLibrary: core.partLibrary, onboardingNews: (slug) => onboardingNewsAvailable( ctx, diff --git a/packages/core/test/bridge-rpc.test.ts b/packages/core/test/bridge-rpc.test.ts index f2938c548d..9b94831bb6 100644 --- a/packages/core/test/bridge-rpc.test.ts +++ b/packages/core/test/bridge-rpc.test.ts @@ -213,6 +213,8 @@ describe('bridge typert service', () => { 'standingLimitsSet', 'botAvatarSet', 'botAppearanceSet', + 'partLibraryList', + 'partLibraryAdd', 'botBannerSet', 'marketplaceList', 'marketplaceSubmit', diff --git a/packages/core/test/part-library.test.ts b/packages/core/test/part-library.test.ts new file mode 100644 index 0000000000..5ab3c50068 --- /dev/null +++ b/packages/core/test/part-library.test.ts @@ -0,0 +1,174 @@ +import { describe, expect, it } from 'vitest'; +import { OperationalDatabaseError, mountOperationalDatabase } from '../src/database/owner.js'; +import { BOT_HARNESS_SCHEMA_PLAN } from '../src/database/schema-plan.js'; +import { defineSchemaPlan } from '../src/database/schema.js'; +import { createCore } from '../src/plugin.js'; +import { createBridgeMethods } from '../src/bridge/methods.js'; +import { + DEFAULT_ILLUSTRATED_RECIPE, + customPartId, + withAvatarHeadpiece, + withAvatarSpecies, + type PixelCustomPart, +} from '../src/bots/avatar-appearance.js'; +import { readSharedPresentation } from '../src/bots/shared-presentation.js'; +import type { BotAgentAdapter } from '../src/runtime/bot-runtime.js'; +import { createTempRoot } from './helpers.js'; + +const agents: BotAgentAdapter = { + async runOrchestrator() {}, + async runAssignment() {}, + requestAssignment() { + throw new Error('Unexpected Assignment'); + }, + async close() {}, +}; + +const crown: PixelCustomPart = { + slot: 'headpiece', + front: [ + [13, 2, '#efb93f', 1], + [18, 2, '#efb93f', 1], + [13, 3, 'hairColor', 0], + [18, 3, 'hairColor', 0], + ], + back: [], +}; + +async function withCore( + dshHome: string, + test: (core: ReturnType) => Promise | void, +): Promise { + const core = createCore({ dshHome, agents }); + try { + await test(core); + } finally { + await core.runtime.close(); + core.operationalDatabase.close(); + } +} + +describe('Part Library through the public Host bridge', () => { + it('adds drawn parts once by content and keeps them across restarts', async () => { + const dshHome = createTempRoot('bh-part-library-'); + await withCore(dshHome, (core) => { + const bridge = createBridgeMethods({ ...core }); + expect(bridge.partLibraryList()).toEqual({ ok: true, value: { parts: [] } }); + const added = bridge.partLibraryAdd({ part: crown, name: ' Little crown ' }); + expect(added).toMatchObject({ + ok: true, + value: { + entry: { id: customPartId(crown), name: 'Little crown', origins: ['drawn'] }, + }, + }); + const reordered = { ...crown, front: [...crown.front].reverse() }; + const again = bridge.partLibraryAdd({ part: reordered, name: 'Copy' }); + expect(again.ok && again.value.entry.name).toBe('Little crown'); + const parts = bridge.partLibraryList(); + expect(parts.ok && parts.value.parts).toHaveLength(1); + }); + await withCore(dshHome, (core) => { + const bridge = createBridgeMethods({ ...core }); + const parts = bridge.partLibraryList(); + expect(parts.ok && parts.value.parts.map((entry) => entry.id)).toEqual([customPartId(crown)]); + }); + }); + + it('reports unavailable storage as a structured result', async () => { + await withCore(createTempRoot('bh-part-library-storage-'), (core) => { + const failing = { + list: () => { + throw new OperationalDatabaseError('closed', 'closed'); + }, + add: () => { + throw new OperationalDatabaseError('closed', 'closed'); + }, + }; + const bridge = createBridgeMethods({ ...core, partLibrary: failing }); + expect(bridge.partLibraryList()).toMatchObject({ + ok: false, + error: { code: 'storage-unavailable' }, + }); + expect(bridge.partLibraryAdd({ part: crown, name: '' })).toMatchObject({ + ok: false, + error: { code: 'storage-unavailable' }, + }); + }); + }); + + it('rejects invalid parts, names and parents', async () => { + await withCore(createTempRoot('bh-part-library-invalid-'), (core) => { + const bridge = createBridgeMethods({ ...core }); + expect(bridge.partLibraryAdd({ part: { ...crown, slot: 'mouth' }, name: '' }).ok).toBe(false); + expect( + bridge.partLibraryAdd({ part: { ...crown, front: [[40, 0, 'hairColor', 0]] }, name: '' }) + .ok, + ).toBe(false); + expect(bridge.partLibraryAdd({ part: crown, name: 'x'.repeat(61) }).ok).toBe(false); + expect(bridge.partLibraryAdd({ part: crown, name: '', parent: 'abc' }).ok).toBe(false); + const parts = bridge.partLibraryList(); + expect(parts.ok && parts.value.parts).toEqual([]); + }); + }); + + it('records an edit as a new part and never changes an applied copy', async () => { + await withCore(createTempRoot('bh-part-library-apply-'), (core) => { + const bridge = createBridgeMethods({ ...core }); + expect(core.registry.create({ slug: 'ada', displayName: 'Ada', workspaces: [] }).ok).toBe( + true, + ); + const original = bridge.partLibraryAdd({ part: crown, name: 'Crown' }); + if (!original.ok) throw new Error('add failed'); + const recipe = withAvatarHeadpiece( + withAvatarSpecies(DEFAULT_ILLUSTRATED_RECIPE, 'human'), + original.value.entry.part, + ); + const applied = core.registry.setAppearance('ada', recipe); + expect(applied.ok).toBe(true); + const edited: PixelCustomPart = { ...crown, back: [[15, 6, 'skinColor', -1]] }; + const derived = bridge.partLibraryAdd({ + part: edited, + name: 'Crown with band', + parent: original.value.entry.id, + }); + expect(derived).toMatchObject({ + ok: true, + value: { entry: { id: customPartId(edited), parent: customPartId(crown) } }, + }); + const parts = bridge.partLibraryList(); + expect(parts.ok && parts.value.parts.map((entry) => entry.name)).toEqual([ + 'Crown with band', + 'Crown', + ]); + const stored = core.registry.get('ada')?.appearance; + expect(stored && 'recipe' in stored && stored.recipe).toMatchObject({ + assetVersion: 3, + headpiece: { front: original.value.entry.part.front, back: [] }, + }); + const memoryDir = core.registry.memoryDirFor('ada')!; + expect(readSharedPresentation(memoryDir)?.appearance?.recipe).toMatchObject({ + assetVersion: 3, + headpiece: original.value.entry.part, + }); + }); + }); +}); + +it('upgrades generation 72 with an empty Part Library', () => { + const dshHome = createTempRoot('bh-part-library-upgrade-'); + const prior = mountOperationalDatabase({ + dshHome, + schemaPlan: defineSchemaPlan( + BOT_HARNESS_SCHEMA_PLAN.migrations.filter((m) => m.generation <= 72), + ), + }); + expect(prior.generation).toBe(72); + prior.close(); + const upgraded = mountOperationalDatabase({ dshHome, schemaPlan: BOT_HARNESS_SCHEMA_PLAN }); + try { + expect(upgraded.mode).toBe('ready'); + expect(upgraded.generation).toBe(BOT_HARNESS_SCHEMA_PLAN.targetGeneration); + } finally { + upgraded.close(); + } +}); diff --git a/packages/core/test/plugin.test.ts b/packages/core/test/plugin.test.ts index 59d780e84c..f4893df892 100644 --- a/packages/core/test/plugin.test.ts +++ b/packages/core/test/plugin.test.ts @@ -473,6 +473,8 @@ describe('plugin entry', () => { 'standingLimitsSet', 'botAvatarSet', 'botAppearanceSet', + 'partLibraryList', + 'partLibraryAdd', 'botBannerSet', 'marketplaceList', 'marketplaceSubmit', diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 12cb875752..9470c50fef 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -568,8 +568,8 @@ importers: packages/core: dependencies: '@botharness/pixel-avatar': - specifier: 0.4.0 - version: 0.4.0 + specifier: 0.5.0 + version: 0.5.0 '@botharness/pixel-banner': specifier: 0.1.0 version: 0.1.0 @@ -1173,8 +1173,8 @@ packages: '@botharness/botui-core@0.3.0': resolution: {integrity: sha512-ZfuyXyAtxIijqxPb7zWKu3/aO3GKT8kTzQpCBYD08t9vOp858r/xL8BsQvwjswTTH2bTZ8saXBnUgjYBRnY8xQ==} - '@botharness/pixel-avatar@0.4.0': - resolution: {integrity: sha512-yYbAwZLGpgyhDVNBXXLd6bmQ8L2pmxECv/CxlJIYaUxfCEHK3VZFGJo/Mcdc5qvvOoguDhtSUAHdpebVdJQhkQ==} + '@botharness/pixel-avatar@0.5.0': + resolution: {integrity: sha512-ZkmYjZtwmUaECR7m9hceXTbkOQnomU23AACKM4lC8TAoolpVPCbHLNjp6GhqDL2RHU2LtWcqg+6tcSuAVT0t5A==} '@botharness/pixel-banner@0.1.0': resolution: {integrity: sha512-2qzZK8O73u9m97sCeQh9s/4QaRsMwCTM42n2HLxCHQNiQp7dYYhulYiYNviasr/9eAGR4ARZr3B06yOCD/Ge1A==} @@ -10790,7 +10790,7 @@ snapshots: '@botharness/botui-core@0.3.0': {} - '@botharness/pixel-avatar@0.4.0': + '@botharness/pixel-avatar@0.5.0': dependencies: '@botharness/pixel-morph': 0.2.0 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 34a0c92b9e..277ef32ec9 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -308,7 +308,7 @@ minimumReleaseAgeExclude: - '@deepseek-ai/dsh-experimental-schedule-bundle@0.2.0-rc.1' - '@deepseek-ai/dsh-host-product-telemetry-otel@0.2.0-rc.1' - '@deepseek-ai/dsh-otel@0.2.0-rc.1' - - '@botharness/pixel-avatar@0.1.0 || 0.2.0 || 0.3.0 || 0.4.0' + - '@botharness/pixel-avatar@0.1.0 || 0.2.0 || 0.3.0 || 0.4.0 || 0.5.0' - '@botharness/pixel-banner@0.1.0' - '@botharness/pixel-morph@0.1.0 || 0.2.0'