@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
@@ -16,7 +16,7 @@
16
16
  import type { Context as ClientContext } from '@deepseek-ai/cordis'
17
17
  import type { ISessions } from '@deepseek-ai/dsh-api-session-controller/client'
18
18
  import type { SessionId } from '@deepseek-ai/dsh-api-remotes/client'
19
- import type { ConfigForm, ConfigForms } from '@deepseek-ai/dsh-client-ui-settings/client'
19
+ import type { ConfigForm, ConfigFormSnapshot } from '@deepseek-ai/dsh-client-ui-settings/client'
20
20
  // Type-only: pulls the locale plugin's Context merge (ctx.locale).
21
21
  import type {} from '@deepseek-ai/dsh-client-locale/client'
22
22
  // Type-only: pulls the shared configuration forms Context merge (ctx.configForms).
@@ -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 }),
@@ -126,38 +128,210 @@ declare module '@deepseek-ai/cordis' {
126
128
  }
127
129
 
128
130
  /**
129
- * The configuration form the settings card stages and saves through: the
130
- * family binder when dsh-web-settings is mounted, otherwise the shared form of
131
- * this plugin's own profile entry.
132
- *
133
- * The two are not interchangeable by name. A plugin's settings ARE its own
134
- * config on 0.1.7, so the form belongs to the profile entry that carries the
135
- * plugin — and only the family binder knows which entry that is, because the
136
- * family bundle renames child rows ('pet' becomes 'web-ui-pet' there) while a
137
- * standalone install keeps the package's own id.
138
- * @param ctx - client root context.
139
- * @returns the form for the pet's settings page.
131
+ * The profile entry ids a pet install is served under, most specific first. The
132
+ * family bundle renames child rows, so a standalone install and an aggregate
133
+ * one answer to different ids for the same 'pet' namespace.
140
134
  */
141
135
  const AGGREGATE_ENTRY_ID = 'web-ui-pet'
142
136
  const PET_ENTRY_IDS: readonly string[] = [AGGREGATE_ENTRY_ID, 'ui-pet', PET_SETTINGS_NS]
143
137
 
144
- function servedEntryId(forms: ConfigForms): string {
145
- let served: readonly string[] | undefined
146
- try {
147
- served = forms.describe().getSnapshot().view?.namespaces.map(view => view.ns)
148
- } catch {
149
- served = undefined
150
- }
151
- if (!served || served.length === 0) return PET_SETTINGS_NS
152
- return PET_ENTRY_IDS.find(id => served.includes(id)) ?? PET_SETTINGS_NS
138
+ /** How long the deferred form keeps retrying before it settles on the fallback. */
139
+ export const BINDER_RETRY_MS = 250
140
+ const BINDER_ATTEMPTS = 24
141
+
142
+ /** The snapshot an unresolved (or resolvable-but-unbound) form publishes. */
143
+ function pendingSnapshot<T>(status: 'loading' | 'unavailable'): ConfigFormSnapshot<T> {
144
+ return { status, value: undefined, base: undefined, user: undefined, revision: undefined, writable: false, mode: 'host' }
153
145
  }
154
146
 
155
- function petSettingsForm(ctx: ClientContext): ConfigForm<PetSettings> {
156
- const binder = ctx.get('webUiSettings')
157
- if (binder !== undefined && typeof binder.bind === 'function') {
158
- return binder.bind<PetSettings>({ namespace: PET_SETTINGS_NS })
147
+ /**
148
+ * A ConfigForm that late-binds to the family settings binder.
149
+ *
150
+ * The binder service (dsh-web-settings) is not guaranteed to be published by the
151
+ * time this plugin's apply() runs: the aggregate bundle mounts its inlined
152
+ * children — including the binder — inside an async mount that awaits the
153
+ * active-rows fetch, while standalone loader entries like this one apply
154
+ * synchronously in that window. A single early probe then permanently falls
155
+ * back to `configForms.get('pet')`, which is never a served row id under the
156
+ * aggregate (the row is `web-ui-pet`), so the settings card renders "not
157
+ * exposed" forever even though the Host serves the namespace.
158
+ *
159
+ * This form resolves through the binder as soon as the service appears and
160
+ * delegates the whole ConfigForm surface to it, re-publishing to its own
161
+ * subscribers on every swap. Until a form is resolved it publishes a loading
162
+ * (then unavailable) snapshot so the card shows a transient state, never a
163
+ * false "not exposed". If the binder never appears it retries for a bounded
164
+ * window, then permanently binds the non-bridge fallback by SERVED entry id.
165
+ */
166
+ class DeferredSettingsForm implements ConfigForm<PetSettings> {
167
+ private ctx: ClientContext
168
+ private current: ConfigForm<PetSettings> | undefined
169
+ private readonly listeners = new Set<() => void>()
170
+ private unsubscribeCurrent: (() => void) | undefined
171
+ private retryTimer: number | undefined
172
+ private attempts = 0
173
+ private disposed = false
174
+ private readonly fallback: ConfigForm<PetSettings>
175
+ private fallbackUnsubscribe: (() => void) | undefined
176
+
177
+ constructor(ctx: ClientContext) {
178
+ this.ctx = ctx
179
+ this.fallback = ctx.configForms.get<PetSettings>(this.resolveFallbackEntryId())
180
+ // No binder yet: the aggregate publishes it after an async mount, so keep
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.
183
+ if (!this.resolve() && !this.fallbackSettled()) this.scheduleRetry()
184
+ else if (this.current === undefined) this.adoptFallback()
185
+ }
186
+
187
+ /**
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.
197
+ */
198
+ private fallbackSettled(): boolean {
199
+ try {
200
+ return this.fallback.getSnapshot().status === 'ready'
201
+ } catch {
202
+ return false
203
+ }
204
+ }
205
+
206
+ /**
207
+ * Bind the fallback to a SERVED row id when the mirror can name one; a mirror
208
+ * that cannot is left to report its own unavailable state.
209
+ */
210
+ private resolveFallbackEntryId(): string {
211
+ try {
212
+ const served = this.ctx.configForms.describe().getSnapshot().view?.namespaces.map(view => view.ns)
213
+ if (served && served.length > 0) {
214
+ const hit = PET_ENTRY_IDS.find(id => served.includes(id))
215
+ if (hit !== undefined) return hit
216
+ }
217
+ } catch {
218
+ // fall through to the family namespace; the form reports unavailable.
219
+ }
220
+ return PET_SETTINGS_NS
221
+ }
222
+
223
+ /**
224
+ * Adopt the family binder the moment it is published.
225
+ * @returns true when a binder was bound, false when none is available yet.
226
+ */
227
+ private resolve(): boolean {
228
+ if (this.disposed) return false
229
+ let binder: { bind?: unknown } | undefined
230
+ try {
231
+ binder = this.ctx.get('webUiSettings') as { bind?: unknown } | undefined
232
+ } catch {
233
+ binder = undefined
234
+ }
235
+ if (binder === undefined || typeof binder.bind !== 'function') return false
236
+ let bound: ConfigForm<PetSettings>
237
+ try {
238
+ bound = (binder as { bind: <T>(spec: { namespace: string }) => ConfigForm<T> })
239
+ .bind<PetSettings>({ namespace: PET_SETTINGS_NS })
240
+ } catch {
241
+ return false
242
+ }
243
+ this.current = bound
244
+ // Mirror the bound form's changes to our own subscribers; a later re-resolve
245
+ // swaps this subscription to the new form.
246
+ this.unsubscribeCurrent?.()
247
+ this.unsubscribeCurrent = bound.subscribe(() => this.publish())
248
+ this.publish()
249
+ return true
250
+ }
251
+
252
+ /**
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).
257
+ */
258
+ private adoptFallback(): void {
259
+ this.current = this.fallback
260
+ this.fallbackUnsubscribe ??= this.fallback.subscribe(() => this.publish())
261
+ this.unsubscribeCurrent = this.fallbackUnsubscribe
262
+ this.publish()
263
+ }
264
+
265
+ /** Retry the binder lookup a few times across the aggregate's async mount. */
266
+ private scheduleRetry(): void {
267
+ if (this.disposed) return
268
+ if (this.attempts >= BINDER_ATTEMPTS) {
269
+ this.adoptFallback()
270
+ return
271
+ }
272
+ this.attempts += 1
273
+ this.retryTimer = window.setTimeout(() => {
274
+ this.retryTimer = undefined
275
+ if (this.disposed) return
276
+ if (this.resolve()) return
277
+ // The binder still absent: keep waiting only while the shared form cannot
278
+ // answer for itself, otherwise a standalone install stalls for the window.
279
+ if (this.fallbackSettled()) {
280
+ this.attempts = BINDER_ATTEMPTS
281
+ this.adoptFallback()
282
+ return
283
+ }
284
+ this.scheduleRetry()
285
+ }, BINDER_RETRY_MS)
286
+ }
287
+
288
+ private publish(): void {
289
+ for (const listener of this.listeners) listener()
290
+ }
291
+
292
+ /** The resolved form, or a placeholder snapshot when still pending. */
293
+ private snapshot(): ConfigFormSnapshot<PetSettings> {
294
+ return this.current?.getSnapshot() ?? pendingSnapshot<PetSettings>(this.attempts >= BINDER_ATTEMPTS ? 'unavailable' : 'loading')
295
+ }
296
+
297
+ getSnapshot(): ConfigFormSnapshot<PetSettings> {
298
+ return this.snapshot()
299
+ }
300
+
301
+ subscribe(listener: () => void): () => void {
302
+ this.listeners.add(listener)
303
+ return () => { this.listeners.delete(listener) }
304
+ }
305
+
306
+ mutate(ops: Parameters<ConfigForm<PetSettings>['mutate']>[0], expectedRevision?: number): Promise<boolean> {
307
+ return this.current?.mutate(ops, expectedRevision) ?? Promise.resolve(false)
308
+ }
309
+
310
+ set(field: string, value: unknown): Promise<boolean> {
311
+ return this.current?.set(field, value) ?? Promise.resolve(false)
312
+ }
313
+
314
+ unset(field: string): Promise<boolean> {
315
+ return this.current?.unset(field) ?? Promise.resolve(false)
316
+ }
317
+
318
+ /** Release the retry timer and mirror subscription; not part of ConfigForm. */
319
+ dispose(): void {
320
+ if (this.disposed) return
321
+ this.disposed = true
322
+ if (this.retryTimer !== undefined) {
323
+ window.clearTimeout(this.retryTimer)
324
+ this.retryTimer = undefined
325
+ }
326
+ this.unsubscribeCurrent?.()
327
+ this.unsubscribeCurrent = undefined
328
+ this.current = undefined
329
+ this.listeners.clear()
330
+ // The shared per-entry form carries no disposer of its own (ConfigForm is a
331
+ // pure read/write surface); only this form's own subscriptions are released.
332
+ this.fallbackUnsubscribe?.()
333
+ this.fallbackUnsubscribe = undefined
159
334
  }
160
- return ctx.configForms.get<PetSettings>(servedEntryId(ctx.configForms))
161
335
  }
162
336
 
163
337
  /**
@@ -199,7 +373,7 @@ export function apply(ctx: ClientContext): void {
199
373
  defaultPetRendererRegistry.register(live2dRenderer)
200
374
  defaultPetRendererRegistry.register(frames2dRenderer)
201
375
 
202
- const settingsForm = petSettingsForm(ctx)
376
+ const settingsForm = new DeferredSettingsForm(ctx)
203
377
  const enabled = (): boolean => {
204
378
  const snapshot = settingsForm.getSnapshot()
205
379
  return snapshot.status === 'ready'
@@ -412,6 +586,19 @@ export function apply(ctx: ClientContext): void {
412
586
  // Ignore; next poll resyncs.
413
587
  })
414
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
+ },
415
602
  feedbackDone: () => {
416
603
  setFeedback(null)
417
604
  },
@@ -466,7 +653,16 @@ export function apply(ctx: ClientContext): void {
466
653
  // root then owns the whole surface, so a root-keyed suppressor (the
467
654
  // portrait mobile layer, which hides [data-dsh-plugin="pet"]) really
468
655
  // hides the sprite instead of missing the portaled float.
469
- 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 }))
470
666
 
471
667
  let uiGone = false
472
668
  disposeUi = () => {
@@ -500,6 +696,9 @@ export function apply(ctx: ClientContext): void {
500
696
  ctx.effect(
501
697
  () => () => {
502
698
  unsubscribeSettings()
699
+ // Release the deferred form's retry timer and its mirror subscription so a
700
+ // disposed fiber can never bind or publish after teardown.
701
+ settingsForm.dispose()
503
702
  killUi()
504
703
  },
505
704
  'pet: client lifecycle',
@@ -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)',
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
  /**
@@ -258,6 +278,22 @@ export function petSettingsSection(
258
278
  persisted: Partial<PetDisplayConfig> = {},
259
279
  committed: Partial<PetDisplayConfig> = {},
260
280
  ): PetSettingsSection {
281
+ // `visible` and `enabled` answer two DIFFERENT questions and are kept
282
+ // apart on purpose (#1762):
283
+ //
284
+ // - `visible` is the pet's own hide/show intent, persisted in its pet.json
285
+ // and written by the sprite's hide/summon control and by the aggregate
286
+ // shell's fallback switch.
287
+ // - `enabled` is the plugin master switch, which hides the pet whatever that
288
+ // own intent says.
289
+ //
290
+ // The effective "is it on screen" state is the conjunction, and it belongs at
291
+ // the single point that PRODUCES the view (see PetService.state), never here
292
+ // and never written back to pet.json. Folding it into this field is what made
293
+ // the master switch one-way: switching it off stored the derived `false` as
294
+ // the user's own intent, so switching it on again (or restarting) read that
295
+ // stored `false` back and the pet never returned.
296
+ const enabled = readLive(config.enabled, PET_FORM_DEFAULTS.enabled)
261
297
  return {
262
298
  visible: displayField('visible', config.visible, persisted, committed),
263
299
  size: displayField('size', config.size, persisted, committed),
@@ -265,8 +301,13 @@ export function petSettingsSection(
265
301
  bottom: displayField('bottom', config.bottom, persisted, committed),
266
302
  bubbleScale: displayField('bubbleScale', config.bubbleScale, persisted, committed),
267
303
  petId: readLive(config.petId, fallbackPetId),
268
- enabled: readLive(config.enabled, PET_FORM_DEFAULTS.enabled),
304
+ enabled,
269
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)),
270
311
  }
271
312
  }
272
313
 
@@ -328,6 +369,7 @@ function applyImpl(ctx: Context, config: PetPluginConfig = {}): void {
328
369
  ...config,
329
370
  enabled: readLive(config.enabled, PET_FORM_DEFAULTS.enabled),
330
371
  decorationEnabled: readLive(config.decorationEnabled, PET_FORM_DEFAULTS.decorationEnabled),
372
+ statusBubbles: statusBubbleMode(readLive<PetStatusBubbleMode | undefined>(config.statusBubbles, undefined)),
331
373
  registry,
332
374
  })
333
375
  // The mirror back into the settings document (see syncSettingsFromPet) has to
@@ -0,0 +1,130 @@
1
+ import { describe, expect, it, vi } from 'vitest'
2
+ import { MAX_PANEL_ACTIONS, normalizePanelAction, PanelActionRegistry } from './panel-actions.ts'
3
+
4
+ /**
5
+ * The hover-panel action registry (issue #6). Registration validates the
6
+ * shape a plugin hands the pet service, the table stays ordered and bounded,
7
+ * and a click dispatches to the registering plugin's own callback.
8
+ */
9
+
10
+ describe('normalizePanelAction', () => {
11
+ it('accepts a registration with the documented shape', () => {
12
+ expect(normalizePanelAction({ id: 'pet-quota-swap', label: '换装' })).toEqual({
13
+ id: 'pet-quota-swap',
14
+ label: '换装',
15
+ order: 0,
16
+ })
17
+ })
18
+
19
+ it('carries the optional tooltip and order the plugin declared', () => {
20
+ expect(normalizePanelAction({ id: 'swap', label: '换装', title: '切换到下一只宠物', order: -5 }))
21
+ .toEqual({ id: 'swap', label: '换装', title: '切换到下一只宠物', order: -5 })
22
+ })
23
+
24
+ it('rejects an id a click could not be dispatched back on', () => {
25
+ for (const id of [undefined, '', 'Swap', 'pet quota', '../escape', 'a'.repeat(65)]) {
26
+ expect(normalizePanelAction({ id, label: '换装' })).toBeUndefined()
27
+ }
28
+ })
29
+
30
+ it('rejects a registration with no label and truncates an over-long one', () => {
31
+ expect(normalizePanelAction({ id: 'swap', label: ' ' })).toBeUndefined()
32
+ expect(normalizePanelAction({ id: 'swap' })).toBeUndefined()
33
+ expect(normalizePanelAction({ id: 'swap', label: 'x'.repeat(80) })?.label).toBe('x'.repeat(24))
34
+ })
35
+
36
+ it('ignores unknown fields and a non-numeric order', () => {
37
+ expect(normalizePanelAction({ id: 'swap', label: '换装', order: 'first', evil: true }))
38
+ .toEqual({ id: 'swap', label: '换装', order: 0 })
39
+ })
40
+ })
41
+
42
+ describe('PanelActionRegistry', () => {
43
+ it('serves the registered actions and dispatches a click to the plugin', async () => {
44
+ const registry = new PanelActionRegistry()
45
+ const onSelect = vi.fn()
46
+ registry.register({ id: 'swap', label: '换装', onSelect })
47
+
48
+ expect(registry.views()).toEqual([{ id: 'swap', label: '换装', order: 0 }])
49
+ await expect(registry.select('swap', { petId: 'whale-girl' })).resolves.toBe(true)
50
+ expect(onSelect).toHaveBeenCalledWith({ petId: 'whale-girl' })
51
+ })
52
+
53
+ it('reports an unregistered id instead of invoking anything', async () => {
54
+ const registry = new PanelActionRegistry()
55
+ const onSelect = vi.fn()
56
+ registry.register({ id: 'swap', label: '换装', onSelect })
57
+
58
+ await expect(registry.select('other', { petId: 'whale-girl' })).resolves.toBe(false)
59
+ expect(onSelect).not.toHaveBeenCalled()
60
+ })
61
+
62
+ it('lets a later registration of the same id replace the earlier one', async () => {
63
+ const registry = new PanelActionRegistry()
64
+ const first = vi.fn()
65
+ const second = vi.fn()
66
+ registry.register({ id: 'swap', label: '换装', onSelect: first })
67
+ registry.register({ id: 'swap', label: '更衣', onSelect: second })
68
+
69
+ await registry.select('swap', { petId: 'whale-girl' })
70
+ expect(first).not.toHaveBeenCalled()
71
+ expect(second).toHaveBeenCalledTimes(1)
72
+ expect(registry.views()).toEqual([{ id: 'swap', label: '更衣', order: 0 }])
73
+ })
74
+
75
+ it('keeps the replacing registration when the superseded one disposes', async () => {
76
+ // The trap this guards: a hot-reloaded plugin disposes its old
77
+ // registration after the new one is in, and the naive "delete by id"
78
+ // disposer would take the live action with it.
79
+ const registry = new PanelActionRegistry()
80
+ const disposeFirst = registry.register({ id: 'swap', label: '换装', onSelect: vi.fn() })
81
+ registry.register({ id: 'swap', label: '更衣', onSelect: vi.fn() })
82
+
83
+ disposeFirst()
84
+ expect(registry.views().map(view => view.label)).toEqual(['更衣'])
85
+ })
86
+
87
+ it('reclaims the action when the registering plugin disposes it', async () => {
88
+ const registry = new PanelActionRegistry()
89
+ const dispose = registry.register({ id: 'swap', label: '换装', onSelect: vi.fn() })
90
+
91
+ dispose()
92
+ expect(registry.views()).toEqual([])
93
+ await expect(registry.select('swap', { petId: 'whale-girl' })).resolves.toBe(false)
94
+ // Disposing twice is the shape an effect re-run produces; it is a no-op.
95
+ expect(() => dispose()).not.toThrow()
96
+ })
97
+
98
+ it('renders the registered block in order, ties on id', () => {
99
+ const registry = new PanelActionRegistry()
100
+ registry.register({ id: 'b', label: 'B', order: 1, onSelect: vi.fn() })
101
+ registry.register({ id: 'a', label: 'A', order: 1, onSelect: vi.fn() })
102
+ registry.register({ id: 'c', label: 'C', order: 0, onSelect: vi.fn() })
103
+
104
+ expect(registry.views().map(view => view.id)).toEqual(['c', 'a', 'b'])
105
+ })
106
+
107
+ it('refuses a malformed registration where it was written', () => {
108
+ const registry = new PanelActionRegistry()
109
+ expect(() => registry.register({ label: '换装', onSelect: vi.fn() })).toThrow(/invalid panel action/)
110
+ expect(() => registry.register({ id: 'swap', label: '换装' })).toThrow(/onSelect/)
111
+ })
112
+
113
+ it('bounds the row so plugins cannot grow it without limit', () => {
114
+ const registry = new PanelActionRegistry()
115
+ for (let index = 0; index < MAX_PANEL_ACTIONS; index += 1) {
116
+ registry.register({ id: 'swap-' + index, label: '换装', onSelect: vi.fn() })
117
+ }
118
+ expect(registry.views()).toHaveLength(MAX_PANEL_ACTIONS)
119
+ expect(() => registry.register({ id: 'swap-overflow', label: '换装', onSelect: vi.fn() })).toThrow(/limit/)
120
+ // Re-registering an id that is already in the row is not a new row.
121
+ expect(() => registry.register({ id: 'swap-0', label: '换装', onSelect: vi.fn() })).not.toThrow()
122
+ })
123
+
124
+ it('propagates a failing callback so the caller can report it', async () => {
125
+ const registry = new PanelActionRegistry()
126
+ registry.register({ id: 'swap', label: '换装', onSelect: () => { throw new Error('plugin bug') } })
127
+
128
+ await expect(registry.select('swap', { petId: 'whale-girl' })).rejects.toThrow('plugin bug')
129
+ })
130
+ })