@linxin666/dsh-pet 0.4.6 → 0.4.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -74,7 +74,7 @@ export const BINDER_RETRY_MS = 250;
74
74
  const BINDER_ATTEMPTS = 24;
75
75
  /** The snapshot an unresolved (or resolvable-but-unbound) form publishes. */
76
76
  function pendingSnapshot(status) {
77
- return { status, value: undefined, base: undefined, user: undefined, revision: undefined, writable: false, mode: 'host' };
77
+ return { status, value: undefined, base: undefined, user: undefined, revision: undefined, writable: false };
78
78
  }
79
79
  /**
80
80
  * A ConfigForm that late-binds to the family settings binder.
@@ -14,9 +14,11 @@
14
14
  * - Canvas bitmap buffer (default where createImageBitmap/fetch/2D context
15
15
  * exist): frames are decoded once into an ImageBitmap on demand, with a
16
16
  * bounded look-ahead window over the playing track, and drawn onto one
17
- * <canvas> - steady-state playback issues zero DOM mutations and zero
18
- * re-decodes (measured hotspot: swapping <img>.src per frame drove image
19
- * decode + invalidation every tick).
17
+ * <canvas>. Steady-state playback issues zero DOM mutations and re-decodes
18
+ * only what the retention budget evicted: decoded frames are held under
19
+ * MAX_RETAINED_BYTES, so a long-lived pet that plays every track of every
20
+ * skin cannot pin every bitmap for the life of the page (measured hotspot:
21
+ * swapping <img>.src per frame drove image decode + invalidation every tick).
20
22
  * - Classic <img> fallback (jsdom/tests or missing APIs): identical to the
21
23
  * historical behavior - cache-warm Image elements plus guarded src swaps,
22
24
  * so environments without modern decoding keep working unchanged.
@@ -1 +1 @@
1
- {"version":3,"file":"frames2d.d.ts","sourceRoot":"","sources":["../../../../src/client/renderers/frames2d.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,OAAO,EAA4B,KAAK,WAAW,EAA2B,KAAK,iBAAiB,EAAE,MAAM,6BAA6B,CAAA;AACzI,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAA;AAEnD,oEAAoE;AACp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IAChF,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,CAAA;IACzC;;;;OAIG;IACH,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,CAAA;IAC7C,2DAA2D;IAC3D,YAAY,IAAI,MAAM,CAAA;CACvB;AA+HD,eAAO,MAAM,gBAAgB,EAAE,WAAW,CAAC,iBAAiB,CA2Y3D,CAAA"}
@@ -14,9 +14,11 @@
14
14
  * - Canvas bitmap buffer (default where createImageBitmap/fetch/2D context
15
15
  * exist): frames are decoded once into an ImageBitmap on demand, with a
16
16
  * bounded look-ahead window over the playing track, and drawn onto one
17
- * <canvas> - steady-state playback issues zero DOM mutations and zero
18
- * re-decodes (measured hotspot: swapping <img>.src per frame drove image
19
- * decode + invalidation every tick).
17
+ * <canvas>. Steady-state playback issues zero DOM mutations and re-decodes
18
+ * only what the retention budget evicted: decoded frames are held under
19
+ * MAX_RETAINED_BYTES, so a long-lived pet that plays every track of every
20
+ * skin cannot pin every bitmap for the life of the page (measured hotspot:
21
+ * swapping <img>.src per frame drove image decode + invalidation every tick).
20
22
  * - Classic <img> fallback (jsdom/tests or missing APIs): identical to the
21
23
  * historical behavior - cache-warm Image elements plus guarded src swaps,
22
24
  * so environments without modern decoding keep working unchanged.
@@ -26,6 +28,19 @@
26
28
  import { PET_RENDERER_API_VERSION } from "../../contracts/renderer.js";
27
29
  /** Stall watchdog period: a looping track stuck longer re-kicks its chain. */
28
30
  const WATCHDOG_MS = 1200;
31
+ /**
32
+ * Retention budget for decoded frame bitmaps, in bytes.
33
+ *
34
+ * The budget is expressed in bytes rather than in frames because a frame's
35
+ * decoded footprint is `width * height * 4` and published pets differ by more
36
+ * than an order of magnitude (a 512x683 frame is 1.33 MB, a 128x128 frame is
37
+ * 64 KB): a frame count would be either useless for small atlases or too tight
38
+ * for large ones. 128 MiB holds this repository's longest shipped track (78
39
+ * frames, 104 MB) in full, so a running loop still re-decodes nothing, while
40
+ * capping a pet that played every track of every skin at roughly a tenth of
41
+ * the ~1.7 GB the unbounded memo reached.
42
+ */
43
+ const MAX_RETAINED_BYTES = 128 * 1024 * 1024;
29
44
  function isRecord(value) {
30
45
  return typeof value === 'object' && value !== null && !Array.isArray(value);
31
46
  }
@@ -108,6 +123,22 @@ function validateFrames2dConfig(config) {
108
123
  }
109
124
  return { tracks, phases: phases, ...(skins === undefined ? {} : { skins }) };
110
125
  }
126
+ /**
127
+ * Release one decoded frame. `close()` is browser-only and idempotent, so the
128
+ * call is guarded for exotic hosts and for frames that were already released;
129
+ * the `<img>` fallback has no close, where dropping the reference is the
130
+ * release.
131
+ */
132
+ function releaseFrame(frame) {
133
+ if (frame === undefined)
134
+ return;
135
+ try {
136
+ const maybeClose = frame.source.close;
137
+ if (typeof maybeClose === 'function')
138
+ maybeClose.call(frame.source);
139
+ }
140
+ catch { /* already released */ }
141
+ }
111
142
  export const frames2dRenderer = {
112
143
  id: 'frames2d',
113
144
  apiVersion: PET_RENDERER_API_VERSION,
@@ -155,11 +186,18 @@ export const frames2dRenderer = {
155
186
  img.style.pointerEvents = 'none';
156
187
  ctx.container.appendChild(img);
157
188
  }
158
- // Decode cache: one concurrent decode per URL, memoized forever (frames
159
- // are tiny same-origin webp files; failures resolve undefined and keep
160
- // the last painted frame instead of breaking playback).
189
+ // Decode cache: one concurrent decode per URL, retained under a decoded
190
+ // byte budget. The historical map memoized every decoded frame forever, so
191
+ // a pet that had played all of its tracks (every skin) kept every bitmap
192
+ // alive for the life of the page: a shipped three-skin pet measures 1276
193
+ // frames at 512x683 RGBA, about 1.7 GB, growing monotonically. Entries now
194
+ // carry their decoded footprint, sit in Map insertion order (delete + set
195
+ // is an LRU touch) and the least recently used ones outside the playing
196
+ // window are closed once MAX_RETAINED_BYTES is crossed. A failed decode
197
+ // still resolves undefined and leaves the memo, so a transient fetch error
198
+ // retries instead of sticking.
161
199
  const decoding = new Map();
162
- const decodedAll = [];
200
+ let retainedBytes = 0;
163
201
  // All frame fetches funnel through a small pool. Full-library warm passes
164
202
  // on large pets fire 1100+ requests at once, which trips the browser's
165
203
  // in-flight request limit (net::ERR_INSUFFICIENT_RESOURCES) and fails
@@ -210,27 +248,96 @@ export const frames2dRenderer = {
210
248
  frameQueue.unshift(frameQueue.splice(index, 1)[0]);
211
249
  }
212
250
  const cached = decoding.get(url);
213
- if (cached !== undefined)
214
- return cached;
251
+ if (cached !== undefined) {
252
+ // LRU touch: a hit means playback just asked for this frame, so it must
253
+ // not be the next victim. Re-inserting the same entry only reorders.
254
+ decoding.delete(url);
255
+ decoding.set(url, cached);
256
+ return cached.job;
257
+ }
215
258
  let release;
216
259
  const gate = new Promise((resolve) => { release = resolve; });
217
260
  const job = gate.then(() => (disposed ? undefined : decodeFrame(url)));
218
- job.then((frame) => { if (frame === undefined)
219
- decoding.delete(url); }, () => decoding.delete(url));
261
+ const entry = { job };
262
+ job.then((frame) => {
263
+ if (frame === undefined) {
264
+ decoding.delete(url);
265
+ return;
266
+ }
267
+ // A decode that lands after dispose is closed here: nothing can close
268
+ // it later, and the map was already drained.
269
+ if (disposed) {
270
+ releaseFrame(frame);
271
+ decoding.delete(url);
272
+ return;
273
+ }
274
+ entry.frame = frame;
275
+ entry.bytes = frame.width * frame.height * 4;
276
+ retainedBytes += entry.bytes;
277
+ // Only a resolved frame is evictable, and its decoded size is known
278
+ // only now, so the budget is enforced here.
279
+ enforceRetentionBudget();
280
+ }, () => decoding.delete(url));
220
281
  void job.finally(() => {
221
282
  activeFrames -= 1;
222
283
  pumpFrames();
223
284
  });
224
- decoding.set(url, job);
225
- decodedAll.push(job.then(() => undefined, () => undefined));
226
- const entry = { url, release };
285
+ decoding.set(url, entry);
286
+ const queued = { url, release };
227
287
  if (jump)
228
- frameQueue.unshift(entry);
288
+ frameQueue.unshift(queued);
229
289
  else
230
- frameQueue.push(entry);
290
+ frameQueue.push(queued);
231
291
  pumpFrames();
232
292
  return job;
233
293
  };
294
+ /**
295
+ * Release decoded bitmaps until the retained footprint is back under
296
+ * MAX_RETAINED_BYTES. Two properties keep this from breaking playback:
297
+ *
298
+ * - The playing track's look-ahead window, plus the frame a draw is waiting
299
+ * on, are never released. Releasing one would hand a closed bitmap to
300
+ * `drawImage`, and re-decoding it would stall the next tick.
301
+ * - Frames of any other track go first. That is what keeps a running loop
302
+ * warm under a budget smaller than two whole tracks: eviction reclaims the
303
+ * track the pet left instead of eating the cycle it is playing.
304
+ *
305
+ * When the protected window alone exceeds the budget nothing is released —
306
+ * a pet whose frames are that large cannot be bounded further without
307
+ * breaking playback, and the overshoot is then exactly one window.
308
+ */
309
+ function enforceRetentionBudget() {
310
+ if (retainedBytes <= MAX_RETAINED_BYTES)
311
+ return;
312
+ const def = config.tracks[track];
313
+ const playing = new Set(def === undefined ? [] : def.frames);
314
+ const protectedUrls = new Set();
315
+ if (pinned !== undefined)
316
+ protectedUrls.add(pinned);
317
+ if (def !== undefined) {
318
+ const end = Math.min(def.frames.length, frameIndex + 1 + PREFETCH_AHEAD);
319
+ for (let index = frameIndex; index < end; index += 1) {
320
+ const url = def.frames[index];
321
+ if (url !== undefined)
322
+ protectedUrls.add(url);
323
+ }
324
+ }
325
+ // Pass 1 reclaims frames of tracks the pet is not playing; pass 2 is the
326
+ // backstop for a single track larger than the whole budget.
327
+ for (const foreignOnly of [true, false]) {
328
+ for (const [url, entry] of decoding) {
329
+ if (retainedBytes <= MAX_RETAINED_BYTES)
330
+ return;
331
+ if (entry.bytes === undefined || protectedUrls.has(url))
332
+ continue;
333
+ if (foreignOnly && playing.has(url))
334
+ continue;
335
+ releaseFrame(entry.frame);
336
+ retainedBytes -= entry.bytes;
337
+ decoding.delete(url);
338
+ }
339
+ }
340
+ }
234
341
  /**
235
342
  * Bounded look-ahead window: decode only the frames playback is about to
236
343
  * need. The historical warm pass decoded every frame of every track up
@@ -265,6 +372,9 @@ export const frames2dRenderer = {
265
372
  let baseIdle = config.phases.idle;
266
373
  let drawToken = 0;
267
374
  let lastDrawnUrl;
375
+ // The frame a draw is currently awaiting. Eviction must not release it:
376
+ // the callback below holds the bitmap and would draw a closed one.
377
+ let pinned;
268
378
  const trackForPhase = (phase) => {
269
379
  const mapped = config.phases[phase];
270
380
  if (mapped === undefined)
@@ -277,7 +387,10 @@ export const frames2dRenderer = {
277
387
  if (context2d === null || canvas === null)
278
388
  return;
279
389
  const myToken = ++drawToken;
390
+ pinned = url;
280
391
  void loadFrame(url, true).then((frame) => {
392
+ if (pinned === url)
393
+ pinned = undefined;
281
394
  if (disposed || frame === undefined || myToken !== drawToken)
282
395
  return;
283
396
  if (lastDrawnUrl === url)
@@ -292,7 +405,8 @@ export const frames2dRenderer = {
292
405
  context2d.clearRect(0, 0, canvas.width, canvas.height);
293
406
  }
294
407
  context2d.drawImage(frame.source, 0, 0);
295
- }).catch(() => { });
408
+ }).catch(() => { if (pinned === url)
409
+ pinned = undefined; /* keep last frame */ });
296
410
  };
297
411
  const show = (trackId, index) => {
298
412
  const def = config.tracks[trackId];
@@ -393,24 +507,16 @@ export const frames2dRenderer = {
393
507
  clearTimeout(timer);
394
508
  if (watchdog !== undefined)
395
509
  clearInterval(watchdog);
396
- // Release decoded bitmaps after pending decodes settle; close() is
397
- // browser-only, so guard it for exotic hosts. Queued-but-unstarted
398
- // frames release immediately as no-ops so the settle barrier drains.
510
+ // Release every retained bitmap and drain the pool. Queued-but-unstarted
511
+ // frames resolve as no-ops (the gate skips decodeFrame once disposed), and
512
+ // a decode that lands after this loop is closed by the resolution guard
513
+ // above, so teardown leaves nothing pending and nothing retained.
399
514
  for (const queued of frameQueue.splice(0))
400
515
  queued.release();
401
- void Promise.allSettled(decodedAll).then(() => {
402
- for (const job of decoding.values()) {
403
- void job.then((frame) => {
404
- try {
405
- const maybeClose = frame?.source?.close;
406
- if (typeof maybeClose === 'function' && frame !== undefined)
407
- maybeClose.call(frame.source);
408
- }
409
- catch { /* already released */ }
410
- }).catch(() => { });
411
- }
412
- decoding.clear();
413
- });
516
+ for (const entry of decoding.values())
517
+ releaseFrame(entry.frame);
518
+ decoding.clear();
519
+ retainedBytes = 0;
414
520
  canvas?.remove();
415
521
  img?.remove();
416
522
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@linxin666/dsh-pet",
3
3
  "description": "Multi-pet companion plugin for the dsh web GUI: a registry-driven floating pet that reacts to model activity, with per-pet naming, petting/feeding interactions and an affinity score",
4
- "version": "0.4.6",
4
+ "version": "0.4.7",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -25,10 +25,6 @@
25
25
  "types": "./lib/types/index.d.ts",
26
26
  "default": "./lib/index.js"
27
27
  },
28
- "./invariant": {
29
- "types": "./lib/types/invariant.d.ts",
30
- "default": "./lib/invariant.js"
31
- },
32
28
  "./client": {
33
29
  "types": "./lib/types/client/index.d.ts",
34
30
  "default": "./lib/client.js"
@@ -54,7 +50,7 @@
54
50
  "license": "Apache-2.0",
55
51
  "dsh": {
56
52
  "engines": {
57
- "dsh": ">=0.1.7-rc.1"
53
+ "dsh": ">=0.2.1-rc.2"
58
54
  },
59
55
  "bundle": {
60
56
  "patch": "./cordis.patch.yml"
@@ -71,37 +67,37 @@
71
67
  }
72
68
  },
73
69
  "dependencies": {
74
- "@deepseek-ai/schemastery": "^3.18.4",
70
+ "@deepseek-ai/schemastery": "~3.18.5",
75
71
  "clsx": "^2.1.1"
76
72
  },
77
73
  "peerDependencies": {
78
- "@deepseek-ai/dsh": ">=0.1.7-rc.1",
74
+ "@deepseek-ai/dsh": ">=0.2.1-rc.2",
79
75
  "react": "^18.2.0",
80
76
  "react-dom": "^18.2.0"
81
77
  },
82
78
  "devDependencies": {
83
- "@deepseek-ai/cordis": "^4.0.4",
84
- "@deepseek-ai/dsh-agent": "^0.1.7-rc.1",
85
- "@deepseek-ai/dsh-api-remotes": "^0.1.7-rc.1",
86
- "@deepseek-ai/dsh-api-session-controller": "^0.1.7-rc.1",
87
- "@deepseek-ai/dsh-api-workspace-controller": "^0.1.7-rc.1",
88
- "@deepseek-ai/dsh-client-locale": "^0.1.7-rc.1",
89
- "@deepseek-ai/dsh-client-store": "^0.1.7-rc.1",
90
- "@deepseek-ai/dsh-client-ui-conversation": "^0.1.7-rc.1",
91
- "@deepseek-ai/dsh-client-ui-renderer": "^0.1.7-rc.1",
92
- "@deepseek-ai/dsh-client-ui-settings": "^0.1.7-rc.1",
93
- "@deepseek-ai/dsh-client-ui-slots": "^0.1.7-rc.1",
94
- "@deepseek-ai/dsh-client-ui-workspace": "^0.1.7-rc.1",
95
- "@deepseek-ai/dsh-host-webserver": "^0.1.7-rc.1",
96
- "@deepseek-ai/dsh-llm": "^0.1.7-rc.1",
97
- "@deepseek-ai/dsh-scope": "^0.1.7-rc.1",
98
- "@deepseek-ai/dsh-session": "^0.1.7-rc.1",
99
- "@deepseek-ai/dsh-settings": "^0.1.7-rc.1",
100
- "@deepseek-ai/dsh-subagent": "^0.1.7-rc.1",
101
- "@deepseek-ai/dsh-timeout": "^0.1.7-rc.1",
102
- "@deepseek-ai/dsh-tools": "^0.1.7-rc.1",
103
- "@deepseek-ai/dsh-util-time": "^0.1.7-rc.1",
104
- "@deepseek-ai/dsh-util-values": "^0.1.7-rc.1",
79
+ "@deepseek-ai/cordis": "~4.0.5",
80
+ "@deepseek-ai/dsh-agent": "^0.2.1-rc.2",
81
+ "@deepseek-ai/dsh-api-remotes": "^0.2.1-rc.2",
82
+ "@deepseek-ai/dsh-api-session-controller": "^0.2.1-rc.2",
83
+ "@deepseek-ai/dsh-api-workspace-controller": "^0.2.1-rc.2",
84
+ "@deepseek-ai/dsh-client-locale": "^0.2.1-rc.2",
85
+ "@deepseek-ai/dsh-client-store": "^0.2.1-rc.2",
86
+ "@deepseek-ai/dsh-client-ui-conversation": "^0.2.1-rc.2",
87
+ "@deepseek-ai/dsh-client-ui-renderer": "^0.2.1-rc.2",
88
+ "@deepseek-ai/dsh-client-ui-settings": "^0.2.1-rc.2",
89
+ "@deepseek-ai/dsh-client-ui-slots": "^0.2.1-rc.2",
90
+ "@deepseek-ai/dsh-client-ui-workspace": "^0.2.1-rc.2",
91
+ "@deepseek-ai/dsh-host-webserver": "^0.2.1-rc.2",
92
+ "@deepseek-ai/dsh-llm": "^0.2.1-rc.2",
93
+ "@deepseek-ai/dsh-scope": "^0.2.1-rc.2",
94
+ "@deepseek-ai/dsh-session": "^0.2.1-rc.2",
95
+ "@deepseek-ai/dsh-settings": "^0.2.1-rc.2",
96
+ "@deepseek-ai/dsh-subagent": "^0.2.1-rc.2",
97
+ "@deepseek-ai/dsh-timeout": "^0.2.1-rc.2",
98
+ "@deepseek-ai/dsh-tools": "^0.2.1-rc.2",
99
+ "@deepseek-ai/dsh-util-time": "^0.2.1-rc.2",
100
+ "@deepseek-ai/dsh-util-values": "^0.2.1-rc.2",
105
101
  "@testing-library/dom": "^10.4.1",
106
102
  "@testing-library/react": "^16.3.2",
107
103
  "@types/node": "^22.20.0",
@@ -141,7 +141,7 @@ const BINDER_ATTEMPTS = 24
141
141
 
142
142
  /** The snapshot an unresolved (or resolvable-but-unbound) form publishes. */
143
143
  function pendingSnapshot<T>(status: 'loading' | 'unavailable'): ConfigFormSnapshot<T> {
144
- return { status, value: undefined, base: undefined, user: undefined, revision: undefined, writable: false, mode: 'host' }
144
+ return { status, value: undefined, base: undefined, user: undefined, revision: undefined, writable: false }
145
145
  }
146
146
 
147
147
  /**
@@ -4,7 +4,7 @@
4
4
  * override, fallback settling, and the stall watchdog, all on fake timers.
5
5
  */
6
6
  import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
7
- import { frames2dRenderer, type Frames2dRendererHandle, type PetFrames2dConfig } from './frames2d.ts'
7
+ import { frames2dRenderer, type Frames2dRendererHandle, type Frames2dTrackConfig, type PetFrames2dConfig } from './frames2d.ts'
8
8
  import { createPhaseStream, type PhaseStream } from '../phase-stream.ts'
9
9
  import type { PetRendererContext } from '../../contracts/renderer.ts'
10
10
  import type { ActivityPhase } from '../../state.ts'
@@ -400,4 +400,106 @@ describe('frames2dRenderer canvas bitmap path', () => {
400
400
  expect(memoFetches).toBeGreaterThan(0)
401
401
  handle.dispose()
402
402
  })
403
+
404
+ /** Decoded frames still resident: created minus closed. */
405
+ const retained = (): number => bitmaps.filter(bmp => bmp.close.mock.calls.length === 0).length
406
+
407
+ const fetchCount = (): number => (fetch as ReturnType<typeof vi.fn>).mock.calls.length
408
+ const fetchedUrls = (): string[] =>
409
+ (fetch as ReturnType<typeof vi.fn>).mock.calls.map(call => String(call[0]))
410
+
411
+ /**
412
+ * Install a decode stub whose frames claim `side * side * 4` bytes each, so a
413
+ * retention budget measured in bytes is reachable without allocating it.
414
+ */
415
+ const stubFramesOf = (side: number): void => {
416
+ vi.stubGlobal('createImageBitmap', vi.fn(async () => {
417
+ const bmp = { width: side, height: side, close: vi.fn() }
418
+ bitmaps.push(bmp)
419
+ return bmp
420
+ }))
421
+ }
422
+
423
+ it('serves a looping track from the cache without re-decoding it', async () => {
424
+ const { ctx } = canvasSetup()
425
+ const handle = frames2dRenderer.mount(ctx, frames2dRenderer.validateConfig(CONFIG)) as Frames2dRendererHandle
426
+ await flush()
427
+ // Mount decodes the idle frame plus its one-frame look-ahead window.
428
+ expect(fetchCount()).toBe(2)
429
+ // Two whole cycles of the two-frame track: every frame is already resident.
430
+ vi.advanceTimersByTime(400)
431
+ await flush()
432
+ expect(fetchCount()).toBe(2)
433
+ expect(retained()).toBe(2)
434
+ handle.dispose()
435
+ })
436
+
437
+ it('releases frames outside the playing window and re-decodes them on demand', async () => {
438
+ // 4096x4096 puts a decoded frame at 64 MB, so the 128 MiB budget holds two
439
+ // of them and a 20-frame track has to evict as the window advances.
440
+ stubFramesOf(4096)
441
+ const longTrack: PetFrames2dConfig = {
442
+ tracks: {
443
+ idle: {
444
+ frames: Array.from({ length: 20 }, (_, index) => `/pet/miku/idle/${index}.webp`),
445
+ durations: Array.from({ length: 20 }, () => 100),
446
+ loop: true,
447
+ },
448
+ },
449
+ phases: { idle: 'idle' },
450
+ }
451
+ const { ctx } = canvasSetup()
452
+ const handle = frames2dRenderer.mount(ctx, frames2dRenderer.validateConfig(longTrack)) as Frames2dRendererHandle
453
+ await flush(80)
454
+ vi.advanceTimersByTime(1500)
455
+ await flush(80)
456
+ // The run decoded the whole track, but only the playing look-ahead window
457
+ // of it stays resident; the rest was really closed, not just unmapped.
458
+ expect(bitmaps.length).toBeGreaterThanOrEqual(20)
459
+ const closedWhilePlaying = bitmaps.filter(bmp => bmp.close.mock.calls.length > 0).length
460
+ expect(closedWhilePlaying).toBeGreaterThanOrEqual(10)
461
+ expect(retained()).toBeLessThanOrEqual(13)
462
+ expect(retained()).toBeLessThan(bitmaps.length)
463
+ // Looping back onto a released frame re-decodes it instead of drawing a
464
+ // closed bitmap.
465
+ vi.advanceTimersByTime(600)
466
+ await flush(80)
467
+ expect(fetchedUrls().filter(url => url === '/pet/miku/idle/0.webp').length).toBeGreaterThanOrEqual(2)
468
+ handle.dispose()
469
+ await flush()
470
+ expect(retained()).toBe(0)
471
+ for (const bmp of bitmaps) expect(bmp.close).toHaveBeenCalled()
472
+ })
473
+
474
+ it('reclaims earlier tracks so a long multi-track run stops growing', async () => {
475
+ stubFramesOf(4096)
476
+ const tracks: Record<string, Frames2dTrackConfig> = {}
477
+ for (let index = 0; index < 6; index += 1) {
478
+ tracks['t' + index] = {
479
+ frames: Array.from({ length: 6 }, (_, frame) => `/pet/miku/t${index}/${frame}.webp`),
480
+ durations: Array.from({ length: 6 }, () => 100),
481
+ loop: true,
482
+ }
483
+ }
484
+ const multiTrack: PetFrames2dConfig = { tracks, phases: { idle: 't0' } }
485
+ const { ctx } = canvasSetup()
486
+ const handle = frames2dRenderer.mount(ctx, frames2dRenderer.validateConfig(multiTrack)) as Frames2dRendererHandle
487
+ await flush(60)
488
+ const residentAfterEachTrack: number[] = []
489
+ for (let index = 0; index < 6; index += 1) {
490
+ handle.setState('t' + index)
491
+ vi.advanceTimersByTime(600)
492
+ await flush(60)
493
+ residentAfterEachTrack.push(retained())
494
+ }
495
+ // Six tracks were decoded in full, and the resident set stays at the playing
496
+ // track plus its window: it does not grow with the number of tracks played.
497
+ expect(bitmaps.length).toBeGreaterThanOrEqual(30)
498
+ expect(Math.max(...residentAfterEachTrack)).toBeLessThanOrEqual(13)
499
+ expect(retained()).toBeLessThan(bitmaps.length)
500
+ handle.dispose()
501
+ await flush()
502
+ expect(retained()).toBe(0)
503
+ for (const bmp of bitmaps) expect(bmp.close).toHaveBeenCalled()
504
+ })
403
505
  })