diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b083a62d7..6f0bc3cd89 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -267,6 +267,8 @@ Advances the first PersonaBot workflow with Assignment delivery, shared motion c ### Changed +- Many active Avatars now animate smoothly together: all transitions share one animation-frame loop, pixel-family tool transitions step at a pixel-art frame rate with merged color runs (`@botharness/pixel-morph` 0.2.0), and Avatars scrolled out of view skip transition work after updates, keeping 32 to 128 active mixed-family Avatars at full frame rate in measured runs ([#757](https://github.com/BotHarness/BotHarness/issues/757)). + - Made the packaged IM Provider qualification independent of developer selections and advanced its own artifact version for the accepted Slack capabilities ([IM installation](docs/product-im-installation.md), [#868](https://github.com/BotHarness/BotHarness/issues/868)). - Bot Inbox sidebar rows now put readable content first, separate source/report metadata from lifecycle status, and highlight items needing repair using the native error color ([#851](https://github.com/BotHarness/BotHarness/issues/851)). diff --git a/CHANGELOG.zh.md b/CHANGELOG.zh.md index dad40551ae..b4ff5aaf1d 100644 --- a/CHANGELOG.zh.md +++ b/CHANGELOG.zh.md @@ -267,6 +267,8 @@ ### Changed +- 大量头像同时活动时更流畅:所有过渡共用一个动画帧循环,像素风格的工具切换按像素画帧率步进并合并同色像素(`@botharness/pixel-morph` 0.2.0),滚出视野的头像在状态更新后不再做过渡计算;实测 32 到 128 个混合风格的活动头像仍保持满帧([#757](https://github.com/BotHarness/BotHarness/issues/757))。 + - 产品 IM Provider 采用独立固定的资格验证输入,并为已验收的 Slack 能力递增自身版本,避免开发版选择隐式改变产品产物([IM 安装指南](docs/product-im-installation.md)、[#868](https://github.com/BotHarness/BotHarness/issues/868))。 - Bot Inbox 侧栏以内容为先,分行展示来源、Report 信息与处理状态,并用原生错误色突出需要修复的项 ([#851](https://github.com/BotHarness/BotHarness/issues/851))。 diff --git a/docs/evidence/issue-757/00-start.png b/docs/evidence/issue-757/00-start.png new file mode 100644 index 0000000000..b97fe29434 Binary files /dev/null and b/docs/evidence/issue-757/00-start.png differ diff --git a/docs/evidence/issue-757/01-draft.png b/docs/evidence/issue-757/01-draft.png new file mode 100644 index 0000000000..bb998ba365 Binary files /dev/null and b/docs/evidence/issue-757/01-draft.png differ diff --git a/docs/evidence/issue-757/02-saved.png b/docs/evidence/issue-757/02-saved.png new file mode 100644 index 0000000000..9bd0a816a3 Binary files /dev/null and b/docs/evidence/issue-757/02-saved.png differ diff --git a/docs/evidence/issue-757/04-approval-pending.png b/docs/evidence/issue-757/04-approval-pending.png new file mode 100644 index 0000000000..ce69be7fd5 Binary files /dev/null and b/docs/evidence/issue-757/04-approval-pending.png differ diff --git a/docs/evidence/issue-757/05-working.png b/docs/evidence/issue-757/05-working.png new file mode 100644 index 0000000000..9edeb26d08 Binary files /dev/null and b/docs/evidence/issue-757/05-working.png differ diff --git a/docs/evidence/issue-757/06-reloaded.png b/docs/evidence/issue-757/06-reloaded.png new file mode 100644 index 0000000000..a3da01ff96 Binary files /dev/null and b/docs/evidence/issue-757/06-reloaded.png differ diff --git a/docs/evidence/issue-757/07-disconnected.png b/docs/evidence/issue-757/07-disconnected.png new file mode 100644 index 0000000000..4048fab9fe Binary files /dev/null and b/docs/evidence/issue-757/07-disconnected.png differ diff --git a/docs/evidence/issue-757/08-restarted.png b/docs/evidence/issue-757/08-restarted.png new file mode 100644 index 0000000000..6e2d50cad9 Binary files /dev/null and b/docs/evidence/issue-757/08-restarted.png differ diff --git a/docs/evidence/issue-757/09-dark.png b/docs/evidence/issue-757/09-dark.png new file mode 100644 index 0000000000..5bded9763e Binary files /dev/null and b/docs/evidence/issue-757/09-dark.png differ diff --git a/docs/evidence/issue-757/10-light.png b/docs/evidence/issue-757/10-light.png new file mode 100644 index 0000000000..ec3d2a86bd Binary files /dev/null and b/docs/evidence/issue-757/10-light.png differ diff --git a/docs/evidence/issue-757/11-mixed-active.png b/docs/evidence/issue-757/11-mixed-active.png new file mode 100644 index 0000000000..480f847046 Binary files /dev/null and b/docs/evidence/issue-757/11-mixed-active.png differ diff --git a/docs/evidence/issue-757/README.md b/docs/evidence/issue-757/README.md new file mode 100644 index 0000000000..1df1daac79 --- /dev/null +++ b/docs/evidence/issue-757/README.md @@ -0,0 +1,139 @@ +# Issue #757 — Mixed-family Avatar runtime and performance acceptance + +Issue: [#757](https://github.com/BotHarness/BotHarness/issues/757), child of hub [#750](https://github.com/BotHarness/BotHarness/issues/750) and source specification [#748](https://github.com/BotHarness/BotHarness/issues/748). + +Measured on 2026-10-05 at main `ea4b9d32` plus this change, Apple M3 (24 GB), macOS 26.7.1, Google Chrome 154.0.8037.98 (headless, 1280 × 900, device scale 1), production React build. + +## How the numbers were taken + +`harness/` mounts the real `PersonaBotAvatar` from client source with the real client CSS: + +- Mixed families: every pixel preset, every line preset, and two pixel recipes at the legal geometry extremes (twin tails, side pose, `spacing ±1`, `height ∓1`, `hairLength ±2`). +- Rapid transitions: every Avatar changes state every 700 ms through eight tool symbols, thinking and idle, staggered so that some transition is always running. This is a stress cadence; real tool calls change far less often. +- One in five Avatars carries a pending approval. +- Each run warms up for 2 s and then measures 6 s of `requestAnimationFrame` intervals together with Chrome `Performance.getMetrics`. + +Rebuild and run it with: + +```sh +NODE_PATH=packages/client/node_modules node_modules/.pnpm/esbuild@0.28.2/node_modules/esbuild/bin/esbuild docs/evidence/issue-757/harness/entry.tsx --bundle --minify --format=iife --jsx=automatic --define:process.env.NODE_ENV='"production"' --outfile=docs/evidence/issue-757/harness/bundle.js +node docs/evidence/issue-757/harness/measure.mjs # gradient, cpu, reduce, stale, lifecycle +node docs/evidence/issue-757/harness/measure.mjs family # pixel-only vs line-only +node docs/evidence/issue-757/harness/measure.mjs scroll # sidebar column with 256 mounted Avatars +``` + +Raw rows are in `measurements-before.jsonl` (main) and `measurements-after.jsonl` (this change, with `@botharness/pixel-morph` 0.2.0). "Main thread" is Chrome `TaskDuration` per second. "rAF/s" counts animation-frame callbacks the page requests, excluding the measuring loop. + +## What the measurements found and what changed + +Before this change, a pixel tool transition rebuilt its whole cell markup, one `` per run, on every display frame. Thirty-two pixel Avatars transitioning together cost about 1 s of main-thread work per second, and the page fell to 20 fps. In a sidebar column of 256 rows, rows scrolled out of view still restarted their transition, and read computed style, on every state update. + +The change follows the morphicons model, which plans each morph pair once and drives every icon on screen from one shared `requestAnimationFrame`. It touches three places and adds no new library: + +- **`@botharness/pixel-morph`** ([BotHarness/BotPixel#3](https://github.com/BotHarness/BotPixel/pull/3)). Transitions advance in 50 ms pixel-art steps (`frameMs: 50`), so a frame is computed only when the step changes. Each step is drawn as one `` per color (`pixelPathMarkup`) instead of one `` per run. All running morphs share one `requestAnimationFrame` loop. The step and path options are opt-in, and the library's defaults and golden output are unchanged. Released as 0.2.0. Planning a face→symbol pair (about 700 pixels) takes about 0.16 ms, and a frame takes about 0.12 ms to compute and serialise. The package is about 2.8 KB gzip with no runtime dependencies. +- **`line-morph.ts`.** Every running line-face morph ticks from one shared loop, like morphicons' own DOM player. +- **`illustrated-avatar.tsx`.** Static pixel symbols use the same path markup. An Avatar remembers that it is out of view across updates, so an offscreen row stays still until the observer reports it visible again. Computed style is read only while motion is actually running. + +Truthful state, symbols, the 0.5 s symbol hold and both families are unchanged. The saved generator output, recipes and snapshots are untouched. + +| Scenario (stress cadence) | Before: frame p50 / p95 / max | Before: main thread, rAF/s | After: frame p50 / p95 / max | After: main thread, rAF/s | +| -------------------------- | ----------------------------- | -------------------------- | ----------------------------------- | ------------------------- | +| 1 mixed | 16.7 / 16.7 / 16.8 ms | 45 ms/s, 23 | 16.7 / 16.7 / 16.8 ms | 40 ms/s, 23 | +| 8 mixed | 16.7 / 16.7 / 16.8 ms | 323 ms/s, 415 | 16.7 / 16.8 / 16.8 ms | 119 ms/s, 61 | +| 32 mixed | 16.7 / 16.8 / 33.4 ms | 796 ms/s, 1299 | 16.7 / 16.7 / 16.8 ms | 192 ms/s, 122 | +| 64 mixed | 33.3 / 50.0 / 83.4 ms | 967 ms/s, 1565 | 16.7 / 16.7 / 16.8 ms | 269 ms/s, 122 | +| 128 mixed | 66.7 / 233 / 250 ms | 1036 ms/s, 1238 | 16.7 / 16.8 / 33.4 ms | 385 ms/s, 120 | +| 32 pixel only | 50 / 117 / 183 ms | 1052 ms/s, 554 | 16.7 / 16.7 / 16.8 ms | 120 ms/s, 61 | +| 32 line only | 16.7 / 16.8 / 50.1 ms | 339 ms/s, 847 | 16.7 / 16.8 / 16.8 ms | 100 ms/s, 61 | +| 32 mixed, 4× CPU throttle | 83 / 283 / 317 ms | 1043 ms/s | 16.7 / 16.8 / 66.7 ms | 536 ms/s | +| 64 mixed, 4× CPU throttle | 167 / 617 / 633 ms | 1067 ms/s | 16.7 / 33.4 / 150 ms | 884 ms/s | +| 32 at 96 px | 16.7 / 33.3 / 83.4 ms | 894 ms/s | 16.7 / 16.8 / 33.4 ms | 162 ms/s | +| 32 instances of one Bot | 16.7 / 33.4 / 50.1 ms | 894 ms/s | 16.7 / 16.7 / 33.4 ms | 115 ms/s | +| Column of 256, top | 16.7 / 117 / 233 ms | 616 ms/s | 16.7 / 16.8 / 50.1 ms | 245 ms/s | +| Column of 256, scrolling | 16.7 / 100 / 217 ms | 677 ms/s | 16.7 / 16.8 / 66.7 ms | 356 ms/s | +| 32 static (no transitions) | 16.7 / 16.8 / 16.8 ms | 23 ms/s, 0 | 16.7 / 16.7 / 16.8 ms | 42 ms/s, 0 | +| 32 under reduced motion | — | — | 16.7 / 16.8 / 16.8 ms, 0 animations | 20 ms/s, 0 | +| 32 while activity is stale | — | — | 16.7 / 16.7 / 16.8 ms, 0 animations | 20 ms/s, 0 | + +The "Column of 256" before-numbers come from the intermediate build that already had the pixel-step change. That makes them an upper bound on what the offscreen fix alone saves. + +Lifecycle after 20 mount/unmount cycles of 32 transitioning Avatars: + +- `document.getAnimations()` returns 0. +- No `requestAnimationFrame` callbacks fire in 2 s. +- DOM nodes return to the empty page (14–18) after repeated GC. A single GC sometimes still holds the last unmounted tree; a dedicated 60-cycle run returned to 14 nodes each time. +- Event listeners return to the React root baseline (133). +- JS heap settles near 3.5–4 MB, with roughly 0.15 MB of drift per 20 cycles. + +Two costs do not come from the Avatar: + +- The activity dot matrix (`@botharness/botui-core`) is now shown next to row names. Thirty-two of them animating cost about 190–560 ms/s of main thread even with no Avatar transitions. They do pause under stale and reduced motion. +- In real DSH, bash calls were refused with "Path is outside this Session's authorized workspace" even with a workspace grant. Read and grep in the same workspace succeeded. + +Neither is part of this change. + +## Asset and bundle cost + +| Item | Measured | +| ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | +| Pixel Avatar SVG nodes (static figure) | 387–459 per Avatar; up to 2,017 at ≥ 96 px while the thinking head-turn frames are mounted | +| Pixel transition and symbol overlay | one `` per color, typically 4–10 nodes | +| Line Avatar SVG nodes | 16–21 per Avatar | +| Avatar renderer modules (core figure, line, symbols, appearance, morphicons, client renderer, morphs) | 75.7 KB minified, 25.5 KB gzip, bundled alone | +| Avatar-only modules inside the full client bundle (adds editor, excludes shared code) | about 81 KB minified, about 28 KB gzip | +| Full client bundle | 1,359 KB minified, 465.6 KB gzip, against 1,215 KB / 425.0 KB at `397a42fc^` (that difference also includes every unrelated feature merged since) | + +## Acceptance budgets + +These budgets are derived from the after-measurements with headroom. The supported limit is **32 simultaneously active Avatars visible together**, in the sidebar plus enlarged Profile or editor views. Up to **256 mounted rows** are supported when the rows outside the viewport are scrolled away. + +| Budget | Limit | Measured | +| ---------------------------------------------------- | ------------------------------------------------------------ | ---------------------------- | +| Frame p95 with 32 active, stress cadence | ≤ 16.8 ms (one display frame) | 16.8 ms | +| Frame p95 with 32 active, 4× CPU throttle | ≤ 33.4 ms | 16.8 ms | +| Frames over 25 ms with 32 active | ≤ 3 % | 0 % (0 of 360); 3 % at 4× | +| Main thread with 32 active, stress cadence | ≤ 300 ms/s | 192 ms/s | +| Animation-frame callbacks while morphing | one shared loop per family (≤ 2 × display rate) | 122/s at 60 Hz | +| Main thread with 32 static | ≤ 50 ms/s | 42 ms/s | +| Animation work under reduced motion, stale or hidden | 0 rAF/s, 0 Avatar animations | 0 / 0 | +| JS heap with 32 active | ≤ 40 MB | 21–38 MB | +| Retained after unmount | 0 animations, 0 rAF, DOM and listeners at baseline | met | +| SVG nodes per Avatar | pixel ≤ 460 (≤ 2,100 with turn frames at ≥ 96 px), line ≤ 24 | 459 / 2,017 / 21 | +| Avatar code added to the client bundle | ≤ 90 KB minified, ≤ 32 KB gzip | about 81 KB / 28 KB | +| Bridge traffic while animating | no per-frame RPC; 0 appearance or Session writes | 0–5 reads in 4–5 s, 0 writes | +| Appearance writes per Save | exactly 1; 0 for draft and Cancel | 1 / 0 | + +## Recognition in light and dark + +`recognition-light-dark.png` shows every preset of both families at 18, 24, 40 and 96 px on light and dark surfaces. Every third Avatar shows its tool symbol. The rows are not cropped and show actual size. + +- Pixel characters stay distinguishable at 18 px by hair silhouette and tile color. +- Line faces stay distinguishable by expression and tile color. +- Tool symbols read at 24 px and above. +- Each tile carries its own background, so contrast does not depend on the theme. + +## Actual DSH path + +`real-dsh-path.json` records each step from `.humanlayer/tasks/751-avatar/qa757.mjs`. The run used a local dev Host built from this change, with an isolated profile and real DeepSeek turns. + +| Step | Result | Evidence | +| ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | +| Edit a draft, then Cancel | 0 writes, revision unchanged | `00-start.png`, `01-draft.png` | +| Edit, then Save | exactly 1 `botAppearanceSet`; fresh read shows the new recipe and revision; the editor preview changed | `02-saved.png` | +| Same appearance across Bindings | identical SVG in sidebar (34 px), header (22 px), Profile (64 px) and editor (160 px) | `real-dsh-path.json` | +| Real work plus native approval | real read turn; bash approval pending with the approval symbol; 239 frames at p95 16.8 ms; 2 read-only bridge requests (`profileUsage`) and 0 writes in that 4 s window | `04-approval-pending.png`, `05-working.png`, `real-work.gif` | +| Resolution and cancellation | approvals both allowed and rejected; the Bot returned to idle; appearance unchanged by work | `real-dsh-path.json` | +| Reload | same identity in all four Bindings | `06-reloaded.png` | +| Disconnect (Host killed) | stale notice; 0 Avatar animations while stale | `07-disconnected.png` | +| Host restart | stale clears; fresh read returns the same appearance and revision; same identity in all Bindings | `08-restarted.png` | +| Round trip and malformed input | a full detailed recipe round-trips exactly through the real bridge; nine malformed inputs are rejected without changing the stored appearance | `real-dsh-path.json` | +| Mixed families together | a pixel Bot, a line Bot and a Bot with a retained unsupported appearance (shown as its saved snapshot) are all active in the sidebar together; both active Bots ran real read/grep turns with approvals; 300 frames at p95 16.8 ms; 5 reads and 0 writes in 5.1 s | `11-mixed-active.png`, `mixed-sidebar.gif`, `09-dark.png`, `10-light.png` | + +The nine rejected inputs were an unknown part, a partial hair split, a missing range, a range overflow, a non-integer range, an extra key, a bad color, a future schema and a non-object. + +Not claimed here, per #757: + +- #123's undelivered attention and waiting axes +- #124 Group expansion +- Live2D +- full sharing and backup diff --git a/docs/evidence/issue-757/harness/entry.tsx b/docs/evidence/issue-757/harness/entry.tsx new file mode 100644 index 0000000000..aa31b7aae0 --- /dev/null +++ b/docs/evidence/issue-757/harness/entry.tsx @@ -0,0 +1,175 @@ +import { createElement, useEffect, useState } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { PersonaBotAvatar } from '../../../../packages/client/src/client/avatar.js'; +import { + AVATAR_PRESETS, + DEFAULT_ILLUSTRATED_RECIPE, + detailedAvatarRecipe, +} from '../../../../packages/core/src/bots/avatar-appearance.js'; +import { LINE_PRESETS } from '../../../../packages/core/src/bots/avatar-line.js'; +import { CSS } from '../../../../packages/client/src/client/styles.js'; + +const TOOLS = [ + 'read', + 'grep', + 'edit', + 'bash', + 'web_search', + 'todo_write', + 'ask_user_question', + 'subagent', +]; +const extreme = detailedAvatarRecipe({ + ...DEFAULT_ILLUSTRATED_RECIPE, + hair: 'twintails', + pose: 'right', + accessory: AVATAR_PRESETS[3]!.accessory, +}); +const RECIPES = [ + ...AVATAR_PRESETS, + ...LINE_PRESETS, + { ...extreme, spacing: 1, height: -1, hairLength: 2 }, + { ...extreme, spacing: -1, height: 1, hairLength: -2, pose: 'left' as const }, +]; + +interface Config { + count: number; + size: number; + sameBot: boolean; + intervalMs: number; + indicator?: boolean; + family?: 'line' | 'illustrated'; + column?: boolean; +} + +function Grid({ config }: { config: Config }) { + const [tick, setTick] = useState(0); + useEffect(() => { + if (!config.intervalMs) return; + const id = setInterval(() => setTick((t) => t + 1), config.intervalMs); + return () => clearInterval(id); + }, [config.intervalMs]); + return createElement( + 'div', + config.column + ? { + style: { + display: 'flex', + flexDirection: 'column', + gap: '6px', + padding: '6px', + width: '260px', + }, + } + : { style: { display: 'flex', flexWrap: 'wrap', gap: '6px', padding: '6px' } }, + Array.from({ length: config.count }, (_, i) => { + const pool = config.family ? RECIPES.filter((r) => r.family === config.family) : RECIPES; + const recipe = config.sameBot ? pool[0]! : pool[i % pool.length]!; + const phase = (tick + i) % (TOOLS.length + 2); + const state = + phase === TOOLS.length ? 'thinking' : phase === TOOLS.length + 1 ? 'idle' : 'working'; + return createElement(PersonaBotAvatar, { + key: i, + personaBotId: config.sameBot ? 'same' : `bot-${i}`, + name: `Bot ${i}`, + appearance: { recipe, revision: 'a'.repeat(64) }, + size: config.size, + indicator: config.indicator ?? false, + state, + ...(state === 'working' + ? { + activity: { + effect: 'generic-working' as const, + toolKind: 'other' as const, + toolName: TOOLS[phase]!, + startedAt: 0, + activeToolCount: 1, + }, + } + : {}), + ...(i % 5 === 0 ? { attention: { approvalCount: 1 } } : {}), + }); + }), + ); +} + +const style = document.createElement('style'); +style.textContent = CSS; +document.head.append(style); +let root: Root | undefined; +Object.assign(window, { + mountGrid(config: Config) { + root?.unmount(); + const host = document.getElementById('app')!; + root = createRoot(host); + root.render(createElement(Grid, { config })); + }, + unmountGrid() { + root?.unmount(); + root = undefined; + }, +}); + +function Sheet({ dark }: { dark: boolean }) { + const sizes = [18, 24, 40, 96]; + const fg = dark ? '#e8e8e8' : '#222'; + return createElement( + 'div', + { + style: { + background: dark ? '#1b1b1f' : '#ffffff', + color: fg, + padding: '12px', + font: '12px system-ui', + }, + }, + createElement('div', { style: { marginBottom: '8px' } }, dark ? 'Dark' : 'Light'), + ...sizes.map((size) => + createElement( + 'div', + { + key: size, + style: { display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '8px' }, + }, + createElement('span', { style: { width: '36px' } }, `${size}px`), + ...RECIPES.map((recipe, i) => + createElement(PersonaBotAvatar, { + key: i, + personaBotId: `s-${i}`, + name: `Bot ${i}`, + appearance: { recipe, revision: 'a'.repeat(64) }, + size, + state: i % 3 === 1 ? 'working' : 'idle', + indicator: false, + ...(i % 3 === 1 + ? { + activity: { + effect: 'generic-working' as const, + toolKind: 'other' as const, + toolName: TOOLS[i % TOOLS.length]!, + startedAt: 0, + activeToolCount: 1, + }, + } + : {}), + }), + ), + ), + ), + ); +} +Object.assign(window, { + mountSheet() { + root?.unmount(); + document.documentElement.dataset.botharnessMotion = 'reduce'; + root = createRoot(document.getElementById('app')!); + root.render( + createElement( + 'div', + null, + createElement(Sheet, { dark: false }), + createElement(Sheet, { dark: true }), + ), + ); + }, +}); diff --git a/docs/evidence/issue-757/harness/index.html b/docs/evidence/issue-757/harness/index.html new file mode 100644 index 0000000000..5ae603d6d1 --- /dev/null +++ b/docs/evidence/issue-757/harness/index.html @@ -0,0 +1,16 @@ + + + + + + + +
+ + + diff --git a/docs/evidence/issue-757/harness/measure.mjs b/docs/evidence/issue-757/harness/measure.mjs new file mode 100644 index 0000000000..ae1ed530ef --- /dev/null +++ b/docs/evidence/issue-757/harness/measure.mjs @@ -0,0 +1,190 @@ +import { createRequire } from 'node:module'; +import { readdirSync } from 'node:fs'; +const pkg = readdirSync('node_modules/.pnpm').find((x) => x.startsWith('puppeteer-core@')); +const puppeteer = createRequire(process.cwd() + '/node_modules/.pnpm/' + pkg + '/node_modules/')( + 'puppeteer-core', +); +import http from 'node:http'; +import fs from 'node:fs'; +const dir = process.cwd() + '/docs/evidence/issue-757/harness'; +const served = { '/': 'index.html', '/index.html': 'index.html', '/bundle.js': 'bundle.js' }; +const server = http.createServer((q, r) => { + const file = served[q.url]; + if (!file) { + r.statusCode = 404; + r.end(); + return; + } + r.end(fs.readFileSync(`${dir}/${file}`)); +}); +await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); +const port = server.address().port; +const browser = await puppeteer.launch({ + executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', + headless: true, + args: ['--js-flags=--expose-gc', '--enable-precise-memory-info', '--window-size=1280,900'], +}); +const page = await browser.newPage(); +await page.setViewport({ width: 1280, height: 900 }); +await page.evaluateOnNewDocument(() => { + const raf = window.requestAnimationFrame.bind(window); + window.__raf = 0; + window.requestAnimationFrame = (cb) => { + window.__raf++; + return raf(cb); + }; +}); +const cdp = await page.createCDPSession(); +await cdp.send('Performance.enable'); +await page.goto('http://127.0.0.1:' + port + '/'); +const metrics = async () => + Object.fromEntries( + (await cdp.send('Performance.getMetrics')).metrics.map((m) => [m.name, m.value]), + ); +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +async function run( + label, + cfg, + { throttle = 1, reduce = false, stale = false, hidden = false, scroll = false, ms = 6000 } = {}, +) { + await cdp.send('Emulation.setCPUThrottlingRate', { rate: throttle }); + await page.evaluate((r) => { + r + ? (document.documentElement.dataset.botharnessMotion = 'reduce') + : delete document.documentElement.dataset.botharnessMotion; + }, reduce); + await page.evaluate((s) => { + s + ? (document.documentElement.dataset.botharnessActivity = 'stale') + : delete document.documentElement.dataset.botharnessActivity; + }, stale); + await page.evaluate((c) => window.mountGrid(c), cfg); + await sleep(2000); + await page.evaluate(() => { + gc(); + }); + const m0 = await metrics(); + const r = await page.evaluate( + async (ms, scroll) => { + const ts = []; + const raf0 = window.__raf; + const t0 = performance.now(); + await new Promise((res) => { + const f = (t) => { + ts.push(t); + if (scroll) { + window.scrollBy(0, 12); + if (window.scrollY + innerHeight >= document.body.scrollHeight - 2) + window.scrollTo(0, 0); + } + if (t - t0 < ms) requestAnimationFrame(f); + else res(); + }; + requestAnimationFrame(f); + }); + const d = ts + .slice(1) + .map((t, i) => t - ts[i]) + .sort((a, b) => a - b); + const q = (p) => d[Math.min(d.length - 1, Math.floor(p * d.length))]; + const svgs = [...document.querySelectorAll('.bh-persona-avatar svg')]; + const nodes = svgs.map((s) => s.querySelectorAll('*').length); + return { + frames: d.length, + p50: +q(0.5).toFixed(1), + p95: +q(0.95).toFixed(1), + max: +d[d.length - 1].toFixed(1), + long: d.filter((x) => x > 25).length, + rafPerSec: +((window.__raf - raf0 - ts.length) / (ms / 1000)).toFixed(0), + anims: document.getAnimations().length, + svgNodesAvg: nodes.length ? Math.round(nodes.reduce((a, b) => a + b, 0) / nodes.length) : 0, + svgNodesMax: Math.max(0, ...nodes), + }; + }, + ms, + scroll, + ); + const m1 = await metrics(); + const sec = ms / 1000; + const out = { + label, + ...r, + scriptMsPerSec: +(((m1.ScriptDuration - m0.ScriptDuration) * 1000) / sec).toFixed(1), + layoutPerSec: +((m1.LayoutCount - m0.LayoutCount) / sec).toFixed(1), + stylePerSec: +((m1.RecalcStyleCount - m0.RecalcStyleCount) / sec).toFixed(1), + taskMsPerSec: +(((m1.TaskDuration - m0.TaskDuration) * 1000) / sec).toFixed(1), + heapMB: +(m1.JSHeapUsedSize / 1048576).toFixed(1), + domNodes: m1.Nodes, + }; + console.log(JSON.stringify(out)); + return out; +} +const base = { size: 40, sameBot: false, intervalMs: 700 }; +const results = []; +const only = process.argv[2]; +const plan = + only === 'family' + ? [ + ['n32-pixel', { ...base, count: 32, family: 'illustrated' }], + ['n32-line', { ...base, count: 32, family: 'line' }], + ['n64-pixel', { ...base, count: 64, family: 'illustrated' }], + ['n64-line', { ...base, count: 64, family: 'line' }], + ] + : null; +if (only === 'scroll') { + await run('col32', { ...base, count: 32, column: true }); + await run('col256-top', { ...base, count: 256, column: true }); + await run('col256-scroll', { ...base, count: 256, column: true }, { scroll: true }); + await page.evaluate(() => window.scrollTo(0, 0)); + await browser.close(); + server.close(); + process.exit(0); +} +if (plan) { + for (const [l, c] of plan) await run(l, c); + await browser.close(); + server.close(); + process.exit(0); +} +for (const n of [1, 8, 32, 64, 128]) results.push(await run('n' + n, { ...base, count: n })); +results.push(await run('n32-idle-static', { ...base, count: 32, intervalMs: 0 })); +results.push(await run('n32-with-indicator', { ...base, count: 32, indicator: true })); +results.push( + await run('n32-static-indicator', { ...base, count: 32, intervalMs: 0, indicator: true }), +); +results.push(await run('n32-size96', { ...base, count: 32, size: 96 })); +results.push(await run('n32-samebot', { ...base, count: 32, sameBot: true })); +results.push(await run('n32-cpu4x', { ...base, count: 32 }, { throttle: 4 })); +results.push(await run('n64-cpu4x', { ...base, count: 64 }, { throttle: 4 })); +results.push(await run('n32-reduce', { ...base, count: 32 }, { reduce: true })); +results.push(await run('n32-stale', { ...base, count: 32 }, { stale: true })); +await cdp.send('Emulation.setCPUThrottlingRate', { rate: 1 }); +await page.evaluate(() => delete document.documentElement.dataset.botharnessActivity); +// lifecycle: mount/unmount cycles +for (let i = 0; i < 20; i++) { + await page.evaluate(() => + window.mountGrid({ count: 32, size: 40, sameBot: false, intervalMs: 150 }), + ); + await sleep(400); + await page.evaluate(() => window.unmountGrid()); +} +await sleep(1500); +await page.evaluate(() => gc()); +await sleep(300); +const after = await metrics(); +const raf0 = await page.evaluate(() => window.__raf); +await sleep(2000); +const raf1 = await page.evaluate(() => window.__raf); +const animsAfter = await page.evaluate(() => document.getAnimations().length); +console.log( + JSON.stringify({ + label: 'after-20-cycles-unmounted', + heapMB: +(after.JSHeapUsedSize / 1048576).toFixed(1), + domNodes: after.Nodes, + listeners: after.JSEventListeners, + rafCallsIn2s: raf1 - raf0, + anims: animsAfter, + }), +); +await browser.close(); +server.close(); diff --git a/docs/evidence/issue-757/measurements-after.jsonl b/docs/evidence/issue-757/measurements-after.jsonl new file mode 100644 index 0000000000..a7b7089dc1 --- /dev/null +++ b/docs/evidence/issue-757/measurements-after.jsonl @@ -0,0 +1,22 @@ +{"label":"n1","frames":360,"p50":16.7,"p95":16.7,"max":16.8,"long":0,"rafPerSec":23,"anims":1,"svgNodesAvg":387,"svgNodesMax":387,"scriptMsPerSec":13.1,"layoutPerSec":8,"stylePerSec":53.5,"taskMsPerSec":39.7,"heapMB":3,"domNodes":1203} +{"label":"n8","frames":360,"p50":16.7,"p95":16.8,"max":16.8,"long":0,"rafPerSec":61,"anims":8,"svgNodesAvg":395,"svgNodesMax":432,"scriptMsPerSec":56.4,"layoutPerSec":28.7,"stylePerSec":69.8,"taskMsPerSec":119,"heapMB":5.4,"domNodes":3289} +{"label":"n32","frames":360,"p50":16.7,"p95":16.7,"max":16.8,"long":0,"rafPerSec":122,"anims":20,"svgNodesAvg":249,"svgNodesMax":459,"scriptMsPerSec":114.8,"layoutPerSec":80.7,"stylePerSec":95.7,"taskMsPerSec":192,"heapMB":21,"domNodes":11142} +{"label":"n64","frames":360,"p50":16.7,"p95":16.7,"max":16.8,"long":0,"rafPerSec":122,"anims":43,"svgNodesAvg":245,"svgNodesMax":459,"scriptMsPerSec":169.5,"layoutPerSec":103.3,"stylePerSec":132.3,"taskMsPerSec":269,"heapMB":29.6,"domNodes":21180} +{"label":"n128","frames":352,"p50":16.7,"p95":16.8,"max":33.4,"long":9,"rafPerSec":120,"anims":74,"svgNodesAvg":211,"svgNodesMax":459,"scriptMsPerSec":234.8,"layoutPerSec":136.5,"stylePerSec":199.5,"taskMsPerSec":384.8,"heapMB":44.7,"domNodes":30598} +{"label":"n32-idle-static","frames":361,"p50":16.7,"p95":16.7,"max":16.8,"long":0,"rafPerSec":0,"anims":18,"svgNodesAvg":246,"svgNodesMax":432,"scriptMsPerSec":2.3,"layoutPerSec":2.5,"stylePerSec":60.3,"taskMsPerSec":41.5,"heapMB":4.1,"domNodes":35382} +{"label":"n32-with-indicator","frames":361,"p50":16.7,"p95":16.8,"max":16.8,"long":0,"rafPerSec":123,"anims":281,"svgNodesAvg":248,"svgNodesMax":458,"scriptMsPerSec":68.7,"layoutPerSec":85.5,"stylePerSec":96,"taskMsPerSec":400.1,"heapMB":19.9,"domNodes":11472} +{"label":"n32-static-indicator","frames":360,"p50":16.7,"p95":16.8,"max":16.8,"long":0,"rafPerSec":0,"anims":279,"svgNodesAvg":246,"svgNodesMax":432,"scriptMsPerSec":1.1,"layoutPerSec":2.5,"stylePerSec":60.3,"taskMsPerSec":193.6,"heapMB":4.3,"domNodes":8316} +{"label":"n32-size96","frames":358,"p50":16.7,"p95":16.8,"max":33.4,"long":2,"rafPerSec":122,"anims":64,"svgNodesAvg":345,"svgNodesMax":1923,"scriptMsPerSec":77.3,"layoutPerSec":86.3,"stylePerSec":96.8,"taskMsPerSec":162.2,"heapMB":32.9,"domNodes":43828} +{"label":"n32-samebot","frames":358,"p50":16.7,"p95":16.7,"max":33.4,"long":2,"rafPerSec":61,"anims":29,"svgNodesAvg":390,"svgNodesMax":426,"scriptMsPerSec":70.9,"layoutPerSec":55.3,"stylePerSec":100.3,"taskMsPerSec":114.7,"heapMB":33.5,"domNodes":44784} +{"label":"n32-cpu4x","frames":337,"p50":16.7,"p95":16.8,"max":66.7,"long":10,"rafPerSec":113,"anims":18,"svgNodesAvg":249,"svgNodesMax":459,"scriptMsPerSec":291.3,"layoutPerSec":76,"stylePerSec":91.5,"taskMsPerSec":535.8,"heapMB":37.5,"domNodes":15732} +{"label":"n64-cpu4x","frames":270,"p50":16.7,"p95":33.4,"max":149.9,"long":38,"rafPerSec":93,"anims":117,"svgNodesAvg":245,"svgNodesMax":459,"scriptMsPerSec":528.7,"layoutPerSec":88.7,"stylePerSec":118,"taskMsPerSec":884.1,"heapMB":43.9,"domNodes":35478} +{"label":"n32-reduce","frames":361,"p50":16.7,"p95":16.8,"max":16.8,"long":0,"rafPerSec":0,"anims":0,"svgNodesAvg":246,"svgNodesMax":432,"scriptMsPerSec":8.6,"layoutPerSec":1.5,"stylePerSec":1.5,"taskMsPerSec":20.1,"heapMB":19.7,"domNodes":24466} +{"label":"n32-stale","frames":361,"p50":16.7,"p95":16.7,"max":16.8,"long":0,"rafPerSec":0,"anims":0,"svgNodesAvg":246,"svgNodesMax":432,"scriptMsPerSec":8.5,"layoutPerSec":1.5,"stylePerSec":1.5,"taskMsPerSec":19.6,"heapMB":9.3,"domNodes":8059} +{"label":"after-20-cycles-unmounted","heapMB":4,"domNodes":16121,"listeners":133,"rafCallsIn2s":0,"anims":0} +{"label":"n32-pixel","frames":360,"p50":16.7,"p95":16.7,"max":16.8,"long":0,"rafPerSec":61,"anims":29,"svgNodesAvg":388,"svgNodesMax":438,"scriptMsPerSec":75,"layoutPerSec":55.3,"stylePerSec":100.7,"taskMsPerSec":119.6,"heapMB":14.5,"domNodes":17110} +{"label":"n32-line","frames":360,"p50":16.7,"p95":16.8,"max":16.8,"long":0,"rafPerSec":61,"anims":6,"svgNodesAvg":16,"svgNodesMax":21,"scriptMsPerSec":52.8,"layoutPerSec":59.8,"stylePerSec":87.8,"taskMsPerSec":100.4,"heapMB":13,"domNodes":633} +{"label":"n64-pixel","frames":356,"p50":16.7,"p95":16.8,"max":33.4,"long":4,"rafPerSec":61,"anims":58,"svgNodesAvg":386,"svgNodesMax":459,"scriptMsPerSec":162.8,"layoutPerSec":93.8,"stylePerSec":142.2,"taskMsPerSec":261.9,"heapMB":24.7,"domNodes":41604} +{"label":"n64-line","frames":360,"p50":16.7,"p95":16.7,"max":16.8,"long":0,"rafPerSec":61,"anims":12,"svgNodesAvg":16,"svgNodesMax":21,"scriptMsPerSec":102.2,"layoutPerSec":59.8,"stylePerSec":116.3,"taskMsPerSec":182.1,"heapMB":40.5,"domNodes":1241} +{"label":"col32","frames":360,"p50":16.7,"p95":16.7,"max":16.8,"long":0,"rafPerSec":122,"anims":13,"svgNodesAvg":247,"svgNodesMax":432,"scriptMsPerSec":62.9,"layoutPerSec":73.2,"stylePerSec":82.2,"taskMsPerSec":125.6,"heapMB":20.7,"domNodes":16094} +{"label":"col256-top","frames":341,"p50":16.7,"p95":16.8,"max":50.1,"long":11,"rafPerSec":116,"anims":37,"svgNodesAvg":212,"svgNodesMax":432,"scriptMsPerSec":115.3,"layoutPerSec":69.8,"stylePerSec":79,"taskMsPerSec":244.8,"heapMB":58.8,"domNodes":72591} +{"label":"col256-scroll","frames":334,"p50":16.7,"p95":16.8,"max":66.7,"long":11,"rafPerSec":96,"anims":35,"svgNodesAvg":212,"svgNodesMax":432,"scriptMsPerSec":119.4,"layoutPerSec":94.8,"stylePerSec":118,"taskMsPerSec":355.9,"heapMB":34.9,"domNodes":70133} diff --git a/docs/evidence/issue-757/measurements-before.jsonl b/docs/evidence/issue-757/measurements-before.jsonl new file mode 100644 index 0000000000..7b23d8be27 --- /dev/null +++ b/docs/evidence/issue-757/measurements-before.jsonl @@ -0,0 +1,16 @@ +{"label":"empty","heapMB":1.8,"domNodes":19,"listeners":133} +{"label":"n1","frames":360,"p50":16.7,"p95":16.7,"max":16.8,"long":0,"rafPerSec":23,"anims":1,"svgNodesAvg":486,"svgNodesMax":486,"scriptMsPerSec":15.1,"layoutPerSec":17.5,"stylePerSec":57.2,"taskMsPerSec":44.9,"heapMB":2.7,"domNodes":1398} +{"label":"n8","frames":361,"p50":16.7,"p95":16.7,"max":16.8,"long":0,"rafPerSec":415,"anims":8,"svgNodesAvg":505,"svgNodesMax":545,"scriptMsPerSec":125.8,"layoutPerSec":65.2,"stylePerSec":80.2,"taskMsPerSec":322.8,"heapMB":6.5,"domNodes":15191} +{"label":"n32","frames":344,"p50":16.7,"p95":16.8,"max":33.4,"long":17,"rafPerSec":1299,"anims":20,"svgNodesAvg":326,"svgNodesMax":765,"scriptMsPerSec":360.7,"layoutPerSec":119,"stylePerSec":145.5,"taskMsPerSec":796,"heapMB":29.6,"domNodes":39013} +{"label":"n64","frames":201,"p50":33.3,"p95":50,"max":83.4,"long":122,"rafPerSec":1565,"anims":37,"svgNodesAvg":322,"svgNodesMax":760,"scriptMsPerSec":457.9,"layoutPerSec":160,"stylePerSec":211,"taskMsPerSec":967.2,"heapMB":24.4,"domNodes":61260} +{"label":"n128","frames":74,"p50":66.7,"p95":233.4,"max":250,"long":69,"rafPerSec":1238,"anims":222,"svgNodesAvg":269,"svgNodesMax":804,"scriptMsPerSec":536.3,"layoutPerSec":254.7,"stylePerSec":365.2,"taskMsPerSec":1035.6,"heapMB":39.3,"domNodes":209476} +{"label":"n32-idle-static","frames":360,"p50":16.7,"p95":16.8,"max":16.8,"long":0,"rafPerSec":0,"anims":18,"svgNodesAvg":297,"svgNodesMax":535,"scriptMsPerSec":1.3,"layoutPerSec":2.5,"stylePerSec":60.2,"taskMsPerSec":23.1,"heapMB":4,"domNodes":9628} +{"label":"n32-with-indicator","frames":228,"p50":16.8,"p95":50,"max":83.4,"long":111,"rafPerSec":863,"anims":281,"svgNodesAvg":322,"svgNodesMax":794,"scriptMsPerSec":287.2,"layoutPerSec":106,"stylePerSec":126.2,"taskMsPerSec":975.7,"heapMB":40.5,"domNodes":65317} +{"label":"n32-static-indicator","frames":360,"p50":16.7,"p95":16.8,"max":16.8,"long":0,"rafPerSec":0,"anims":279,"svgNodesAvg":297,"svgNodesMax":535,"scriptMsPerSec":2.1,"layoutPerSec":2.5,"stylePerSec":60.3,"taskMsPerSec":352.3,"heapMB":4.3,"domNodes":9964} +{"label":"n32-size96","frames":309,"p50":16.7,"p95":33.3,"max":83.4,"long":30,"rafPerSec":1213,"anims":64,"svgNodesAvg":425,"svgNodesMax":2012,"scriptMsPerSec":384.3,"layoutPerSec":120.2,"stylePerSec":139,"taskMsPerSec":893.8,"heapMB":36.2,"domNodes":46755} +{"label":"n32-samebot","frames":268,"p50":16.7,"p95":33.4,"max":50.1,"long":84,"rafPerSec":1269,"anims":29,"svgNodesAvg":524,"svgNodesMax":743,"scriptMsPerSec":426.5,"layoutPerSec":111.7,"stylePerSec":126.5,"taskMsPerSec":893.9,"heapMB":18.6,"domNodes":69422} +{"label":"n32-cpu4x","frames":59,"p50":83.3,"p95":283.3,"max":316.6,"long":55,"rafPerSec":268,"anims":55,"svgNodesAvg":326,"svgNodesMax":773,"scriptMsPerSec":527.9,"layoutPerSec":71.3,"stylePerSec":95.7,"taskMsPerSec":1043.1,"heapMB":36.7,"domNodes":62624} +{"label":"n64-cpu4x","frames":23,"p50":166.7,"p95":616.6,"max":633.3,"long":23,"rafPerSec":258,"anims":37,"svgNodesAvg":327,"svgNodesMax":756,"scriptMsPerSec":617.5,"layoutPerSec":134.3,"stylePerSec":172.7,"taskMsPerSec":1067,"heapMB":25.2,"domNodes":72331} +{"label":"n32-reduce","frames":361,"p50":16.7,"p95":16.7,"max":16.8,"long":0,"rafPerSec":0,"anims":0,"svgNodesAvg":296,"svgNodesMax":535,"scriptMsPerSec":18.3,"layoutPerSec":41,"stylePerSec":83,"taskMsPerSec":45.1,"heapMB":19.5,"domNodes":22066} +{"label":"n32-stale","frames":360,"p50":16.7,"p95":16.8,"max":33.3,"long":1,"rafPerSec":0,"anims":0,"svgNodesAvg":296,"svgNodesMax":535,"scriptMsPerSec":27.2,"layoutPerSec":41,"stylePerSec":83,"taskMsPerSec":63,"heapMB":19.5,"domNodes":31642} +{"label":"after-20-cycles-unmounted","heapMB":3.9,"domNodes":17,"listeners":133,"rafCallsIn2s":0,"anims":0} diff --git a/docs/evidence/issue-757/mixed-sidebar.gif b/docs/evidence/issue-757/mixed-sidebar.gif new file mode 100644 index 0000000000..d862bf2b99 Binary files /dev/null and b/docs/evidence/issue-757/mixed-sidebar.gif differ diff --git a/docs/evidence/issue-757/real-dsh-path.json b/docs/evidence/issue-757/real-dsh-path.json new file mode 100644 index 0000000000..e475b3b5a3 --- /dev/null +++ b/docs/evidence/issue-757/real-dsh-path.json @@ -0,0 +1,78 @@ +[ + { + "step": "edit-cancel", + "ok": true, + "draftWrites": 0, + "revision": "d448e288de9c" + }, + { + "step": "edit-save-read", + "ok": true, + "hair": "ponytail", + "saveWrites": 1, + "revision": "ed94f1823e12" + }, + { + "step": "same-identity-after-save", + "ok": true, + "bindings": ["sidebar@34", "header@22", "profile@64", "editor@160"] + }, + { + "step": "approval-frames-no-per-frame-rpc", + "ok": true, + "frames": { + "count": 239, + "p50": 16.69999999999891, + "p95": 16.799999999999272, + "max": 16.80000000000109 + }, + "rpcInWindow": 2, + "seconds": 4.1, + "methods": ["botharness/profileUsage"] + }, + { + "step": "real-work", + "ok": true, + "lastReply": [ + "read 依然成功(notes.txt = “avatar mixed family acceptance”),但 `sleep 12 && echo AVATAR_757_OK` 同样依然被拒(“Path is outside this Session's authorized workspace”),AVATAR_757_OK 没有输出。" + ] + }, + { + "step": "reload", + "ok": true, + "bindings": ["sidebar@34", "header@22", "profile@64", "editor@160"] + }, + { + "step": "disconnect-stale", + "ok": true, + "staleAvatarAnimations": 0 + }, + { + "step": "host-restart", + "ok": true, + "bindings": ["sidebar@34", "header@22", "profile@64", "editor@160"], + "revision": "ed94f1823e12" + }, + { + "step": "round-trip-and-malformed", + "ok": true, + "rejected": { + "unknown part": true, + "partial hair split": true, + "missing range": true, + "range overflow": true, + "non-integer range": true, + "extra key": true, + "bad color": true, + "future schema": true, + "not an object": true + }, + "detailedRoundTrip": true, + "restoredHair": "ponytail" + }, + { + "step": "mixed-sidebar", + "ok": true, + "families": ["pixel", "line", "image"] + } +] diff --git a/docs/evidence/issue-757/real-work.gif b/docs/evidence/issue-757/real-work.gif new file mode 100644 index 0000000000..c2bcf6e263 Binary files /dev/null and b/docs/evidence/issue-757/real-work.gif differ diff --git a/docs/evidence/issue-757/recognition-light-dark.png b/docs/evidence/issue-757/recognition-light-dark.png new file mode 100644 index 0000000000..5c4a60ef50 Binary files /dev/null and b/docs/evidence/issue-757/recognition-light-dark.png differ diff --git a/packages/client/package.json b/packages/client/package.json index c61757f0a0..3248ce5f09 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -20,7 +20,7 @@ "dependencies": { "@blobatar/react": "^2.7.0", "@botharness/botui-core": "0.3.0", - "@botharness/pixel-morph": "0.1.0", + "@botharness/pixel-morph": "0.2.0", "blobatar": "^2.7.0", "driver.js": "1.4.0", "morphicons": "1.7.1" diff --git a/packages/client/src/client/illustrated-avatar.tsx b/packages/client/src/client/illustrated-avatar.tsx index 927e8fdce4..2c5dae736a 100644 --- a/packages/client/src/client/illustrated-avatar.tsx +++ b/packages/client/src/client/illustrated-avatar.tsx @@ -10,7 +10,7 @@ import { type PixelCell, type PixelSymbol, } from '../../../core/src/bots/avatar-appearance.js'; -import { morphPixels, pixelMarkup, type PixelMorphRun } from '@botharness/pixel-morph'; +import { morphPixels, pixelPathMarkup, type PixelMorphRun } from '@botharness/pixel-morph'; import type { Sampled } from 'morphicons'; import { lineMorphD, @@ -102,6 +102,7 @@ interface LineShown { export const PIXEL_MORPH_MS = 800; export const PIXEL_SYMBOL_HOLD_MS = 500; +export const PIXEL_FRAME_MS = 50; interface PixelShown { key?: PixelSymbol | 'face'; @@ -160,6 +161,7 @@ export function IllustratedAvatar({ ); const line = useRef({ velocity: 0, since: 0 }); const pixel = useRef({ since: 0 }); + const seen = useRef(true); const mount = useMountedResource( (node) => { const morphPath = node.querySelector('path[data-avatar-transition]'); @@ -169,7 +171,7 @@ export function IllustratedAvatar({ const pixelGroup = node.querySelector('[data-avatar-pixel-morph]'); if (!head || !gaze || !blink || typeof head.animate !== 'function') return; const animations = new Set(); - let visible = true; + let visible = seen.current; let disposed = false; let run: { run: LineMorphRun; key: PixelSymbol | 'face' } | undefined; let lineTimer: ReturnType | undefined; @@ -299,7 +301,7 @@ export function IllustratedAvatar({ svg?.removeAttribute('data-pixel-cover'); return; } - pixelGroup.innerHTML = pixelMarkup(cells ?? cellsFor(key)); + pixelGroup.innerHTML = pixelPathMarkup(cells ?? cellsFor(key)); svg?.setAttribute('data-pixel-cover', ''); }; const previous = pixel.current; @@ -316,7 +318,10 @@ export function IllustratedAvatar({ draw(previous.key, from); const start = () => { pixelTimer = undefined; - const run = morphPixels(pixelGroup, from, cellsFor(target), PIXEL_MORPH_MS); + const run = morphPixels(pixelGroup, from, cellsFor(target), PIXEL_MORPH_MS, { + frameMs: PIXEL_FRAME_MS, + markup: pixelPathMarkup, + }); pixelRun = { run, key: target }; void run.finished.then((done) => { if (!done) return; @@ -332,9 +337,11 @@ export function IllustratedAvatar({ }; const loop = (target: Element, frames: Keyframe[], duration: number) => animations.add(target.animate(frames, { duration, iterations: Infinity })); + const settled = () => animations.size === 0 && !run && !lineTimer && !pixelRun; const sync = () => { - const start = getComputedStyle(head).transform; - const gazeStart = getComputedStyle(gaze).transform; + const moving = !settled(); + const start = moving ? getComputedStyle(head).transform : 'none'; + const gazeStart = moving ? getComputedStyle(gaze).transform : 'none'; stop(); head.style.transform = 'none'; gaze.style.transform = 'none'; @@ -417,7 +424,7 @@ export function IllustratedAvatar({ : new IntersectionObserver((entries) => { const next = entries.some((entry) => entry.isIntersecting); if (next === visible) return; - visible = next; + seen.current = visible = next; sync(); }); observer?.observe(node); @@ -430,13 +437,17 @@ export function IllustratedAvatar({ sync(); return () => { disposed = true; - const pose = getComputedStyle(head).transform; - const gazePose = getComputedStyle(gaze).transform; - const headOpacity = getComputedStyle(head).opacity; - stop(); - head.style.transform = pose; - gaze.style.transform = gazePose; - head.style.opacity = headOpacity; + if (settled()) { + stop(); + } else { + const pose = getComputedStyle(head).transform; + const gazePose = getComputedStyle(gaze).transform; + const headOpacity = getComputedStyle(head).opacity; + stop(); + head.style.transform = pose; + gaze.style.transform = gazePose; + head.style.opacity = headOpacity; + } observer?.disconnect(); motion.disconnect(); document.removeEventListener('visibilitychange', sync); diff --git a/packages/client/src/client/line-morph.ts b/packages/client/src/client/line-morph.ts index 1db70f4ab5..b881167e53 100644 --- a/packages/client/src/client/line-morph.ts +++ b/packages/client/src/client/line-morph.ts @@ -60,6 +60,40 @@ export function lineMorphD(shape: readonly Sampled[]): string { ); } +const tickers = new Set<(time: number) => void>(); +let loopId = 0; +let looping = false; + +function loop(time: number): void { + loopId = 0; + looping = true; + for (const tick of [...tickers]) { + try { + tick(time); + } catch (error) { + tickers.delete(tick); + queueMicrotask(() => { + throw error; + }); + } + } + looping = false; + if (tickers.size > 0) loopId = requestAnimationFrame(loop); +} + +function addTicker(tick: (time: number) => void): void { + tickers.add(tick); + if (!looping && loopId === 0) loopId = requestAnimationFrame(loop); +} + +function removeTicker(tick: (time: number) => void): void { + tickers.delete(tick); + if (tickers.size === 0 && loopId !== 0) { + cancelAnimationFrame(loopId); + loopId = 0; + } +} + export function morphLinePath( path: SVGPathElement, from: readonly Sampled[], @@ -75,7 +109,6 @@ export function morphLinePath( motion.config(spring.k, spring.c); motion.v = velocity; motion.start(); - let frame = 0; let last = -1; let settle: (done: boolean) => void = () => undefined; const finished = new Promise((resolve) => { @@ -98,23 +131,21 @@ export function morphLinePath( motion.x = 1; motion.v = 0; render(); - frame = 0; + removeTicker(tick); settle(true); return; } render(); - frame = requestAnimationFrame(tick); }; render(); - frame = requestAnimationFrame(tick); + addTicker(tick); return { finished, current: () => out.map((pts, index) => ({ pts: Float64Array.from(pts), closed: closed[index]! })), velocity: () => motion.v, cancel: () => { - if (frame) cancelAnimationFrame(frame); - frame = 0; + removeTicker(tick); settle(false); }, }; diff --git a/packages/client/test/illustrated-avatar.test.ts b/packages/client/test/illustrated-avatar.test.ts index 0288e416e7..181d0dab62 100644 --- a/packages/client/test/illustrated-avatar.test.ts +++ b/packages/client/test/illustrated-avatar.test.ts @@ -10,7 +10,7 @@ import { } from '../../core/src/bots/avatar-appearance.js'; import { lineMorphD, sampleLineSymbol } from '../src/client/line-morph.js'; import { PIXEL_MORPH_MS, PIXEL_SYMBOL_HOLD_MS } from '../src/client/illustrated-avatar.js'; -import { pixelMarkup as rawPixelMarkup } from '@botharness/pixel-morph'; +import { pixelPathMarkup as rawPixelMarkup } from '@botharness/pixel-morph'; const pixelMarkup = (...args: Parameters) => { const group = document.createElementNS('http://www.w3.org/2000/svg', 'g'); @@ -459,3 +459,78 @@ it('morphs the whole pixel Avatar between tool symbols, holds each briefly and s node.remove(); } }); + +it('keeps an Avatar scrolled out of view still across updates and resumes motion when it returns', async () => { + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + const node = document.createElement('div'); + document.body.append(node); + const root = createRoot(node); + const animate = vi.fn(() => ({ cancel: vi.fn(), finished: Promise.resolve() })); + const previous = Object.getOwnPropertyDescriptor(Element.prototype, 'animate'); + Object.defineProperty(Element.prototype, 'animate', { configurable: true, value: animate }); + Object.defineProperty(document, 'hidden', { configurable: true, value: false }); + const frames = new Map(); + let nextFrame = 0; + vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { + frames.set(++nextFrame, callback); + return nextFrame; + }); + vi.stubGlobal('cancelAnimationFrame', (id: number) => frames.delete(id)); + const observers: ((entries: { isIntersecting: boolean }[]) => void)[] = []; + vi.stubGlobal( + 'IntersectionObserver', + class { + constructor(callback: (entries: { isIntersecting: boolean }[]) => void) { + observers.push(callback); + } + observe() {} + disconnect() {} + }, + ); + const scroll = (isIntersecting: boolean) => + act(async () => observers.at(-1)!([{ isIntersecting }])); + const render = (toolName: string) => + act(async () => + root.render( + createElement(PersonaBotAvatar, { + personaBotId: 'ada', + name: 'Ada', + appearance: { recipe: DEFAULT_ILLUSTRATED_RECIPE, revision: 'a'.repeat(64) }, + size: 40, + state: 'working', + activity: { + effect: 'generic-working' as const, + toolKind: 'other' as const, + toolName, + startedAt: 0, + activeToolCount: 1, + }, + }), + ), + ); + const hair = DEFAULT_ILLUSTRATED_RECIPE.hairColor; + const drawn = () => node.querySelector('[data-avatar-pixel-morph]')!.innerHTML; + try { + await render('edit'); + await scroll(false); + animate.mockClear(); + await render('bash'); + await render('grep'); + await act(() => new Promise((resolve) => setTimeout(resolve, PIXEL_SYMBOL_HOLD_MS + 40))); + expect(frames.size).toBe(0); + expect(animate).not.toHaveBeenCalled(); + expect(drawn()).toBe(pixelMarkup(pixelSymbolCells('search', hair))); + await scroll(true); + expect(animate).toHaveBeenCalled(); + await render('edit'); + await act(() => new Promise((resolve) => setTimeout(resolve, PIXEL_SYMBOL_HOLD_MS + 40))); + expect(frames.size).toBe(1); + } finally { + await act(() => root.unmount()); + vi.unstubAllGlobals(); + if (previous) Object.defineProperty(Element.prototype, 'animate', previous); + else Reflect.deleteProperty(Element.prototype, 'animate'); + Reflect.deleteProperty(document, 'hidden'); + node.remove(); + } +}); diff --git a/packages/client/test/line-morph.test.ts b/packages/client/test/line-morph.test.ts new file mode 100644 index 0000000000..6423271103 --- /dev/null +++ b/packages/client/test/line-morph.test.ts @@ -0,0 +1,72 @@ +// @vitest-environment jsdom +import { afterEach, expect, it, vi } from 'vitest'; +import { LINE_TOOL_SYMBOLS } from '../../core/src/bots/avatar-appearance.js'; +import { morphLinePath, sampleLineSymbol } from '../src/client/line-morph.js'; + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +it('drives every running line morph from one shared animation frame', async () => { + const callbacks: FrameRequestCallback[] = []; + vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => + callbacks.push(callback), + ); + vi.stubGlobal('cancelAnimationFrame', () => undefined); + const from = sampleLineSymbol(LINE_TOOL_SYMBOLS.search, 1); + const to = sampleLineSymbol(LINE_TOOL_SYMBOLS.edit, 1); + const paths = Array.from({ length: 8 }, () => + document.createElementNS('http://www.w3.org/2000/svg', 'path'), + ); + const runs = paths.map((path) => morphLinePath(path, from, to, { k: 170, c: 26 }, 0)); + expect(callbacks).toHaveLength(1); + runs[0]!.cancel(); + await expect(runs[0]!.finished).resolves.toBe(false); + for (let time = 0; callbacks.length && time < 5000; time += 1000 / 60) { + expect(callbacks).toHaveLength(1); + callbacks.shift()!(time); + } + expect(callbacks).toHaveLength(0); + await expect(Promise.all(runs.slice(1).map((run) => run.finished))).resolves.toEqual( + runs.slice(1).map(() => true), + ); +}); + +it('keeps the shared loop alive when one morph throws and never runs two frame chains', async () => { + const callbacks: FrameRequestCallback[] = []; + vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => + callbacks.push(callback), + ); + vi.stubGlobal('cancelAnimationFrame', () => undefined); + const reported: unknown[] = []; + vi.stubGlobal('queueMicrotask', (task: () => void) => { + try { + task(); + } catch (error) { + reported.push(error); + } + }); + const from = sampleLineSymbol(LINE_TOOL_SYMBOLS.search, 1); + const to = sampleLineSymbol(LINE_TOOL_SYMBOLS.edit, 1); + const path = () => document.createElementNS('http://www.w3.org/2000/svg', 'path'); + const spring = { k: 170, c: 26 }; + let follow: ReturnType | undefined; + const failing = morphLinePath(path(), from, to, spring, 0, () => { + throw new Error('near failed'); + }); + const handing = morphLinePath(path(), from, to, spring, 0, () => { + handing.cancel(); + follow = morphLinePath(path(), to, from, spring, 0); + }); + void failing; + for (let time = 0; callbacks.length && time < 5000; time += 1000 / 60) { + expect(callbacks).toHaveLength(1); + callbacks.shift()!(time); + } + expect(reported).toHaveLength(1); + expect(follow).toBeDefined(); + await expect(follow!.finished).resolves.toBe(true); + const later = morphLinePath(path(), from, to, spring, 0); + expect(callbacks).toHaveLength(1); + later.cancel(); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0133bd3b0a..392c7328dd 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -394,8 +394,8 @@ importers: specifier: 0.3.0 version: 0.3.0 '@botharness/pixel-morph': - specifier: 0.1.0 - version: 0.1.0 + specifier: 0.2.0 + version: 0.2.0 blobatar: specifier: ^2.7.0 version: 2.7.0(react@18.3.1) @@ -1111,6 +1111,9 @@ packages: '@botharness/pixel-morph@0.1.0': resolution: {integrity: sha512-LHVZsfjRrBeWLwMjZ+ubeVTHt1lTTTPXzkCeGi7h2mwNjhlXOZZFOBojJts82PJsUaVAQPuNrjOOV3hU1M3q4A==} + '@botharness/pixel-morph@0.2.0': + resolution: {integrity: sha512-Mi8lIZJdYaBub6qYNMwqgFP88RkMEJFQOAUVVAsL/yCg8j9lw56EtIgYCHaFrIApx4bvs3eIwodwQAYd5OpLPg==} + '@braintree/sanitize-url@7.1.2': resolution: {integrity: sha512-jigsZK+sMF/cuiB7sERuo9V7N9jx+dhmHHnQyDSVdpZwVutaBu7WvNYqMDLSgFgfB30n452TP3vjDAvFC973mA==} @@ -10656,6 +10659,8 @@ snapshots: '@botharness/pixel-morph@0.1.0': {} + '@botharness/pixel-morph@0.2.0': {} + '@braintree/sanitize-url@7.1.2': {} '@bruits/satteri-darwin-arm64@0.10.5': diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 3a8d16d783..4c4ce5e413 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -310,3 +310,4 @@ minimumReleaseAgeExclude: - '@deepseek-ai/dsh-otel@0.2.0-rc.1' - '@botharness/pixel-avatar@0.1.0' - '@botharness/pixel-morph@0.1.0' + - '@botharness/pixel-morph@0.2.0'