@linxin666/dsh-pet 0.4.5 → 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.
Files changed (66) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +30 -3
  3. package/README.zh.md +30 -3
  4. package/lib/client.js +178 -62
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +734 -26
  7. package/lib/live2d-vendor.js +129 -95
  8. package/lib/live2d-vendor.js.map +1 -1
  9. package/lib/types/announce.d.ts +16 -0
  10. package/lib/types/announce.d.ts.map +1 -1
  11. package/lib/types/announce.js +16 -0
  12. package/lib/types/client/PetDockEntry.d.ts +6 -0
  13. package/lib/types/client/PetDockEntry.d.ts.map +1 -1
  14. package/lib/types/client/PetDockEntry.js +1 -1
  15. package/lib/types/client/PetSettingsCard.d.ts +4 -0
  16. package/lib/types/client/PetSettingsCard.d.ts.map +1 -1
  17. package/lib/types/client/PetSettingsCard.js +16 -1
  18. package/lib/types/client/PetSprite.d.ts +7 -0
  19. package/lib/types/client/PetSprite.d.ts.map +1 -1
  20. package/lib/types/client/PetSprite.js +23 -13
  21. package/lib/types/client/index.d.ts.map +1 -1
  22. package/lib/types/client/index.js +43 -11
  23. package/lib/types/client/locales.d.ts +4 -0
  24. package/lib/types/client/locales.d.ts.map +1 -1
  25. package/lib/types/client/locales.js +4 -0
  26. package/lib/types/client/renderers/frames2d.d.ts +5 -3
  27. package/lib/types/client/renderers/frames2d.d.ts.map +1 -1
  28. package/lib/types/client/renderers/frames2d.js +139 -33
  29. package/lib/types/index.d.ts +14 -3
  30. package/lib/types/index.d.ts.map +1 -1
  31. package/lib/types/index.js +15 -2
  32. package/lib/types/panel-actions.d.ts +96 -0
  33. package/lib/types/panel-actions.d.ts.map +1 -0
  34. package/lib/types/panel-actions.js +134 -0
  35. package/lib/types/routes.d.ts.map +1 -1
  36. package/lib/types/routes.js +10 -0
  37. package/lib/types/service.d.ts +137 -9
  38. package/lib/types/service.d.ts.map +1 -1
  39. package/lib/types/service.js +151 -19
  40. package/package.json +26 -30
  41. package/src/announce.ts +17 -0
  42. package/src/client/PetDockEntry.test.tsx +1 -0
  43. package/src/client/PetDockEntry.tsx +7 -0
  44. package/src/client/PetSettingsCard.test.tsx +88 -0
  45. package/src/client/PetSettingsCard.tsx +31 -0
  46. package/src/client/PetSprite.test.tsx +197 -0
  47. package/src/client/PetSprite.tsx +56 -12
  48. package/src/client/index.test.tsx +74 -4
  49. package/src/client/index.ts +43 -11
  50. package/src/client/locales.ts +4 -0
  51. package/src/client/renderers/frames2d.test.ts +103 -1
  52. package/src/client/renderers/frames2d.ts +143 -30
  53. package/src/index.test.ts +22 -0
  54. package/src/index.ts +28 -2
  55. package/src/panel-actions.test.ts +130 -0
  56. package/src/panel-actions.ts +182 -0
  57. package/src/registry.test.ts +3 -2
  58. package/src/routes.ts +9 -0
  59. package/src/service.test.ts +128 -0
  60. package/src/service.ts +206 -22
  61. package/lib/invariant.js +0 -34
  62. package/lib/state-NvDEoCln.js +0 -455
  63. package/lib/types/invariant.d.ts +0 -10
  64. package/lib/types/invariant.d.ts.map +0 -1
  65. package/lib/types/invariant.js +0 -27
  66. package/src/invariant.ts +0 -40
@@ -42,7 +42,7 @@ import { live2dRenderer } from './renderers/live2d.ts'
42
42
  import { frames2dRenderer } from './renderers/frames2d.ts'
43
43
  import { registerPetUiTeardown, takeoverPetUiTeardown } from './ui-teardown.ts'
44
44
  import { PetSettingsSection, PetSettingsCardController, type PetSettings } from './PetSettingsCard.tsx'
45
- import { NS, en, zh, t } from './locales.ts'
45
+ import { NS, en, zh } from './locales.ts'
46
46
  import { mainViewSessionId } from './main-session.ts'
47
47
  import { reportDailyHeartbeat } from './telemetry.ts'
48
48
 
@@ -56,6 +56,7 @@ interface PetHttpApi {
56
56
  setConfig(patch: Partial<PetDisplayConfig>): Promise<{ ok: true; display: PetDisplayConfig }>
57
57
  setName(name: string): Promise<{ ok: true; name: string } | { ok: false; error: string }>
58
58
  setPet(petId: string): Promise<{ ok: true; petId: string } | { ok: false; error: string }>
59
+ panelAction(id: string): Promise<{ ok: boolean; error?: string }>
59
60
  setSkin(skin?: string): Promise<{ ok: boolean; error?: string; skin?: string }>
60
61
  gameplayTouch(zone?: string): Promise<PetGameplayVerbResult>
61
62
  gameplaySetMode(mode: string | null): Promise<PetGameplayVerbResult>
@@ -88,6 +89,7 @@ const petApi: PetHttpApi = {
88
89
  setConfig: (patch) => petFetch('/api/pet/set-config', patch),
89
90
  setName: (name) => petFetch('/api/pet/set-name', { name }),
90
91
  setPet: (petId) => petFetch('/api/pet/set-pet', { petId }),
92
+ panelAction: (id) => petFetch('/api/pet/panel-action', { id }),
91
93
  setSkin: (skin) => petFetch('/api/pet/set-skin', skin === undefined ? {} : { skin }),
92
94
  gameplayTouch: (zone) => petFetch('/api/pet/gameplay/touch', zone === undefined ? {} : { zone }),
93
95
  gameplaySetMode: (mode) => petFetch('/api/pet/gameplay/mode', { mode }),
@@ -139,7 +141,7 @@ const BINDER_ATTEMPTS = 24
139
141
 
140
142
  /** The snapshot an unresolved (or resolvable-but-unbound) form publishes. */
141
143
  function pendingSnapshot<T>(status: 'loading' | 'unavailable'): ConfigFormSnapshot<T> {
142
- 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 }
143
145
  }
144
146
 
145
147
  /**
@@ -176,19 +178,26 @@ class DeferredSettingsForm implements ConfigForm<PetSettings> {
176
178
  this.ctx = ctx
177
179
  this.fallback = ctx.configForms.get<PetSettings>(this.resolveFallbackEntryId())
178
180
  // No binder yet: the aggregate publishes it after an async mount, so keep
179
- // probing. A shared form that can answer for itself is adopted at once.
181
+ // probing. A shared form that can already answer for itself is adopted at
182
+ // once; one still loading has simply not been filled in yet.
180
183
  if (!this.resolve() && !this.fallbackSettled()) this.scheduleRetry()
181
184
  else if (this.current === undefined) this.adoptFallback()
182
185
  }
183
186
 
184
187
  /**
185
- * True while the shared mirror reports the pet namespace unavailable — the
186
- * only state in which waiting can still help. A fallback that is ready (or
187
- * merely loading, which the mirror fills in on its own) is adopted at once.
188
+ * True only once the shared mirror answers for the pet namespace itself.
189
+ *
190
+ * 'ready' is the only state that answers (#1813). A host-persisted row starts
191
+ * out as 'loading' — the mirror has published no view yet — and that is not
192
+ * an answer: adopting it on sight drops the retry window, and under the
193
+ * aggregate, which serves only the renamed 'web-ui-pet' row, the form then
194
+ * settles into 'unavailable' and the page stays "not exposed" for good. So
195
+ * 'loading' and 'unavailable' both keep the window open and let the binder be
196
+ * adopted the moment the aggregate publishes it.
188
197
  */
189
198
  private fallbackSettled(): boolean {
190
199
  try {
191
- return this.fallback.getSnapshot().status !== 'unavailable'
200
+ return this.fallback.getSnapshot().status === 'ready'
192
201
  } catch {
193
202
  return false
194
203
  }
@@ -241,9 +250,10 @@ class DeferredSettingsForm implements ConfigForm<PetSettings> {
241
250
  }
242
251
 
243
252
  /**
244
- * Adopt the shared per-entry form. It is used immediately unless it reports
245
- * the namespace unavailable, in which case the binder may still be on its way
246
- * and the retry window takes over (see scheduleRetry).
253
+ * Adopt the shared per-entry form. It is used immediately unless it cannot
254
+ * answer yet (still loading, or reporting the namespace unavailable), in which
255
+ * case the binder may still be on its way and the retry window takes over
256
+ * (see scheduleRetry).
247
257
  */
248
258
  private adoptFallback(): void {
249
259
  this.current = this.fallback
@@ -576,6 +586,19 @@ export function apply(ctx: ClientContext): void {
576
586
  // Ignore; next poll resyncs.
577
587
  })
578
588
  },
589
+ // A panel action click (issue #6) travels back to the host, which
590
+ // dispatches it to the plugin that registered the action. The plugin's
591
+ // own callback does the work; the browser half only reports the id, and
592
+ // the next poll brings back whatever that callback changed. A click on
593
+ // an action the plugin already disposed answers { ok: false } — the
594
+ // button was one poll tick stale, which is not a pet failure.
595
+ panelAction: (id) => {
596
+ petApi.panelAction(id).then((result) => {
597
+ if (result.ok) pollNow()
598
+ }, () => {
599
+ // Ignore; next poll resyncs.
600
+ })
601
+ },
579
602
  feedbackDone: () => {
580
603
  setFeedback(null)
581
604
  },
@@ -630,7 +653,16 @@ export function apply(ctx: ClientContext): void {
630
653
  // root then owns the whole surface, so a root-keyed suppressor (the
631
654
  // portrait mobile layer, which hides [data-dsh-plugin="pet"]) really
632
655
  // hides the sprite instead of missing the portaled float.
633
- petRoot.render(createElement(PetDockEntry, { ...injected(), t, portalTarget: container }))
656
+ //
657
+ // The floating surface has no session-scoped locale seat, so it must be
658
+ // handed the framework one explicitly. Resolving its copy from the
659
+ // plugin's own zh/en dictionary keyed on <html lang> sent every
660
+ // registered language except English to Chinese: a ru/ja/de page showed a
661
+ // Chinese panel while the settings card beside it was translated. Binding
662
+ // the 'pet' namespace instead follows the active language, the English
663
+ // fallback, and every language pack that registers a dictionary for it
664
+ // (the settings section label already resolves through the same seat).
665
+ petRoot.render(createElement(PetDockEntry, { ...injected(), t: ctx.locale.bind(NS), portalTarget: container }))
634
666
 
635
667
  let uiGone = false
636
668
  disposeUi = () => {
@@ -64,6 +64,8 @@ export const zh = {
64
64
  'settings.enabledHint': '关闭后隐藏宠物并停止轮询,可在设置里重新启用。',
65
65
  'settings.decoration': '状态装饰',
66
66
  'settings.decorationHint': '在宠物状态气泡里显示喷水鲸鱼等状态装饰;关闭后气泡只剩文字。',
67
+ 'settings.statusBubbles': '状态气泡',
68
+ 'settings.statusBubblesHint': '宠物自带的会话/状态气泡(正在思考、正在使用 xxx)。关掉后只剩第三方插件通过公告契约推送的气泡与互动反馈气泡;默认开启。',
67
69
  'settings.visible': '显示宠物',
68
70
  'settings.visibleHint': '关闭后宠物隐藏,可从聊天输入区重新召唤。',
69
71
  'settings.size': '大小(px)',
@@ -149,6 +151,8 @@ export const en = {
149
151
  'settings.enabledHint': 'When off, the pet hides and polling stops; re-enable it here.',
150
152
  'settings.decoration': 'Status decoration',
151
153
  'settings.decorationHint': 'Show ornaments like the spouting whale inside the pet status bubbles; when off, bubbles stay text-only.',
154
+ 'settings.statusBubbles': 'Status bubbles',
155
+ 'settings.statusBubblesHint': 'The pet\'s own session/status bubbles (thinking, using ...). Turning them off leaves only bubbles a third-party plugin pushes through the announcement contract, plus the interaction feedback bubble; on by default.',
152
156
  'settings.visible': 'Show the pet',
153
157
  'settings.visibleHint': 'When off, the pet hides; summon it again from the input row.',
154
158
  'settings.size': 'Size (px)',
@@ -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
  })
@@ -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.
@@ -78,6 +80,20 @@ export interface Frames2dRendererHandle extends PetRendererHandle {
78
80
  /** Stall watchdog period: a looping track stuck longer re-kicks its chain. */
79
81
  const WATCHDOG_MS = 1200
80
82
 
83
+ /**
84
+ * Retention budget for decoded frame bitmaps, in bytes.
85
+ *
86
+ * The budget is expressed in bytes rather than in frames because a frame's
87
+ * decoded footprint is `width * height * 4` and published pets differ by more
88
+ * than an order of magnitude (a 512x683 frame is 1.33 MB, a 128x128 frame is
89
+ * 64 KB): a frame count would be either useless for small atlases or too tight
90
+ * for large ones. 128 MiB holds this repository's longest shipped track (78
91
+ * frames, 104 MB) in full, so a running loop still re-decodes nothing, while
92
+ * capping a pet that played every track of every skin at roughly a tenth of
93
+ * the ~1.7 GB the unbounded memo reached.
94
+ */
95
+ const MAX_RETAINED_BYTES = 128 * 1024 * 1024
96
+
81
97
  function isRecord(value: unknown): value is Record<string, unknown> {
82
98
  return typeof value === 'object' && value !== null && !Array.isArray(value)
83
99
  }
@@ -160,6 +176,32 @@ interface DecodedFrame {
160
176
  height: number
161
177
  }
162
178
 
179
+ /**
180
+ * One memoized decode job. `frame` and `bytes` appear only once the job
181
+ * resolved with a frame — exactly the set the retention budget may release;
182
+ * pending and failed jobs carry neither. The owning map's insertion order is
183
+ * the LRU order (re-inserting an entry marks it most recently used).
184
+ */
185
+ interface DecodeEntry {
186
+ job: Promise<DecodedFrame | undefined>
187
+ frame?: DecodedFrame
188
+ bytes?: number
189
+ }
190
+
191
+ /**
192
+ * Release one decoded frame. `close()` is browser-only and idempotent, so the
193
+ * call is guarded for exotic hosts and for frames that were already released;
194
+ * the `<img>` fallback has no close, where dropping the reference is the
195
+ * release.
196
+ */
197
+ function releaseFrame(frame: DecodedFrame | undefined): void {
198
+ if (frame === undefined) return
199
+ try {
200
+ const maybeClose = (frame.source as { close?: () => void }).close
201
+ if (typeof maybeClose === 'function') maybeClose.call(frame.source)
202
+ } catch { /* already released */ }
203
+ }
204
+
163
205
  export const frames2dRenderer: PetRenderer<PetFrames2dConfig> = {
164
206
  id: 'frames2d',
165
207
  apiVersion: PET_RENDERER_API_VERSION,
@@ -209,11 +251,18 @@ export const frames2dRenderer: PetRenderer<PetFrames2dConfig> = {
209
251
  ctx.container.appendChild(img)
210
252
  }
211
253
 
212
- // Decode cache: one concurrent decode per URL, memoized forever (frames
213
- // are tiny same-origin webp files; failures resolve undefined and keep
214
- // the last painted frame instead of breaking playback).
215
- const decoding = new Map<string, Promise<DecodedFrame | undefined>>()
216
- const decodedAll: Promise<void>[] = []
254
+ // Decode cache: one concurrent decode per URL, retained under a decoded
255
+ // byte budget. The historical map memoized every decoded frame forever, so
256
+ // a pet that had played all of its tracks (every skin) kept every bitmap
257
+ // alive for the life of the page: a shipped three-skin pet measures 1276
258
+ // frames at 512x683 RGBA, about 1.7 GB, growing monotonically. Entries now
259
+ // carry their decoded footprint, sit in Map insertion order (delete + set
260
+ // is an LRU touch) and the least recently used ones outside the playing
261
+ // window are closed once MAX_RETAINED_BYTES is crossed. A failed decode
262
+ // still resolves undefined and leaves the memo, so a transient fetch error
263
+ // retries instead of sticking.
264
+ const decoding = new Map<string, DecodeEntry>()
265
+ let retainedBytes = 0
217
266
  // All frame fetches funnel through a small pool. Full-library warm passes
218
267
  // on large pets fire 1100+ requests at once, which trips the browser's
219
268
  // in-flight request limit (net::ERR_INSUFFICIENT_RESOURCES) and fails
@@ -263,27 +312,93 @@ export const frames2dRenderer: PetRenderer<PetFrames2dConfig> = {
263
312
  if (index > 0) frameQueue.unshift(frameQueue.splice(index, 1)[0]!)
264
313
  }
265
314
  const cached = decoding.get(url)
266
- if (cached !== undefined) return cached
315
+ if (cached !== undefined) {
316
+ // LRU touch: a hit means playback just asked for this frame, so it must
317
+ // not be the next victim. Re-inserting the same entry only reorders.
318
+ decoding.delete(url)
319
+ decoding.set(url, cached)
320
+ return cached.job
321
+ }
267
322
  let release!: () => void
268
323
  const gate = new Promise<void>((resolve) => { release = resolve })
269
324
  const job: Promise<DecodedFrame | undefined> = gate.then(() => (disposed ? undefined : decodeFrame(url)))
325
+ const entry: DecodeEntry = { job }
270
326
  job.then(
271
- (frame) => { if (frame === undefined) decoding.delete(url) },
327
+ (frame) => {
328
+ if (frame === undefined) {
329
+ decoding.delete(url)
330
+ return
331
+ }
332
+ // A decode that lands after dispose is closed here: nothing can close
333
+ // it later, and the map was already drained.
334
+ if (disposed) {
335
+ releaseFrame(frame)
336
+ decoding.delete(url)
337
+ return
338
+ }
339
+ entry.frame = frame
340
+ entry.bytes = frame.width * frame.height * 4
341
+ retainedBytes += entry.bytes
342
+ // Only a resolved frame is evictable, and its decoded size is known
343
+ // only now, so the budget is enforced here.
344
+ enforceRetentionBudget()
345
+ },
272
346
  () => decoding.delete(url),
273
347
  )
274
348
  void job.finally(() => {
275
349
  activeFrames -= 1
276
350
  pumpFrames()
277
351
  })
278
- decoding.set(url, job)
279
- decodedAll.push(job.then(() => undefined, () => undefined))
280
- const entry = { url, release }
281
- if (jump) frameQueue.unshift(entry)
282
- else frameQueue.push(entry)
352
+ decoding.set(url, entry)
353
+ const queued = { url, release }
354
+ if (jump) frameQueue.unshift(queued)
355
+ else frameQueue.push(queued)
283
356
  pumpFrames()
284
357
  return job
285
358
  }
286
359
 
360
+ /**
361
+ * Release decoded bitmaps until the retained footprint is back under
362
+ * MAX_RETAINED_BYTES. Two properties keep this from breaking playback:
363
+ *
364
+ * - The playing track's look-ahead window, plus the frame a draw is waiting
365
+ * on, are never released. Releasing one would hand a closed bitmap to
366
+ * `drawImage`, and re-decoding it would stall the next tick.
367
+ * - Frames of any other track go first. That is what keeps a running loop
368
+ * warm under a budget smaller than two whole tracks: eviction reclaims the
369
+ * track the pet left instead of eating the cycle it is playing.
370
+ *
371
+ * When the protected window alone exceeds the budget nothing is released —
372
+ * a pet whose frames are that large cannot be bounded further without
373
+ * breaking playback, and the overshoot is then exactly one window.
374
+ */
375
+ function enforceRetentionBudget(): void {
376
+ if (retainedBytes <= MAX_RETAINED_BYTES) return
377
+ const def = config.tracks[track]
378
+ const playing = new Set<string>(def === undefined ? [] : def.frames)
379
+ const protectedUrls = new Set<string>()
380
+ if (pinned !== undefined) protectedUrls.add(pinned)
381
+ if (def !== undefined) {
382
+ const end = Math.min(def.frames.length, frameIndex + 1 + PREFETCH_AHEAD)
383
+ for (let index = frameIndex; index < end; index += 1) {
384
+ const url = def.frames[index]
385
+ if (url !== undefined) protectedUrls.add(url)
386
+ }
387
+ }
388
+ // Pass 1 reclaims frames of tracks the pet is not playing; pass 2 is the
389
+ // backstop for a single track larger than the whole budget.
390
+ for (const foreignOnly of [true, false]) {
391
+ for (const [url, entry] of decoding) {
392
+ if (retainedBytes <= MAX_RETAINED_BYTES) return
393
+ if (entry.bytes === undefined || protectedUrls.has(url)) continue
394
+ if (foreignOnly && playing.has(url)) continue
395
+ releaseFrame(entry.frame)
396
+ retainedBytes -= entry.bytes
397
+ decoding.delete(url)
398
+ }
399
+ }
400
+ }
401
+
287
402
  /**
288
403
  * Bounded look-ahead window: decode only the frames playback is about to
289
404
  * need. The historical warm pass decoded every frame of every track up
@@ -318,6 +433,9 @@ export const frames2dRenderer: PetRenderer<PetFrames2dConfig> = {
318
433
  let baseIdle: string = config.phases.idle
319
434
  let drawToken = 0
320
435
  let lastDrawnUrl: string | undefined
436
+ // The frame a draw is currently awaiting. Eviction must not release it:
437
+ // the callback below holds the bitmap and would draw a closed one.
438
+ let pinned: string | undefined
321
439
 
322
440
  const trackForPhase = (phase: ActivityPhase): string => {
323
441
  const mapped = config.phases[phase]
@@ -330,7 +448,9 @@ export const frames2dRenderer: PetRenderer<PetFrames2dConfig> = {
330
448
  const paintCanvas = (url: string): void => {
331
449
  if (context2d === null || canvas === null) return
332
450
  const myToken = ++drawToken
451
+ pinned = url
333
452
  void loadFrame(url, true).then((frame) => {
453
+ if (pinned === url) pinned = undefined
334
454
  if (disposed || frame === undefined || myToken !== drawToken) return
335
455
  if (lastDrawnUrl === url) return
336
456
  lastDrawnUrl = url
@@ -342,7 +462,7 @@ export const frames2dRenderer: PetRenderer<PetFrames2dConfig> = {
342
462
  context2d.clearRect(0, 0, canvas.width, canvas.height)
343
463
  }
344
464
  context2d.drawImage(frame.source as CanvasImageSource, 0, 0)
345
- }).catch(() => { /* keep last frame */ })
465
+ }).catch(() => { if (pinned === url) pinned = undefined /* keep last frame */ })
346
466
  }
347
467
 
348
468
  const show = (trackId: string, index: number): void => {
@@ -433,21 +553,14 @@ export const frames2dRenderer: PetRenderer<PetFrames2dConfig> = {
433
553
  unsubscribe()
434
554
  if (timer !== undefined) clearTimeout(timer)
435
555
  if (watchdog !== undefined) clearInterval(watchdog)
436
- // Release decoded bitmaps after pending decodes settle; close() is
437
- // browser-only, so guard it for exotic hosts. Queued-but-unstarted
438
- // frames release immediately as no-ops so the settle barrier drains.
556
+ // Release every retained bitmap and drain the pool. Queued-but-unstarted
557
+ // frames resolve as no-ops (the gate skips decodeFrame once disposed), and
558
+ // a decode that lands after this loop is closed by the resolution guard
559
+ // above, so teardown leaves nothing pending and nothing retained.
439
560
  for (const queued of frameQueue.splice(0)) queued.release()
440
- void Promise.allSettled(decodedAll).then(() => {
441
- for (const job of decoding.values()) {
442
- void job.then((frame) => {
443
- try {
444
- const maybeClose = (frame?.source as { close?: () => void } | undefined)?.close
445
- if (typeof maybeClose === 'function' && frame !== undefined) maybeClose.call(frame.source)
446
- } catch { /* already released */ }
447
- }).catch(() => { /* never rejects anyway */ })
448
- }
449
- decoding.clear()
450
- })
561
+ for (const entry of decoding.values()) releaseFrame(entry.frame)
562
+ decoding.clear()
563
+ retainedBytes = 0
451
564
  canvas?.remove()
452
565
  img?.remove()
453
566
  }
package/src/index.test.ts CHANGED
@@ -33,6 +33,7 @@ describe('pet configuration schema', () => {
33
33
  bubbleScale: 1,
34
34
  enabled: true,
35
35
  decorationEnabled: true,
36
+ statusBubbles: 'auto',
36
37
  })
37
38
  })
38
39
 
@@ -69,6 +70,7 @@ describe('pet configuration schema', () => {
69
70
  petId: true,
70
71
  enabled: true,
71
72
  decorationEnabled: true,
73
+ statusBubbles: true,
72
74
  })
73
75
  })
74
76
  })
@@ -93,6 +95,7 @@ describe('petSettingsSection', () => {
93
95
  petId: 'doro',
94
96
  enabled: true,
95
97
  decorationEnabled: true,
98
+ statusBubbles: 'auto',
96
99
  })
97
100
  })
98
101
 
@@ -109,6 +112,25 @@ describe('petSettingsSection', () => {
109
112
  expect(before.size).toBe(160)
110
113
  })
111
114
 
115
+ it('user switches the pet\'s own bubbles off from the settings page (#6)', () => {
116
+ // Given a resolved config whose user turned the status bubbles off
117
+ const resolved = Config({ statusBubbles: 'off' })
118
+ // When the plugin resolves the settings section it runs with
119
+ const section = petSettingsSection(resolved, 'whale-girl')
120
+ // Then the running pet is told to render no built-in bubbles
121
+ expect(section.statusBubbles).toBe('off')
122
+ // And the edit lands in the running activation, not only in the document
123
+ commitLive(resolved.statusBubbles, 'off')
124
+ expect(petSettingsSection(resolved, 'whale-girl').statusBubbles).toBe('off')
125
+ })
126
+
127
+ it('user keeps the status bubbles when the document carries no choice', () => {
128
+ // Given a mount outside a Loader, where no schema default was applied
129
+ const section = petSettingsSection({}, 'whale-girl')
130
+ // Then the shipped behavior stands rather than the bubbles silently vanishing
131
+ expect(section.statusBubbles).toBe('auto')
132
+ })
133
+
112
134
  it('user keeps the pet selection it already has when the config names none', () => {
113
135
  // Given a mount whose config carries no pet selection
114
136
  // When the plugin resolves the settings section it runs with
package/src/index.ts CHANGED
@@ -16,20 +16,28 @@ import { Context, type Volatile } from '@deepseek-ai/cordis'
16
16
  import type {} from '@deepseek-ai/dsh-settings'
17
17
  import type {} from '@deepseek-ai/dsh-host-webserver'
18
18
  import z from '@deepseek-ai/schemastery'
19
- import { PET_SETTINGS_NAMESPACE, PetService, type PetConfig, type PetSettingsSection } from './service.ts'
19
+ import { DEFAULT_STATUS_BUBBLE_MODE, PET_SETTINGS_NAMESPACE, PetService, STATUS_BUBBLE_MODES, statusBubbleMode, type PetConfig, type PetSettingsSection, type PetStatusBubbleMode } from './service.ts'
20
20
  import { makePetRoutes } from './routes.ts'
21
21
  import { loadPetRegistry, petPackageRoot } from './registry.ts'
22
22
  import { BUBBLE_SCALE_MAX, BUBBLE_SCALE_MIN, DEFAULT_PET_ID, DISPLAY_INSET_MAX, DISPLAY_SIZE_MAX, DISPLAY_SIZE_MIN, type PetDisplayConfig } from './persist.ts'
23
23
  import { mountOnce } from './mount-once.ts'
24
24
 
25
- export { PetService, MAX_SESSION_BUBBLES } from './service.ts'
25
+ export { PetService, MAX_SESSION_BUBBLES, DEFAULT_STATUS_BUBBLE_MODE, STATUS_BUBBLE_MODES, statusBubbleMode } from './service.ts'
26
26
  export type {
27
27
  PetConfig,
28
28
  PetInteractResult,
29
29
  PetSettingsSection,
30
30
  PetSessionView,
31
31
  PetStateView,
32
+ PetStatusBubbleMode,
32
33
  } from './service.ts'
34
+ export { MAX_PANEL_ACTIONS, PanelActionRegistry, normalizePanelAction } from './panel-actions.ts'
35
+ export type {
36
+ PetPanelActionContext,
37
+ PetPanelActionHandler,
38
+ PetPanelActionRegistration,
39
+ PetPanelActionView,
40
+ } from './panel-actions.ts'
33
41
  export {
34
42
  AFFINITY_MAX,
35
43
  AFFINITY_RANKS,
@@ -133,6 +141,7 @@ export const PET_FORM_DEFAULTS = {
133
141
  petId: DEFAULT_PET_ID,
134
142
  enabled: true,
135
143
  decorationEnabled: true,
144
+ statusBubbles: DEFAULT_STATUS_BUBBLE_MODE,
136
145
  } as const
137
146
 
138
147
  /**
@@ -149,6 +158,12 @@ export interface PetFormConfig {
149
158
  enabled?: LiveField<boolean>
150
159
  /** Status-decoration master switch (pet-center M5, #567); defaults to on. */
151
160
  decorationEnabled?: LiveField<boolean>
161
+ /**
162
+ * Whether the pet renders its own session/status bubbles (issue #6);
163
+ * defaults to 'auto', which is exactly the behavior that shipped before
164
+ * the switch existed.
165
+ */
166
+ statusBubbles?: LiveField<PetStatusBubbleMode | undefined>
152
167
  /** Master switch for the pet surface. */
153
168
  visible?: LiveField<boolean>
154
169
  /** Scale of the rendered pet in px (sprite cell height). */
@@ -189,6 +204,11 @@ export const Config = z.object({
189
204
  petId: z.string().volatile(),
190
205
  enabled: z.boolean().default(PET_FORM_DEFAULTS.enabled).volatile(),
191
206
  decorationEnabled: z.boolean().default(PET_FORM_DEFAULTS.decorationEnabled).volatile(),
207
+ // The pet's own session/status bubbles (issue #6). 'auto' is the shipped
208
+ // behavior; 'off' is the opt-in a user (or a plugin that drives its own
209
+ // bubble surface) needs, and it hides ONLY those bubbles — the sprite, the
210
+ // interaction feedback and a sibling plugin's announcement bubble stay.
211
+ statusBubbles: z.union([...STATUS_BUBBLE_MODES]).default(PET_FORM_DEFAULTS.statusBubbles).volatile(),
192
212
  })
193
213
 
194
214
  /**
@@ -283,6 +303,11 @@ export function petSettingsSection(
283
303
  petId: readLive(config.petId, fallbackPetId),
284
304
  enabled,
285
305
  decorationEnabled: readLive(config.decorationEnabled, PET_FORM_DEFAULTS.decorationEnabled),
306
+ // Not a display field: the bubble switch has no persisted pet.json twin
307
+ // (it is a plugin-level rendering preference, like `decorationEnabled`),
308
+ // so it reads the live value directly and normalizes anything unknown to
309
+ // the shipped default instead of trusting the document.
310
+ statusBubbles: statusBubbleMode(readLive<PetStatusBubbleMode | undefined>(config.statusBubbles, undefined)),
286
311
  }
287
312
  }
288
313
 
@@ -344,6 +369,7 @@ function applyImpl(ctx: Context, config: PetPluginConfig = {}): void {
344
369
  ...config,
345
370
  enabled: readLive(config.enabled, PET_FORM_DEFAULTS.enabled),
346
371
  decorationEnabled: readLive(config.decorationEnabled, PET_FORM_DEFAULTS.decorationEnabled),
372
+ statusBubbles: statusBubbleMode(readLive<PetStatusBubbleMode | undefined>(config.statusBubbles, undefined)),
347
373
  registry,
348
374
  })
349
375
  // The mirror back into the settings document (see syncSettingsFromPet) has to