@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
@@ -12,9 +12,10 @@
12
12
  * @module @linxin666/dsh-pet/service
13
13
  */
14
14
  import { Service } from '@deepseek-ai/cordis';
15
- import { announcementFresh, parseAnnouncement } from "./announce.js";
15
+ import { announcementFresh, MAX_ANNOUNCEMENTS, parseAnnouncement } from "./announce.js";
16
16
  import { emptyProjectionRuntime, isActivityPhase, projectAssistantStreamFrame, projectOfficialEvent, } from "./event-projection.js";
17
17
  import { PetLedger } from "./ledger.js";
18
+ import { PanelActionRegistry } from "./panel-actions.js";
18
19
  import { DEFAULT_PET_NAME, DISPLAY_INSET_MAX, DISPLAY_SIZE_MAX, BUBBLE_SCALE_MAX, BUBBLE_SCALE_MIN, DISPLAY_SIZE_MIN, PET_NAME_MAX_LENGTH, loadPetPersist, petHomeDir, savePetPersist, } from "./persist.js";
19
20
  import { DEFAULT_DECORATION_ID, decorationView, loadPetRegistry, petEntryView, petPackageRoot, } from "./registry.js";
20
21
  import { WHISPER_TTL_MS } from "./chatter.js";
@@ -23,6 +24,18 @@ import { defaultPetStateConfig, PetStateMachine, } from "./state.js";
23
24
  import { applyGameplayEffects, drawLotteryTier, initialGameplayState, isDeclaredMode, rollTouchBranch, rollWorkOutcome, settleGameplay, } from "./gameplay.js";
24
25
  /** The unified gameplay currency: the shared treat (小鱼干) ledger. */
25
26
  const GAMEPLAY_TREATS_CURRENCY = 'treats';
27
+ /** Every accepted {@link PetStatusBubbleMode}, in settings-card order. */
28
+ export const STATUS_BUBBLE_MODES = ['auto', 'off'];
29
+ /** The shipped default; the switch changes nothing until a user turns it off. */
30
+ export const DEFAULT_STATUS_BUBBLE_MODE = 'auto';
31
+ /**
32
+ * Normalize a stored, live or hand-edited bubble mode.
33
+ * @param value - the value the settings document carries, when any.
34
+ * @returns the effective mode; anything but 'off' renders the bubbles.
35
+ */
36
+ export function statusBubbleMode(value) {
37
+ return value === 'off' ? 'off' : DEFAULT_STATUS_BUBBLE_MODE;
38
+ }
26
39
  /** Settings namespace of the pet capability. Spelled here rather than imported: the browser half spells the same value. */
27
40
  export const PET_SETTINGS_NAMESPACE = 'pet';
28
41
  /** Hard cap on simultaneously displayed session bubbles (most recent first). */
@@ -43,8 +56,17 @@ export class PetService extends Service {
43
56
  enabled;
44
57
  /** Status-decoration master switch (M5, #567); mirrored from settings. */
45
58
  decorationEnabled;
46
- /** The freshest plugin-authored announcement (dsh-usage linkage). */
47
- announcement;
59
+ /** Whether the pet renders its own session/status bubbles (issue #6). */
60
+ statusBubbles;
61
+ /**
62
+ * Plugin-authored announcements, one slot per `source` (issue #1812). The
63
+ * contract started as a single slot, where a second announcing plugin
64
+ * displaced the first; the map is the upgrade the design note predicted for
65
+ * exactly this moment. Insertion order is the render order and re-announcing
66
+ * a source updates its entry in place, so two publishers on different
67
+ * cadences never swap positions.
68
+ */
69
+ announcements = new Map();
48
70
  disposeActivity;
49
71
  /** Session whose most recent meaningful event currently drives the global pet. */
50
72
  displaySession;
@@ -60,6 +82,13 @@ export class PetService extends Service {
60
82
  * disposed sessions are removed by the 'session/disposed' listener.
61
83
  */
62
84
  sessionActivity = new Map();
85
+ /**
86
+ * Hover-panel actions registered by sibling plugins (issue #6). The pet owns
87
+ * the panel row and serves the registrations; each plugin owns the callback a
88
+ * click dispatches to. Bounded, in-memory, reclaimed with the registering
89
+ * plugin's disposer.
90
+ */
91
+ panelActions = new PanelActionRegistry();
63
92
  /**
64
93
  * Sessions whose reward source is the official event stream. This metadata
65
94
  * outlives transient visual resets so a derived legacy `done` cannot reward
@@ -93,18 +122,17 @@ export class PetService extends Service {
93
122
  persist = { ...persist, petId: this.registry.defaultEntry().id };
94
123
  }
95
124
  const selected = this.registry.byId(persist.petId) ?? this.registry.defaultEntry();
96
- const voiceRemarks = mergeVoicePacks(this.registry.globalVoice, selected.voice)?.remarks;
97
125
  const ledgerConfig = {
98
126
  affinity: config.affinity,
99
127
  treats: config.treats,
100
- remarks: selected.remarks,
101
- voiceRemarks,
128
+ ...this.remarkLayers(selected),
102
129
  };
103
130
  this.ledger = new PetLedger(persist, ledgerConfig);
104
131
  this.stateConfig = { ...defaultPetStateConfig, ...(config.state ?? {}) };
105
132
  this.machine = new PetStateMachine(this.stateConfig);
106
133
  this.enabled = config.enabled ?? true;
107
134
  this.decorationEnabled = config.decorationEnabled ?? true;
135
+ this.statusBubbles = statusBubbleMode(config.statusBubbles);
108
136
  this.syncActivity();
109
137
  }
110
138
  /**
@@ -127,23 +155,118 @@ export class PetService extends Service {
127
155
  isEnabled() {
128
156
  return this.enabled;
129
157
  }
158
+ /**
159
+ * The remark layers one pet contributes to the ledger: its manifest pools
160
+ * first, then the voice packs (a pet directory's voice.json over the global
161
+ * `$DSH_HOME/pets/.voice.json`). Every path that seats the ledger's remark
162
+ * pools resolves them here, so no call site can apply the manifest pools and
163
+ * silently drop the voice layer: doing that reverted a pet whose lines a voice
164
+ * pack had translated back to the built-in pools the moment the settings
165
+ * surface applied.
166
+ * @param entry - the pet whose remark pools apply.
167
+ * @returns the layers `PetLedger.setRemarks` takes.
168
+ */
169
+ remarkLayers(entry) {
170
+ return {
171
+ remarks: entry.remarks,
172
+ voiceRemarks: mergeVoicePacks(this.registry.globalVoice, entry.voice)?.remarks,
173
+ };
174
+ }
175
+ /** Re-seat the ledger's remark pools from one pet's layers. */
176
+ applyRemarks(entry) {
177
+ const layers = this.remarkLayers(entry);
178
+ this.ledger.setRemarks(layers.remarks, layers.voiceRemarks);
179
+ }
130
180
  /** RPC: current pet state snapshot. */
131
181
  async state(currentSessionId) {
132
182
  return this.view(currentSessionId);
133
183
  }
134
184
  /**
135
- * RPC: one plugin-authored announcement bubble (dsh-usage linkage). The
136
- * payload is validated into a bounded PetAnnouncement; a malformed one is
137
- * dropped silently — a sibling plugin's bug must never surface as pet
138
- * breakage. The announcement is in-memory only.
185
+ * RPC: one plugin-authored announcement bubble, held in the publisher's own
186
+ * slot keyed by `source` (issue #1812). The payload is validated into a
187
+ * bounded PetAnnouncement; a malformed one is dropped silently — a sibling
188
+ * plugin's bug must never surface as pet breakage. Re-announcing replaces
189
+ * only the caller's own slot, so publishers coexist instead of displacing
190
+ * each other. Announcements are in-memory only.
191
+ *
192
+ * The slot table is bounded by {@link MAX_ANNOUNCEMENTS}. Expired entries are
193
+ * pruned first, so a silent publisher never holds a slot; when the table is
194
+ * genuinely full, the entry that has been silent longest gives up its slot
195
+ * to the arriving one — a publisher that keeps refreshing is never evicted.
139
196
  */
140
197
  announce(input) {
141
198
  const parsed = parseAnnouncement(input, Date.now());
142
199
  if (parsed === undefined)
143
200
  return { ok: false };
144
- this.announcement = parsed;
201
+ const now = Date.now();
202
+ for (const [source, entry] of this.announcements) {
203
+ if (!announcementFresh(entry, now))
204
+ this.announcements.delete(source);
205
+ }
206
+ if (!this.announcements.has(parsed.source) && this.announcements.size >= MAX_ANNOUNCEMENTS) {
207
+ let oldest = '';
208
+ let oldestAt = Number.POSITIVE_INFINITY;
209
+ for (const [source, entry] of this.announcements) {
210
+ if (entry.at < oldestAt) {
211
+ oldest = source;
212
+ oldestAt = entry.at;
213
+ }
214
+ }
215
+ if (oldest !== '')
216
+ this.announcements.delete(oldest);
217
+ }
218
+ this.announcements.set(parsed.source, parsed);
145
219
  return { ok: true };
146
220
  }
221
+ /**
222
+ * The announcement slots still fresh, in render order. An expired entry
223
+ * simply stops appearing (the client's 2 s poll drops it); no timer owns its
224
+ * removal.
225
+ */
226
+ freshAnnouncements() {
227
+ const now = Date.now();
228
+ return [...this.announcements.values()].filter(entry => announcementFresh(entry, now));
229
+ }
230
+ /**
231
+ * Register one action into the hover panel's action row (issue #6). The pet
232
+ * renders the button and dispatches the click back to `onSelect`; the plugin
233
+ * decides what the button does. Registering is a wiring step, so a malformed
234
+ * registration throws at the caller's own apply instead of being dropped.
235
+ *
236
+ * The registration is reclaimed by the disposer, so the idiomatic call binds
237
+ * it to the registering plugin's fiber:
238
+ * ```ts
239
+ * ctx.effect(() => ctx.pet.registerPanelAction({
240
+ * id: 'pet-quota-swap',
241
+ * label: '换装',
242
+ * onSelect: async () => { await cycleToNextPet(ctx.pet) },
243
+ * }))
244
+ * ```
245
+ * @param action - the registration to serve in the panel row.
246
+ * @returns a disposer that removes this registration.
247
+ * @throws when the id, label or callback is unusable, or the row is full.
248
+ */
249
+ registerPanelAction(action) {
250
+ return this.panelActions.register(action);
251
+ }
252
+ /**
253
+ * RPC: dispatch one hover-panel action click back to the plugin that
254
+ * registered it. A rejected id is a stale click (the plugin disposed its
255
+ * registration between render and click), and a throwing callback is that
256
+ * plugin's own failure — neither may surface as pet breakage, so both answer
257
+ * `{ ok: false }` instead of throwing out of the route.
258
+ * @param id - the action id the browser half reported.
259
+ * @returns whether the click reached a registered action.
260
+ */
261
+ async selectPanelAction(id) {
262
+ try {
263
+ const selected = await this.panelActions.select(id, { petId: this.selectedPetId() });
264
+ return selected ? { ok: true } : { ok: false, error: 'unknown-panel-action' };
265
+ }
266
+ catch {
267
+ return { ok: false, error: 'panel-action-failed' };
268
+ }
269
+ }
147
270
  /** Current persisted display config (read-only view). */
148
271
  display() {
149
272
  return { ...this.ledger.snapshot.display };
@@ -191,8 +314,7 @@ export class PetService extends Service {
191
314
  if (entry === undefined)
192
315
  return { ok: false, error: 'unknown-pet' };
193
316
  this.ledger.setPetId(entry.id);
194
- const voiceRemarks = mergeVoicePacks(this.registry.globalVoice, entry.voice)?.remarks;
195
- this.ledger.setRemarks(entry.remarks, voiceRemarks);
317
+ this.applyRemarks(entry);
196
318
  this.flush();
197
319
  this.syncSettingsFromPet();
198
320
  return { ok: true, petId: entry.id };
@@ -594,10 +716,11 @@ export class PetService extends Service {
594
716
  */
595
717
  applySettingsSection(section) {
596
718
  this.decorationEnabled = section.decorationEnabled ?? true;
719
+ this.statusBubbles = statusBubbleMode(section.statusBubbles);
597
720
  const selected = typeof section.petId === 'string' ? this.registry.byId(section.petId) : undefined;
598
721
  if (selected !== undefined) {
599
722
  this.ledger.setPetId(selected.id);
600
- this.ledger.setRemarks(selected.remarks);
723
+ this.applyRemarks(selected);
601
724
  }
602
725
  else if (section.petId !== undefined) {
603
726
  // The stored selection names a pet the registry no longer has: keep the
@@ -605,7 +728,13 @@ export class PetService extends Service {
605
728
  this.syncSettingsFromPet();
606
729
  }
607
730
  const next = { ...this.ledger.snapshot.display };
608
- next.visible = section.visible && (section.enabled ?? true);
731
+ // The pet's own hide/show intent, stored verbatim. The master switch is
732
+ // applied when the state view is produced (see the state view below), not
733
+ // here: writing the conjunction into pet.json turned `enabled: false` into
734
+ // a persisted "the user hid the pet" and the switch could never be undone -
735
+ // re-enabling it (or restarting) read that stored `false` straight back
736
+ // (#1762).
737
+ next.visible = section.visible;
609
738
  next.size = Math.round(Math.min(DISPLAY_SIZE_MAX, Math.max(DISPLAY_SIZE_MIN, section.size)));
610
739
  next.right = Math.round(Math.min(DISPLAY_INSET_MAX, Math.max(0, section.right)));
611
740
  next.bottom = Math.round(Math.min(DISPLAY_INSET_MAX, Math.max(0, section.bottom)));
@@ -695,12 +824,18 @@ export class PetService extends Service {
695
824
  }
696
825
  // Read-only: the ledger settles on economic events only, never on a read,
697
826
  // so polling the state cannot trigger pet.json writes.
698
- // An expired announcement simply stops appearing (the client's 2 s poll
699
- // drops it); no timer owns its removal.
700
- const announcement = this.announcement !== undefined && announcementFresh(this.announcement, Date.now())
701
- ? this.announcement
702
- : undefined;
827
+ // One slot per publishing plugin (issue #1812); an expired entry simply
828
+ // stops appearing (the client's 2 s poll drops it), no timer owns removal.
829
+ const announcements = this.freshAnnouncements();
830
+ // The freshest entry keeps the pre-#1812 meaning of the singular field, so
831
+ // a browser half that predates the array still renders one bubble instead
832
+ // of none (a rolling upgrade must never blank a publisher's bubble).
833
+ const announcement = announcements.reduce((freshest, entry) => freshest === undefined || entry.at > freshest.at ? entry : freshest, undefined);
703
834
  const skin = this.persistedSkin(entry);
835
+ // The hover panel's action row extensions (issue #6). Served on every poll
836
+ // so a plugin that mounts or disposes its registration shows up (or goes
837
+ // away) within one tick, without a separate endpoint.
838
+ const panelActions = this.panelActions.views();
704
839
  return {
705
840
  animation: snapshot.animation,
706
841
  ...(snapshot.bubble === undefined ? {} : { bubble: snapshot.bubble }),
@@ -709,8 +844,15 @@ export class PetService extends Service {
709
844
  sessions,
710
845
  ...(decoration === undefined ? {} : { decoration }),
711
846
  ...(announcement === undefined ? {} : { announcement }),
847
+ ...(announcements.length === 0 ? {} : { announcements }),
848
+ statusBubbles: this.statusBubbles,
849
+ ...(panelActions.length === 0 ? {} : { panelActions }),
712
850
  affinity: this.ledger.affinityView(Date.now()),
713
- display: { ...this.ledger.snapshot.display },
851
+ // The one place the two visibility answers are combined: the pet's own
852
+ // hide/show intent AND the plugin master switch. Producing the effective
853
+ // value here - rather than storing it - keeps the switch reversible and
854
+ // keeps pet.json describing only what the user chose (#1762).
855
+ display: { ...this.ledger.snapshot.display, visible: this.isEnabled() && this.ledger.snapshot.display.visible },
714
856
  pet: {
715
857
  id: entry.id,
716
858
  displayName: entry.displayName,
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.4",
4
+ "version": "0.4.6",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
package/src/announce.ts CHANGED
@@ -4,6 +4,11 @@
4
4
  * validates it into a bounded payload, and the browser half renders it as a
5
5
  * dedicated, specially styled bubble above the session bubble stack.
6
6
  *
7
+ * One slot per publisher (issue #1812): `source` is the slot key, so two
8
+ * announcing plugins coexist instead of displacing each other, and each keeps
9
+ * its own TTL. The single-slot contract this replaced is kept on the wire as
10
+ * the freshest entry, so an older browser half keeps working unchanged.
11
+ *
7
12
  * The validation lives in this pure module so the wire contract has exactly
8
13
  * one home and stays testable without the cordis service.
9
14
  * @module @linxin666/dsh-pet/announce
@@ -36,6 +41,18 @@ export interface PetAnnouncement {
36
41
  /** Default freshness window. */
37
42
  export const ANNOUNCE_DEFAULT_TTL_MS = 10_000
38
43
 
44
+ /**
45
+ * How many publishers can hold an announcement bubble at once (issue #1812).
46
+ *
47
+ * The contract has exactly one slot per `source` — that is the whole upgrade
48
+ * from the single-slot design — but the pet's bubble stack is a finite column,
49
+ * so the table is bounded rather than open. The bound is deliberately above the
50
+ * realistic publisher count (a quota bubble, a balance bubble, a notification):
51
+ * it exists so a misbehaving publisher that rotates `source` per bubble cannot
52
+ * grow the pet's stack without limit.
53
+ */
54
+ export const MAX_ANNOUNCEMENTS = 4
55
+
39
56
  /**
40
57
  * Hard TTL ceiling. A repeating announcer declares its poll cadence as
41
58
  * the TTL, so an always-on bubble stays continuous across polls; the
@@ -77,6 +77,7 @@ function injected(): PetInjected {
77
77
  summon: vi.fn(),
78
78
  dragEnd: vi.fn(),
79
79
  rename: vi.fn(),
80
+ panelAction: vi.fn(),
80
81
  openSession: vi.fn(),
81
82
  feedbackDone: vi.fn(),
82
83
  gameplay: {
@@ -41,6 +41,12 @@ export interface PetInjected {
41
41
  dragEnd: (right: number, bottom: number) => void
42
42
  /** Rename the selected pet (persisted by the host). */
43
43
  rename: (name: string) => void
44
+ /**
45
+ * Report a click on one plugin-registered panel action (issue #6). The host
46
+ * dispatches it to the plugin that registered the action; the panel itself
47
+ * only renders the button the state snapshot served.
48
+ */
49
+ panelAction: (id: string) => void
44
50
  /** Navigate the GUI to the session a bubble reports on. */
45
51
  openSession: (sessionId: string) => void
46
52
  /** Clear the reaction bubble. */
@@ -116,6 +122,7 @@ export function PetDockEntry(props: PetDockEntryProps): ReactElement {
116
122
  onHide={props.hide}
117
123
  onDragEnd={props.dragEnd}
118
124
  onRename={props.rename}
125
+ onPanelAction={props.panelAction}
119
126
  onOpenSession={props.openSession}
120
127
  onFeedbackDone={props.feedbackDone}
121
128
  portalTarget={props.portalTarget}
@@ -41,6 +41,36 @@ function response(value: unknown, ok = true): Response {
41
41
  return { ok, status: ok ? 200 : 500, json: async () => value } as Response
42
42
  }
43
43
 
44
+ /**
45
+ * A Host-served pet namespace: the settings document, its user layer, and a
46
+ * mutate that applies the card's batch and publishes the settled view back,
47
+ * which is what the card's read-back judgment reads.
48
+ */
49
+ function readyForm(value: PetSettings) {
50
+ let section: PetSettings = { ...value }
51
+ // The Host document's user layer is keyed by field name, so the test seam
52
+ // writes through a record view of the same shape the form contract serves.
53
+ let user: Record<string, unknown> = {}
54
+ const listeners = new Set<() => void>()
55
+ const publish = () => { for (const listener of listeners) listener() }
56
+ const mutate = vi.fn(async (ops: ReadonlyArray<{ op: 'set' | 'unset'; path: string[]; value?: unknown }>) => {
57
+ for (const op of ops) {
58
+ const field = op.path[0] as string
59
+ if (op.op === 'set') user[field] = op.value
60
+ else delete user[field]
61
+ }
62
+ section = { ...value, ...user }
63
+ publish()
64
+ return true
65
+ })
66
+ const scope = {
67
+ getSnapshot: () => ({ status: 'ready', writable: true, value: section, base: value, user, revision: 1 }),
68
+ subscribe: (listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener) } },
69
+ mutate,
70
+ } as unknown as ConfigForm<PetSettings>
71
+ return { scope, mutate, value: () => ({ user }) }
72
+ }
73
+
44
74
  beforeAll(() => {
45
75
  document.documentElement.lang = 'zh'
46
76
  })
@@ -212,3 +242,61 @@ describe('pet settings card rendered without a Host settings form', () => {
212
242
  controller.dispose()
213
243
  })
214
244
  })
245
+
246
+ describe('the status bubble switch on the Host settings form', () => {
247
+ it('user switches the pet own bubbles off and the form writes the mode', async () => {
248
+ // Given a Host that serves the pet namespace with the shipped default
249
+ vi.useFakeTimers()
250
+ const { scope, value, mutate } = readyForm({ statusBubbles: 'auto' })
251
+ vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL) => {
252
+ const path = String(input)
253
+ if (path === '/api/pet/pets') return response([{ id: 'whale-girl', displayName: '鲸鱼娘' }])
254
+ if (path === '/api/pet/state') return response({ pet: { id: 'whale-girl' }, display: { visible: true } })
255
+ throw new Error('unexpected request: ' + path)
256
+ }))
257
+ const controller = new PetSettingsCardController(scope)
258
+ await vi.advanceTimersByTimeAsync(0)
259
+ const face = controller.inject()
260
+ const state = () => face.hooks.petSettingsCard.getSnapshot()
261
+
262
+ // When the card renders, the switch is on screen beside the other fields
263
+ render(
264
+ <PetSettingsCard
265
+ t={t}
266
+ usePetSettingsCard={select => useSyncExternalStore(face.hooks.petSettingsCard.subscribe, () => select(face.hooks.petSettingsCard.getSnapshot()))}
267
+ save={face.save}
268
+ discard={face.discard}
269
+ edit={face.edit}
270
+ resetField={face.resetField}
271
+ />,
272
+ )
273
+ expect(screen.getByLabelText(t('settings.statusBubbles'))).toBeTruthy()
274
+ expect(state()).toMatchObject({ statusBubbles: { text: 'auto', invalid: false } })
275
+
276
+ // When the user picks Off and saves
277
+ face.edit('statusBubbles', 'off')
278
+ expect(state()).toMatchObject({ dirty: true, statusBubbles: { text: 'off' } })
279
+ face.save()
280
+ await vi.waitFor(() => { expect(state().saving).toBe(false) })
281
+
282
+ // Then the settings document holds the mode, and the draft clears
283
+ expect(mutate).toHaveBeenCalledWith([{ op: 'set', path: ['statusBubbles'], value: 'off' }])
284
+ expect(value().user?.statusBubbles).toBe('off')
285
+ expect(state()).toMatchObject({ dirty: false, failed: false, statusBubbles: { text: 'off' } })
286
+ controller.dispose()
287
+ })
288
+
289
+ it('refuses a draft the switch does not accept instead of writing it', () => {
290
+ const { scope } = readyForm({ statusBubbles: 'auto' })
291
+ const face = new PetSettingsCardController(scope).inject()
292
+
293
+ face.edit('statusBubbles', 'maybe')
294
+
295
+ // The save stays blocked: a mode the host schema has no union member for
296
+ // must never reach the settings document.
297
+ expect(face.hooks.petSettingsCard.getSnapshot()).toMatchObject({
298
+ invalid: true,
299
+ statusBubbles: { text: 'maybe', invalid: true },
300
+ })
301
+ })
302
+ })
@@ -37,6 +37,8 @@ export interface PetSettings {
37
37
  petId?: string
38
38
  /** Status-decoration master switch (pet-center M5, #567). */
39
39
  decorationEnabled?: boolean
40
+ /** Whether the pet's own session/status bubbles render (issue #6). */
41
+ statusBubbles?: string
40
42
  }
41
43
 
42
44
  /** What the pet settings card renders. */
@@ -59,6 +61,8 @@ export interface PetSettingsCardState extends CardShell {
59
61
  petId: CardFieldState
60
62
  /** Status-decoration master switch. */
61
63
  decorationEnabled: CardFieldState
64
+ /** Whether the pet's own session/status bubbles render. */
65
+ statusBubbles: CardFieldState
62
66
  /** Pet choices (registry ids + display names), loaded from the host. */
63
67
  petChoices: readonly { value: string; label: string }[]
64
68
  }
@@ -71,6 +75,13 @@ export interface PetSettingsCardFace extends CardActions {
71
75
  }
72
76
  }
73
77
 
78
+ /**
79
+ * The bubble modes this card can write, in render order. Mirrors the host
80
+ * schema's union (see PetStatusBubbleMode); the browser half never imports the
81
+ * host module for a value, so the accepted set is spelled here as literals.
82
+ */
83
+ const STATUS_BUBBLE_CHOICES = ['auto', 'off'] as const
84
+
74
85
  /** One registry choice as served by '/api/pet/pets'. */
75
86
  interface PetChoice {
76
87
  id: string
@@ -128,6 +139,11 @@ export class PetSettingsCardController {
128
139
  this.form = new CardForm(scope, [
129
140
  booleanField('enabled'),
130
141
  booleanField('decorationEnabled'),
142
+ // The bubble switch is a two-value mode, not a boolean: 'off' is the
143
+ // opt-out, and a future mode (say, one that keeps only the current
144
+ // session's bubble) has to be able to join the same field without
145
+ // breaking every settings document already written.
146
+ choiceField('statusBubbles', STATUS_BUBBLE_CHOICES),
131
147
  booleanField('visible'),
132
148
  numberField('size'),
133
149
  numberField('right'),
@@ -268,6 +284,7 @@ export class PetSettingsCardController {
268
284
  petSelectionFallback: fallback,
269
285
  enabled: this.form.field('enabled'),
270
286
  decorationEnabled: this.form.field('decorationEnabled'),
287
+ statusBubbles: this.form.field('statusBubbles'),
271
288
  visible: fallback ? this.fallbackVisible() : this.form.field('visible'),
272
289
  size: this.form.field('size'),
273
290
  right: this.form.field('right'),
@@ -387,6 +404,20 @@ export function PetSettingsCard(props: PetSettingsCardProps) {
387
404
  onEdit={(text) => { props.edit('decorationEnabled', text) }}
388
405
  onReset={() => { props.resetField('decorationEnabled') }}
389
406
  />}
407
+ {state.petSelectionFallback ? null : <ChoiceField
408
+ id="settings-pet-status-bubbles"
409
+ label={t('settings.statusBubbles')}
410
+ hint={t('settings.statusBubblesHint')}
411
+ inheritLabel={t('settings.inherit')}
412
+ {...fieldProps}
413
+ {...state.statusBubbles}
414
+ choices={[
415
+ { value: STATUS_BUBBLE_CHOICES[0], label: t('settings.on') },
416
+ { value: STATUS_BUBBLE_CHOICES[1], label: t('settings.off') },
417
+ ]}
418
+ onEdit={(text) => { props.edit('statusBubbles', text) }}
419
+ onReset={() => { props.resetField('statusBubbles') }}
420
+ />}
390
421
  <ChoiceField
391
422
  id="settings-pet-pet"
392
423
  label={t('settings.pet')}