@linxin666/dsh-pet 0.4.4 → 0.4.6

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 (54) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +46 -6
  3. package/README.zh.md +46 -6
  4. package/lib/client.js +244 -47
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +287 -28
  7. package/lib/types/announce.d.ts +16 -0
  8. package/lib/types/announce.d.ts.map +1 -1
  9. package/lib/types/announce.js +16 -0
  10. package/lib/types/client/PetDockEntry.d.ts +6 -0
  11. package/lib/types/client/PetDockEntry.d.ts.map +1 -1
  12. package/lib/types/client/PetDockEntry.js +1 -1
  13. package/lib/types/client/PetSettingsCard.d.ts +4 -0
  14. package/lib/types/client/PetSettingsCard.d.ts.map +1 -1
  15. package/lib/types/client/PetSettingsCard.js +16 -1
  16. package/lib/types/client/PetSprite.d.ts +7 -0
  17. package/lib/types/client/PetSprite.d.ts.map +1 -1
  18. package/lib/types/client/PetSprite.js +23 -13
  19. package/lib/types/client/index.d.ts +2 -0
  20. package/lib/types/client/index.d.ts.map +1 -1
  21. package/lib/types/client/index.js +224 -28
  22. package/lib/types/client/locales.d.ts +4 -0
  23. package/lib/types/client/locales.d.ts.map +1 -1
  24. package/lib/types/client/locales.js +4 -0
  25. package/lib/types/index.d.ts +14 -3
  26. package/lib/types/index.d.ts.map +1 -1
  27. package/lib/types/index.js +32 -3
  28. package/lib/types/panel-actions.d.ts +96 -0
  29. package/lib/types/panel-actions.d.ts.map +1 -0
  30. package/lib/types/panel-actions.js +134 -0
  31. package/lib/types/routes.d.ts.map +1 -1
  32. package/lib/types/routes.js +10 -0
  33. package/lib/types/service.d.ts +137 -9
  34. package/lib/types/service.d.ts.map +1 -1
  35. package/lib/types/service.js +163 -21
  36. package/package.json +1 -1
  37. package/src/announce.ts +17 -0
  38. package/src/client/PetDockEntry.test.tsx +1 -0
  39. package/src/client/PetDockEntry.tsx +7 -0
  40. package/src/client/PetSettingsCard.test.tsx +88 -0
  41. package/src/client/PetSettingsCard.tsx +31 -0
  42. package/src/client/PetSprite.test.tsx +197 -0
  43. package/src/client/PetSprite.tsx +56 -12
  44. package/src/client/index.test.tsx +152 -4
  45. package/src/client/index.ts +228 -29
  46. package/src/client/locales.ts +4 -0
  47. package/src/index.test.ts +22 -0
  48. package/src/index.ts +45 -3
  49. package/src/panel-actions.test.ts +130 -0
  50. package/src/panel-actions.ts +182 -0
  51. package/src/registry.test.ts +11 -1
  52. package/src/routes.ts +9 -0
  53. package/src/service.test.ts +128 -0
  54. package/src/service.ts +218 -24
package/src/service.ts CHANGED
@@ -16,7 +16,7 @@ import { Context, Service } from '@deepseek-ai/cordis'
16
16
  import type { AssistantStreamFrame } from '@deepseek-ai/dsh-agent'
17
17
  import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
18
18
  import type { AffinityConfig, PetAffinityView, PetInteraction } from './affinity.ts'
19
- import { announcementFresh, parseAnnouncement, type PetAnnouncement } from './announce.ts'
19
+ import { announcementFresh, MAX_ANNOUNCEMENTS, parseAnnouncement, type PetAnnouncement } from './announce.ts'
20
20
  import type { TreatConfig } from './treats.ts'
21
21
  import {
22
22
  emptyProjectionRuntime,
@@ -27,6 +27,7 @@ import {
27
27
  type ProjectionRuntime,
28
28
  } from './event-projection.ts'
29
29
  import { PetLedger, type LedgerConfig, type LedgerInteractionResult } from './ledger.ts'
30
+ import { PanelActionRegistry, type PetPanelActionRegistration, type PetPanelActionView } from './panel-actions.ts'
30
31
  import {
31
32
  DEFAULT_PET_NAME,
32
33
  DISPLAY_INSET_MAX,
@@ -47,12 +48,14 @@ import {
47
48
  petEntryView,
48
49
  petPackageRoot,
49
50
  type PetDefinition,
51
+ type PetEntry,
50
52
  type PetManifest,
51
53
  type PetRegistry,
52
54
  type PetRegistryDiagnostic,
53
55
  } from './registry.ts'
54
56
  import { WHISPER_TTL_MS, type VoicePackOverrides, type VoicePoolsProvider } from './chatter.ts'
55
57
  import { mergeVoicePacks } from './voice-pack.ts'
58
+ import type { PetRemarks } from './remarks.ts'
56
59
  import type { DecorationView } from './contracts/status-decoration.ts'
57
60
  import {
58
61
  defaultPetStateConfig,
@@ -90,6 +93,8 @@ export interface PetConfig {
90
93
  enabled?: boolean
91
94
  /** Status-decoration master switch (pet-center M5, #567); defaults to on. */
92
95
  decorationEnabled?: boolean
96
+ /** Whether the pet's own session/status bubbles render (issue #6); defaults to 'auto'. */
97
+ statusBubbles?: PetStatusBubbleMode
93
98
  /** Prebuilt registry (tests); defaults to scanning the package + user dirs. */
94
99
  registry?: PetRegistry
95
100
  /** Extra manifest entries composed by the embedding application. */
@@ -123,6 +128,36 @@ export interface PetSettingsSection {
123
128
  * the settings surface mirrors this field and can turn it off.
124
129
  */
125
130
  decorationEnabled?: boolean
131
+ /** Whether the pet's own session/status bubbles render (issue #6). */
132
+ statusBubbles?: PetStatusBubbleMode
133
+ }
134
+
135
+ /**
136
+ * Whether the pet renders its own session/status bubbles (issue #6).
137
+ *
138
+ * `auto` is the shipped behavior: every active session keeps a bubble, and a
139
+ * sibling plugin's announcement bubble rides the same stack above them. `off`
140
+ * hides ONLY the pet's own bubbles — the announcement bubble, the interaction
141
+ * feedback bubble and the sprite itself are untouched — which is what a plugin
142
+ * that drives its own bubble surface needs. Anything unknown resolves to
143
+ * `auto`, so an older profile or a hand-edited settings document keeps the
144
+ * status bubbles rather than losing them silently.
145
+ */
146
+ export type PetStatusBubbleMode = 'auto' | 'off'
147
+
148
+ /** Every accepted {@link PetStatusBubbleMode}, in settings-card order. */
149
+ export const STATUS_BUBBLE_MODES: readonly PetStatusBubbleMode[] = ['auto', 'off']
150
+
151
+ /** The shipped default; the switch changes nothing until a user turns it off. */
152
+ export const DEFAULT_STATUS_BUBBLE_MODE: PetStatusBubbleMode = 'auto'
153
+
154
+ /**
155
+ * Normalize a stored, live or hand-edited bubble mode.
156
+ * @param value - the value the settings document carries, when any.
157
+ * @returns the effective mode; anything but 'off' renders the bubbles.
158
+ */
159
+ export function statusBubbleMode(value: unknown): PetStatusBubbleMode {
160
+ return value === 'off' ? 'off' : DEFAULT_STATUS_BUBBLE_MODE
126
161
  }
127
162
 
128
163
  /** Settings namespace of the pet capability. Spelled here rather than imported: the browser half spells the same value. */
@@ -206,11 +241,36 @@ export interface PetStateView {
206
241
  */
207
242
  gameplay?: PetGameplayStateView
208
243
  /**
209
- * The freshest plugin-authored announcement (dsh-usage linkage), within
210
- * its TTL; absent when none is fresh. Rendered as a dedicated styled
211
- * bubble above the session stack.
244
+ * The freshest plugin-authored announcement, within its TTL; absent when none
245
+ * is fresh. Rendered as a dedicated styled bubble above the session stack.
246
+ *
247
+ * Kept alongside `announcements` with exactly the meaning it had when the
248
+ * contract had a single slot, so a browser half predating the per-source
249
+ * upgrade keeps rendering one bubble instead of none (issue #1812). New
250
+ * readers should use `announcements`.
212
251
  */
213
252
  announcement?: PetAnnouncement
253
+ /**
254
+ * Every fresh plugin-authored announcement, one per publishing plugin, in
255
+ * render order (issue #1812). Absent when nothing is fresh, so a host with no
256
+ * publisher serves exactly what it served before the upgrade.
257
+ */
258
+ announcements?: PetAnnouncement[]
259
+ /**
260
+ * Whether the pet's own session/status bubbles render (issue #6). Absent
261
+ * on a host that predates the switch, which the browser half reads as
262
+ * `'auto'` — the behavior that shipped before it existed. Turning it to
263
+ * `'off'` hides those bubbles only; `announcement` and `bubble` (the
264
+ * legacy single status bubble) are still served, so the wire contract does
265
+ * not change with the display preference.
266
+ */
267
+ statusBubbles?: PetStatusBubbleMode
268
+ /**
269
+ * Actions a sibling plugin registered into the hover panel's action row
270
+ * (issue #6), in render order. Absent when none is registered, so the
271
+ * panel row is exactly what it was before the extension point existed.
272
+ */
273
+ panelActions?: PetPanelActionView[]
214
274
  }
215
275
 
216
276
  /** Result of `pet.interact`. */
@@ -277,8 +337,17 @@ export class PetService extends Service {
277
337
  private enabled: boolean
278
338
  /** Status-decoration master switch (M5, #567); mirrored from settings. */
279
339
  private decorationEnabled: boolean
280
- /** The freshest plugin-authored announcement (dsh-usage linkage). */
281
- private announcement: PetAnnouncement | undefined
340
+ /** Whether the pet renders its own session/status bubbles (issue #6). */
341
+ private statusBubbles: PetStatusBubbleMode
342
+ /**
343
+ * Plugin-authored announcements, one slot per `source` (issue #1812). The
344
+ * contract started as a single slot, where a second announcing plugin
345
+ * displaced the first; the map is the upgrade the design note predicted for
346
+ * exactly this moment. Insertion order is the render order and re-announcing
347
+ * a source updates its entry in place, so two publishers on different
348
+ * cadences never swap positions.
349
+ */
350
+ private readonly announcements = new Map<string, PetAnnouncement>()
282
351
  private disposeActivity: (() => void) | undefined
283
352
  /** Session whose most recent meaningful event currently drives the global pet. */
284
353
  private displaySession: Session | undefined
@@ -294,6 +363,13 @@ export class PetService extends Service {
294
363
  * disposed sessions are removed by the 'session/disposed' listener.
295
364
  */
296
365
  private readonly sessionActivity = new Map<Session, SessionActivity>()
366
+ /**
367
+ * Hover-panel actions registered by sibling plugins (issue #6). The pet owns
368
+ * the panel row and serves the registrations; each plugin owns the callback a
369
+ * click dispatches to. Bounded, in-memory, reclaimed with the registering
370
+ * plugin's disposer.
371
+ */
372
+ private readonly panelActions = new PanelActionRegistry()
297
373
  /**
298
374
  * Sessions whose reward source is the official event stream. This metadata
299
375
  * outlives transient visual resets so a derived legacy `done` cannot reward
@@ -328,18 +404,17 @@ export class PetService extends Service {
328
404
  persist = { ...persist, petId: this.registry.defaultEntry().id }
329
405
  }
330
406
  const selected = this.registry.byId(persist.petId) ?? this.registry.defaultEntry()
331
- const voiceRemarks = mergeVoicePacks(this.registry.globalVoice, selected.voice)?.remarks
332
407
  const ledgerConfig: LedgerConfig = {
333
408
  affinity: config.affinity,
334
409
  treats: config.treats,
335
- remarks: selected.remarks,
336
- voiceRemarks,
410
+ ...this.remarkLayers(selected),
337
411
  }
338
412
  this.ledger = new PetLedger(persist, ledgerConfig)
339
413
  this.stateConfig = { ...defaultPetStateConfig, ...(config.state ?? {}) }
340
414
  this.machine = new PetStateMachine(this.stateConfig)
341
415
  this.enabled = config.enabled ?? true
342
416
  this.decorationEnabled = config.decorationEnabled ?? true
417
+ this.statusBubbles = statusBubbleMode(config.statusBubbles)
343
418
 
344
419
  this.syncActivity()
345
420
  }
@@ -366,24 +441,121 @@ export class PetService extends Service {
366
441
  return this.enabled
367
442
  }
368
443
 
444
+ /**
445
+ * The remark layers one pet contributes to the ledger: its manifest pools
446
+ * first, then the voice packs (a pet directory's voice.json over the global
447
+ * `$DSH_HOME/pets/.voice.json`). Every path that seats the ledger's remark
448
+ * pools resolves them here, so no call site can apply the manifest pools and
449
+ * silently drop the voice layer: doing that reverted a pet whose lines a voice
450
+ * pack had translated back to the built-in pools the moment the settings
451
+ * surface applied.
452
+ * @param entry - the pet whose remark pools apply.
453
+ * @returns the layers `PetLedger.setRemarks` takes.
454
+ */
455
+ private remarkLayers(entry: PetEntry): { remarks?: PetRemarks; voiceRemarks?: PetRemarks } {
456
+ return {
457
+ remarks: entry.remarks,
458
+ voiceRemarks: mergeVoicePacks(this.registry.globalVoice, entry.voice)?.remarks,
459
+ }
460
+ }
461
+
462
+ /** Re-seat the ledger's remark pools from one pet's layers. */
463
+ private applyRemarks(entry: PetEntry): void {
464
+ const layers = this.remarkLayers(entry)
465
+ this.ledger.setRemarks(layers.remarks, layers.voiceRemarks)
466
+ }
467
+
369
468
  /** RPC: current pet state snapshot. */
370
469
  async state(currentSessionId?: string): Promise<PetStateView> {
371
470
  return this.view(currentSessionId)
372
471
  }
373
472
 
374
473
  /**
375
- * RPC: one plugin-authored announcement bubble (dsh-usage linkage). The
376
- * payload is validated into a bounded PetAnnouncement; a malformed one is
377
- * dropped silently — a sibling plugin's bug must never surface as pet
378
- * breakage. The announcement is in-memory only.
474
+ * RPC: one plugin-authored announcement bubble, held in the publisher's own
475
+ * slot keyed by `source` (issue #1812). The payload is validated into a
476
+ * bounded PetAnnouncement; a malformed one is dropped silently — a sibling
477
+ * plugin's bug must never surface as pet breakage. Re-announcing replaces
478
+ * only the caller's own slot, so publishers coexist instead of displacing
479
+ * each other. Announcements are in-memory only.
480
+ *
481
+ * The slot table is bounded by {@link MAX_ANNOUNCEMENTS}. Expired entries are
482
+ * pruned first, so a silent publisher never holds a slot; when the table is
483
+ * genuinely full, the entry that has been silent longest gives up its slot
484
+ * to the arriving one — a publisher that keeps refreshing is never evicted.
379
485
  */
380
486
  announce(input: unknown): { ok: boolean } {
381
487
  const parsed = parseAnnouncement(input, Date.now())
382
488
  if (parsed === undefined) return { ok: false }
383
- this.announcement = parsed
489
+ const now = Date.now()
490
+ for (const [source, entry] of this.announcements) {
491
+ if (!announcementFresh(entry, now)) this.announcements.delete(source)
492
+ }
493
+ if (!this.announcements.has(parsed.source) && this.announcements.size >= MAX_ANNOUNCEMENTS) {
494
+ let oldest = ''
495
+ let oldestAt = Number.POSITIVE_INFINITY
496
+ for (const [source, entry] of this.announcements) {
497
+ if (entry.at < oldestAt) {
498
+ oldest = source
499
+ oldestAt = entry.at
500
+ }
501
+ }
502
+ if (oldest !== '') this.announcements.delete(oldest)
503
+ }
504
+ this.announcements.set(parsed.source, parsed)
384
505
  return { ok: true }
385
506
  }
386
507
 
508
+ /**
509
+ * The announcement slots still fresh, in render order. An expired entry
510
+ * simply stops appearing (the client's 2 s poll drops it); no timer owns its
511
+ * removal.
512
+ */
513
+ private freshAnnouncements(): PetAnnouncement[] {
514
+ const now = Date.now()
515
+ return [...this.announcements.values()].filter(entry => announcementFresh(entry, now))
516
+ }
517
+
518
+ /**
519
+ * Register one action into the hover panel's action row (issue #6). The pet
520
+ * renders the button and dispatches the click back to `onSelect`; the plugin
521
+ * decides what the button does. Registering is a wiring step, so a malformed
522
+ * registration throws at the caller's own apply instead of being dropped.
523
+ *
524
+ * The registration is reclaimed by the disposer, so the idiomatic call binds
525
+ * it to the registering plugin's fiber:
526
+ * ```ts
527
+ * ctx.effect(() => ctx.pet.registerPanelAction({
528
+ * id: 'pet-quota-swap',
529
+ * label: '换装',
530
+ * onSelect: async () => { await cycleToNextPet(ctx.pet) },
531
+ * }))
532
+ * ```
533
+ * @param action - the registration to serve in the panel row.
534
+ * @returns a disposer that removes this registration.
535
+ * @throws when the id, label or callback is unusable, or the row is full.
536
+ */
537
+ registerPanelAction(action: PetPanelActionRegistration): () => void {
538
+ return this.panelActions.register(action)
539
+ }
540
+
541
+ /**
542
+ * RPC: dispatch one hover-panel action click back to the plugin that
543
+ * registered it. A rejected id is a stale click (the plugin disposed its
544
+ * registration between render and click), and a throwing callback is that
545
+ * plugin's own failure — neither may surface as pet breakage, so both answer
546
+ * `{ ok: false }` instead of throwing out of the route.
547
+ * @param id - the action id the browser half reported.
548
+ * @returns whether the click reached a registered action.
549
+ */
550
+ async selectPanelAction(id: string): Promise<{ ok: boolean; error?: string }> {
551
+ try {
552
+ const selected = await this.panelActions.select(id, { petId: this.selectedPetId() })
553
+ return selected ? { ok: true } : { ok: false, error: 'unknown-panel-action' }
554
+ } catch {
555
+ return { ok: false, error: 'panel-action-failed' }
556
+ }
557
+ }
558
+
387
559
  /** Current persisted display config (read-only view). */
388
560
  display(): PetDisplayConfig {
389
561
  return { ...this.ledger.snapshot.display }
@@ -436,8 +608,7 @@ export class PetService extends Service {
436
608
  const entry = this.registry.byId(petId)
437
609
  if (entry === undefined) return { ok: false, error: 'unknown-pet' }
438
610
  this.ledger.setPetId(entry.id)
439
- const voiceRemarks = mergeVoicePacks(this.registry.globalVoice, entry.voice)?.remarks
440
- this.ledger.setRemarks(entry.remarks, voiceRemarks)
611
+ this.applyRemarks(entry)
441
612
  this.flush()
442
613
  this.syncSettingsFromPet()
443
614
  return { ok: true, petId: entry.id }
@@ -822,17 +993,24 @@ export class PetService extends Service {
822
993
  */
823
994
  applySettingsSection(section: PetSettingsSection): void {
824
995
  this.decorationEnabled = section.decorationEnabled ?? true
996
+ this.statusBubbles = statusBubbleMode(section.statusBubbles)
825
997
  const selected = typeof section.petId === 'string' ? this.registry.byId(section.petId) : undefined
826
998
  if (selected !== undefined) {
827
999
  this.ledger.setPetId(selected.id)
828
- this.ledger.setRemarks(selected.remarks)
1000
+ this.applyRemarks(selected)
829
1001
  } else if (section.petId !== undefined) {
830
1002
  // The stored selection names a pet the registry no longer has: keep the
831
1003
  // current selection and repair the settings document.
832
1004
  this.syncSettingsFromPet()
833
1005
  }
834
1006
  const next = { ...this.ledger.snapshot.display }
835
- next.visible = section.visible && (section.enabled ?? true)
1007
+ // The pet's own hide/show intent, stored verbatim. The master switch is
1008
+ // applied when the state view is produced (see the state view below), not
1009
+ // here: writing the conjunction into pet.json turned `enabled: false` into
1010
+ // a persisted "the user hid the pet" and the switch could never be undone -
1011
+ // re-enabling it (or restarting) read that stored `false` straight back
1012
+ // (#1762).
1013
+ next.visible = section.visible
836
1014
  next.size = Math.round(Math.min(DISPLAY_SIZE_MAX, Math.max(DISPLAY_SIZE_MIN, section.size)))
837
1015
  next.right = Math.round(Math.min(DISPLAY_INSET_MAX, Math.max(0, section.right)))
838
1016
  next.bottom = Math.round(Math.min(DISPLAY_INSET_MAX, Math.max(0, section.bottom)))
@@ -919,12 +1097,21 @@ export class PetService extends Service {
919
1097
  }
920
1098
  // Read-only: the ledger settles on economic events only, never on a read,
921
1099
  // so polling the state cannot trigger pet.json writes.
922
- // An expired announcement simply stops appearing (the client's 2 s poll
923
- // drops it); no timer owns its removal.
924
- const announcement = this.announcement !== undefined && announcementFresh(this.announcement, Date.now())
925
- ? this.announcement
926
- : undefined
1100
+ // One slot per publishing plugin (issue #1812); an expired entry simply
1101
+ // stops appearing (the client's 2 s poll drops it), no timer owns removal.
1102
+ const announcements = this.freshAnnouncements()
1103
+ // The freshest entry keeps the pre-#1812 meaning of the singular field, so
1104
+ // a browser half that predates the array still renders one bubble instead
1105
+ // of none (a rolling upgrade must never blank a publisher's bubble).
1106
+ const announcement = announcements.reduce<PetAnnouncement | undefined>(
1107
+ (freshest, entry) => freshest === undefined || entry.at > freshest.at ? entry : freshest,
1108
+ undefined,
1109
+ )
927
1110
  const skin = this.persistedSkin(entry)
1111
+ // The hover panel's action row extensions (issue #6). Served on every poll
1112
+ // so a plugin that mounts or disposes its registration shows up (or goes
1113
+ // away) within one tick, without a separate endpoint.
1114
+ const panelActions = this.panelActions.views()
928
1115
  return {
929
1116
  animation: snapshot.animation,
930
1117
  ...(snapshot.bubble === undefined ? {} : { bubble: snapshot.bubble }),
@@ -933,8 +1120,15 @@ export class PetService extends Service {
933
1120
  sessions,
934
1121
  ...(decoration === undefined ? {} : { decoration }),
935
1122
  ...(announcement === undefined ? {} : { announcement }),
1123
+ ...(announcements.length === 0 ? {} : { announcements }),
1124
+ statusBubbles: this.statusBubbles,
1125
+ ...(panelActions.length === 0 ? {} : { panelActions }),
936
1126
  affinity: this.ledger.affinityView(Date.now()),
937
- display: { ...this.ledger.snapshot.display },
1127
+ // The one place the two visibility answers are combined: the pet's own
1128
+ // hide/show intent AND the plugin master switch. Producing the effective
1129
+ // value here - rather than storing it - keeps the switch reversible and
1130
+ // keeps pet.json describing only what the user chose (#1762).
1131
+ display: { ...this.ledger.snapshot.display, visible: this.isEnabled() && this.ledger.snapshot.display.visible },
938
1132
  pet: {
939
1133
  id: entry.id,
940
1134
  displayName: entry.displayName,