@linxin666/dsh-pet 0.4.4 → 0.4.5

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.
@@ -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).
@@ -126,38 +126,202 @@ declare module '@deepseek-ai/cordis' {
126
126
  }
127
127
 
128
128
  /**
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.
129
+ * The profile entry ids a pet install is served under, most specific first. The
130
+ * family bundle renames child rows, so a standalone install and an aggregate
131
+ * one answer to different ids for the same 'pet' namespace.
140
132
  */
141
133
  const AGGREGATE_ENTRY_ID = 'web-ui-pet'
142
134
  const PET_ENTRY_IDS: readonly string[] = [AGGREGATE_ENTRY_ID, 'ui-pet', PET_SETTINGS_NS]
143
135
 
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
136
+ /** How long the deferred form keeps retrying before it settles on the fallback. */
137
+ export const BINDER_RETRY_MS = 250
138
+ const BINDER_ATTEMPTS = 24
139
+
140
+ /** The snapshot an unresolved (or resolvable-but-unbound) form publishes. */
141
+ function pendingSnapshot<T>(status: 'loading' | 'unavailable'): ConfigFormSnapshot<T> {
142
+ return { status, value: undefined, base: undefined, user: undefined, revision: undefined, writable: false, mode: 'host' }
153
143
  }
154
144
 
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 })
145
+ /**
146
+ * A ConfigForm that late-binds to the family settings binder.
147
+ *
148
+ * The binder service (dsh-web-settings) is not guaranteed to be published by the
149
+ * time this plugin's apply() runs: the aggregate bundle mounts its inlined
150
+ * children — including the binder — inside an async mount that awaits the
151
+ * active-rows fetch, while standalone loader entries like this one apply
152
+ * synchronously in that window. A single early probe then permanently falls
153
+ * back to `configForms.get('pet')`, which is never a served row id under the
154
+ * aggregate (the row is `web-ui-pet`), so the settings card renders "not
155
+ * exposed" forever even though the Host serves the namespace.
156
+ *
157
+ * This form resolves through the binder as soon as the service appears and
158
+ * delegates the whole ConfigForm surface to it, re-publishing to its own
159
+ * subscribers on every swap. Until a form is resolved it publishes a loading
160
+ * (then unavailable) snapshot so the card shows a transient state, never a
161
+ * false "not exposed". If the binder never appears it retries for a bounded
162
+ * window, then permanently binds the non-bridge fallback by SERVED entry id.
163
+ */
164
+ class DeferredSettingsForm implements ConfigForm<PetSettings> {
165
+ private ctx: ClientContext
166
+ private current: ConfigForm<PetSettings> | undefined
167
+ private readonly listeners = new Set<() => void>()
168
+ private unsubscribeCurrent: (() => void) | undefined
169
+ private retryTimer: number | undefined
170
+ private attempts = 0
171
+ private disposed = false
172
+ private readonly fallback: ConfigForm<PetSettings>
173
+ private fallbackUnsubscribe: (() => void) | undefined
174
+
175
+ constructor(ctx: ClientContext) {
176
+ this.ctx = ctx
177
+ this.fallback = ctx.configForms.get<PetSettings>(this.resolveFallbackEntryId())
178
+ // 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.
180
+ if (!this.resolve() && !this.fallbackSettled()) this.scheduleRetry()
181
+ else if (this.current === undefined) this.adoptFallback()
182
+ }
183
+
184
+ /**
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
+ */
189
+ private fallbackSettled(): boolean {
190
+ try {
191
+ return this.fallback.getSnapshot().status !== 'unavailable'
192
+ } catch {
193
+ return false
194
+ }
195
+ }
196
+
197
+ /**
198
+ * Bind the fallback to a SERVED row id when the mirror can name one; a mirror
199
+ * that cannot is left to report its own unavailable state.
200
+ */
201
+ private resolveFallbackEntryId(): string {
202
+ try {
203
+ const served = this.ctx.configForms.describe().getSnapshot().view?.namespaces.map(view => view.ns)
204
+ if (served && served.length > 0) {
205
+ const hit = PET_ENTRY_IDS.find(id => served.includes(id))
206
+ if (hit !== undefined) return hit
207
+ }
208
+ } catch {
209
+ // fall through to the family namespace; the form reports unavailable.
210
+ }
211
+ return PET_SETTINGS_NS
212
+ }
213
+
214
+ /**
215
+ * Adopt the family binder the moment it is published.
216
+ * @returns true when a binder was bound, false when none is available yet.
217
+ */
218
+ private resolve(): boolean {
219
+ if (this.disposed) return false
220
+ let binder: { bind?: unknown } | undefined
221
+ try {
222
+ binder = this.ctx.get('webUiSettings') as { bind?: unknown } | undefined
223
+ } catch {
224
+ binder = undefined
225
+ }
226
+ if (binder === undefined || typeof binder.bind !== 'function') return false
227
+ let bound: ConfigForm<PetSettings>
228
+ try {
229
+ bound = (binder as { bind: <T>(spec: { namespace: string }) => ConfigForm<T> })
230
+ .bind<PetSettings>({ namespace: PET_SETTINGS_NS })
231
+ } catch {
232
+ return false
233
+ }
234
+ this.current = bound
235
+ // Mirror the bound form's changes to our own subscribers; a later re-resolve
236
+ // swaps this subscription to the new form.
237
+ this.unsubscribeCurrent?.()
238
+ this.unsubscribeCurrent = bound.subscribe(() => this.publish())
239
+ this.publish()
240
+ return true
241
+ }
242
+
243
+ /**
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).
247
+ */
248
+ private adoptFallback(): void {
249
+ this.current = this.fallback
250
+ this.fallbackUnsubscribe ??= this.fallback.subscribe(() => this.publish())
251
+ this.unsubscribeCurrent = this.fallbackUnsubscribe
252
+ this.publish()
253
+ }
254
+
255
+ /** Retry the binder lookup a few times across the aggregate's async mount. */
256
+ private scheduleRetry(): void {
257
+ if (this.disposed) return
258
+ if (this.attempts >= BINDER_ATTEMPTS) {
259
+ this.adoptFallback()
260
+ return
261
+ }
262
+ this.attempts += 1
263
+ this.retryTimer = window.setTimeout(() => {
264
+ this.retryTimer = undefined
265
+ if (this.disposed) return
266
+ if (this.resolve()) return
267
+ // The binder still absent: keep waiting only while the shared form cannot
268
+ // answer for itself, otherwise a standalone install stalls for the window.
269
+ if (this.fallbackSettled()) {
270
+ this.attempts = BINDER_ATTEMPTS
271
+ this.adoptFallback()
272
+ return
273
+ }
274
+ this.scheduleRetry()
275
+ }, BINDER_RETRY_MS)
276
+ }
277
+
278
+ private publish(): void {
279
+ for (const listener of this.listeners) listener()
280
+ }
281
+
282
+ /** The resolved form, or a placeholder snapshot when still pending. */
283
+ private snapshot(): ConfigFormSnapshot<PetSettings> {
284
+ return this.current?.getSnapshot() ?? pendingSnapshot<PetSettings>(this.attempts >= BINDER_ATTEMPTS ? 'unavailable' : 'loading')
285
+ }
286
+
287
+ getSnapshot(): ConfigFormSnapshot<PetSettings> {
288
+ return this.snapshot()
289
+ }
290
+
291
+ subscribe(listener: () => void): () => void {
292
+ this.listeners.add(listener)
293
+ return () => { this.listeners.delete(listener) }
294
+ }
295
+
296
+ mutate(ops: Parameters<ConfigForm<PetSettings>['mutate']>[0], expectedRevision?: number): Promise<boolean> {
297
+ return this.current?.mutate(ops, expectedRevision) ?? Promise.resolve(false)
298
+ }
299
+
300
+ set(field: string, value: unknown): Promise<boolean> {
301
+ return this.current?.set(field, value) ?? Promise.resolve(false)
302
+ }
303
+
304
+ unset(field: string): Promise<boolean> {
305
+ return this.current?.unset(field) ?? Promise.resolve(false)
306
+ }
307
+
308
+ /** Release the retry timer and mirror subscription; not part of ConfigForm. */
309
+ dispose(): void {
310
+ if (this.disposed) return
311
+ this.disposed = true
312
+ if (this.retryTimer !== undefined) {
313
+ window.clearTimeout(this.retryTimer)
314
+ this.retryTimer = undefined
315
+ }
316
+ this.unsubscribeCurrent?.()
317
+ this.unsubscribeCurrent = undefined
318
+ this.current = undefined
319
+ this.listeners.clear()
320
+ // The shared per-entry form carries no disposer of its own (ConfigForm is a
321
+ // pure read/write surface); only this form's own subscriptions are released.
322
+ this.fallbackUnsubscribe?.()
323
+ this.fallbackUnsubscribe = undefined
159
324
  }
160
- return ctx.configForms.get<PetSettings>(servedEntryId(ctx.configForms))
161
325
  }
162
326
 
163
327
  /**
@@ -199,7 +363,7 @@ export function apply(ctx: ClientContext): void {
199
363
  defaultPetRendererRegistry.register(live2dRenderer)
200
364
  defaultPetRendererRegistry.register(frames2dRenderer)
201
365
 
202
- const settingsForm = petSettingsForm(ctx)
366
+ const settingsForm = new DeferredSettingsForm(ctx)
203
367
  const enabled = (): boolean => {
204
368
  const snapshot = settingsForm.getSnapshot()
205
369
  return snapshot.status === 'ready'
@@ -500,6 +664,9 @@ export function apply(ctx: ClientContext): void {
500
664
  ctx.effect(
501
665
  () => () => {
502
666
  unsubscribeSettings()
667
+ // Release the deferred form's retry timer and its mirror subscription so a
668
+ // disposed fiber can never bind or publish after teardown.
669
+ settingsForm.dispose()
503
670
  killUi()
504
671
  },
505
672
  'pet: client lifecycle',
package/src/index.ts CHANGED
@@ -258,6 +258,22 @@ export function petSettingsSection(
258
258
  persisted: Partial<PetDisplayConfig> = {},
259
259
  committed: Partial<PetDisplayConfig> = {},
260
260
  ): PetSettingsSection {
261
+ // `visible` and `enabled` answer two DIFFERENT questions and are kept
262
+ // apart on purpose (#1762):
263
+ //
264
+ // - `visible` is the pet's own hide/show intent, persisted in its pet.json
265
+ // and written by the sprite's hide/summon control and by the aggregate
266
+ // shell's fallback switch.
267
+ // - `enabled` is the plugin master switch, which hides the pet whatever that
268
+ // own intent says.
269
+ //
270
+ // The effective "is it on screen" state is the conjunction, and it belongs at
271
+ // the single point that PRODUCES the view (see PetService.state), never here
272
+ // and never written back to pet.json. Folding it into this field is what made
273
+ // the master switch one-way: switching it off stored the derived `false` as
274
+ // the user's own intent, so switching it on again (or restarting) read that
275
+ // stored `false` back and the pet never returned.
276
+ const enabled = readLive(config.enabled, PET_FORM_DEFAULTS.enabled)
261
277
  return {
262
278
  visible: displayField('visible', config.visible, persisted, committed),
263
279
  size: displayField('size', config.size, persisted, committed),
@@ -265,7 +281,7 @@ export function petSettingsSection(
265
281
  bottom: displayField('bottom', config.bottom, persisted, committed),
266
282
  bubbleScale: displayField('bubbleScale', config.bubbleScale, persisted, committed),
267
283
  petId: readLive(config.petId, fallbackPetId),
268
- enabled: readLive(config.enabled, PET_FORM_DEFAULTS.enabled),
284
+ enabled,
269
285
  decorationEnabled: readLive(config.decorationEnabled, PET_FORM_DEFAULTS.decorationEnabled),
270
286
  }
271
287
  }
@@ -315,7 +315,8 @@ describe('loadPetRegistry', () => {
315
315
  })
316
316
 
317
317
  // The repo checkout also resolves doro and miku (frames2d gameplay pets),
318
- // jyn (frames2d gameplay pet) and starry-doll (community sprite2d pet) from
318
+ // jyn and jyn-foxtail (frames2d gameplay pets), long-niang (sprite2d pet)
319
+ // and starry-doll (community sprite2d pet) from
319
320
  // assets/; the npm files whitelist excludes them (Workshop delivery), so
320
321
  // npm installs see the atlas pets until a Workshop install lands them
321
322
  // under $DSH_HOME/pets. blue-throated-bee-eater ships bundled alongside
@@ -324,6 +325,8 @@ describe('loadPetRegistry', () => {
324
325
  'blue-throated-bee-eater',
325
326
  'doro',
326
327
  'jyn',
328
+ 'jyn-foxtail',
329
+ 'long-niang',
327
330
  'miku',
328
331
  'ouo-neko',
329
332
  'starry-doll',
@@ -341,6 +344,13 @@ describe('loadPetRegistry', () => {
341
344
  displayName: '女仆鲸鱼娘',
342
345
  renderer: 'frames2d',
343
346
  })
347
+ expect(registry.byId('long-niang')).toMatchObject({
348
+ displayName: '龙娘',
349
+ atlasRows: 11,
350
+ columns: 8,
351
+ rows: [6, 8, 8, 4, 5, 8, 6, 6, 6],
352
+ })
353
+ expect(existsSync(petAtlasFile(registry.byId('long-niang')!))).toBe(true)
344
354
  expect(registry.byId('ouo-neko')).toMatchObject({
345
355
  displayName: 'OUO Neko',
346
356
  atlasRows: 11,
package/src/service.ts CHANGED
@@ -832,7 +832,13 @@ export class PetService extends Service {
832
832
  this.syncSettingsFromPet()
833
833
  }
834
834
  const next = { ...this.ledger.snapshot.display }
835
- next.visible = section.visible && (section.enabled ?? true)
835
+ // The pet's own hide/show intent, stored verbatim. The master switch is
836
+ // applied when the state view is produced (see the state view below), not
837
+ // here: writing the conjunction into pet.json turned `enabled: false` into
838
+ // a persisted "the user hid the pet" and the switch could never be undone -
839
+ // re-enabling it (or restarting) read that stored `false` straight back
840
+ // (#1762).
841
+ next.visible = section.visible
836
842
  next.size = Math.round(Math.min(DISPLAY_SIZE_MAX, Math.max(DISPLAY_SIZE_MIN, section.size)))
837
843
  next.right = Math.round(Math.min(DISPLAY_INSET_MAX, Math.max(0, section.right)))
838
844
  next.bottom = Math.round(Math.min(DISPLAY_INSET_MAX, Math.max(0, section.bottom)))
@@ -934,7 +940,11 @@ export class PetService extends Service {
934
940
  ...(decoration === undefined ? {} : { decoration }),
935
941
  ...(announcement === undefined ? {} : { announcement }),
936
942
  affinity: this.ledger.affinityView(Date.now()),
937
- display: { ...this.ledger.snapshot.display },
943
+ // The one place the two visibility answers are combined: the pet's own
944
+ // hide/show intent AND the plugin master switch. Producing the effective
945
+ // value here - rather than storing it - keeps the switch reversible and
946
+ // keeps pet.json describing only what the user chose (#1762).
947
+ display: { ...this.ledger.snapshot.display, visible: this.isEnabled() && this.ledger.snapshot.display.visible },
938
948
  pet: {
939
949
  id: entry.id,
940
950
  displayName: entry.displayName,