@linxin666/dsh-pet 0.4.8 → 0.4.10

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 (47) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +7 -2
  3. package/README.zh.md +7 -2
  4. package/contracts/voice-pack-v1.schema.json +27 -0
  5. package/lib/client.js +24 -13
  6. package/lib/client.js.map +1 -1
  7. package/lib/index.js +160 -28
  8. package/lib/types/affinity.d.ts +26 -3
  9. package/lib/types/affinity.d.ts.map +1 -1
  10. package/lib/types/affinity.js +27 -4
  11. package/lib/types/client/PetDockEntry.d.ts +5 -0
  12. package/lib/types/client/PetDockEntry.d.ts.map +1 -1
  13. package/lib/types/client/PetDockEntry.js +1 -1
  14. package/lib/types/client/PetSprite.d.ts +5 -0
  15. package/lib/types/client/PetSprite.d.ts.map +1 -1
  16. package/lib/types/client/PetSprite.js +20 -8
  17. package/lib/types/client/index.d.ts.map +1 -1
  18. package/lib/types/client/index.js +15 -1
  19. package/lib/types/index.d.ts +1 -1
  20. package/lib/types/index.d.ts.map +1 -1
  21. package/lib/types/ledger.d.ts +10 -1
  22. package/lib/types/ledger.d.ts.map +1 -1
  23. package/lib/types/ledger.js +11 -1
  24. package/lib/types/pair-access.d.ts.map +1 -1
  25. package/lib/types/pair-access.js +26 -3
  26. package/lib/types/service.d.ts +14 -12
  27. package/lib/types/service.d.ts.map +1 -1
  28. package/lib/types/service.js +22 -17
  29. package/lib/types/voice-pack.d.ts +20 -1
  30. package/lib/types/voice-pack.d.ts.map +1 -1
  31. package/lib/types/voice-pack.js +86 -3
  32. package/package.json +24 -24
  33. package/src/affinity.test.ts +42 -0
  34. package/src/affinity.ts +46 -3
  35. package/src/client/PetDockEntry.tsx +6 -0
  36. package/src/client/PetSprite.test.tsx +42 -0
  37. package/src/client/PetSprite.tsx +24 -8
  38. package/src/client/index.test.tsx +4 -0
  39. package/src/client/index.ts +15 -1
  40. package/src/index.ts +2 -0
  41. package/src/ledger.test.ts +19 -0
  42. package/src/ledger.ts +15 -1
  43. package/src/pair-access.ts +26 -3
  44. package/src/service.test.ts +61 -0
  45. package/src/service.ts +27 -18
  46. package/src/voice-pack.test.ts +112 -0
  47. package/src/voice-pack.ts +101 -3
package/src/affinity.ts CHANGED
@@ -56,6 +56,24 @@ export const AFFINITY_RANKS = [
56
56
  { min: 100_000, name: '鲸生共渡', emoji: '*********' },
57
57
  ] as const
58
58
 
59
+ /** One tier of a pet-declared affinity ladder (voice.json `panel.ranks`). */
60
+ export interface AffinityRankName {
61
+ /** Minimum points for this tier; the first entry is always 0. */
62
+ min: number
63
+ /** Default rank name shown in every locale without an English variant. */
64
+ name: string
65
+ /** Optional English name used when the UI locale is English. */
66
+ nameEn?: string
67
+ }
68
+
69
+ /** A resolved rank: the effective name plus the display-only marker. */
70
+ export interface AffinityRank {
71
+ min: number
72
+ name: string
73
+ nameEn?: string
74
+ emoji: string
75
+ }
76
+
59
77
  /** English translations for the 9 built-in affinity rank names (#1226). */
60
78
  export const AFFINITY_RANKS_EN: Readonly<Record<string, string>> = {
61
79
  '幼鲸': 'Baby Whale',
@@ -116,8 +134,8 @@ export interface InteractionOutcome {
116
134
  accepted: boolean
117
135
  }
118
136
 
119
- /** Rank for a point total. */
120
- export function rankOf(points: number): (typeof AFFINITY_RANKS)[number] {
137
+ /** Built-in ladder lookup (the fallback for pets with no declared ladder). */
138
+ function builtinRankOf(points: number): (typeof AFFINITY_RANKS)[number] {
121
139
  let rank: (typeof AFFINITY_RANKS)[number] = AFFINITY_RANKS[0]!
122
140
  for (const candidate of AFFINITY_RANKS) {
123
141
  if (points >= candidate.min) rank = candidate
@@ -125,10 +143,33 @@ export function rankOf(points: number): (typeof AFFINITY_RANKS)[number] {
125
143
  return rank
126
144
  }
127
145
 
146
+ /**
147
+ * Rank for a point total. A pet-declared ladder replaces the tier names while
148
+ * the built-in ladder still supplies the display marker; without a ladder the
149
+ * built-in ladder answers unchanged. Points, thresholds and the persisted
150
+ * ledger are untouched — the ladder is a display-only rename.
151
+ */
152
+ export function rankOf(points: number, ladder?: readonly AffinityRankName[]): AffinityRank {
153
+ const builtin = builtinRankOf(points)
154
+ if (ladder === undefined || ladder.length === 0) return builtin
155
+ let selected = ladder[0]!
156
+ for (const candidate of ladder) {
157
+ if (points >= candidate.min) selected = candidate
158
+ }
159
+ return {
160
+ min: selected.min,
161
+ name: selected.name,
162
+ ...(selected.nameEn === undefined ? {} : { nameEn: selected.nameEn }),
163
+ emoji: builtin.emoji,
164
+ }
165
+ }
166
+
128
167
  /** Read-only affinity snapshot suited for the RPC view shape. */
129
168
  export interface PetAffinityView {
130
169
  points: number
131
170
  rank: string
171
+ /** English rank name when the pet declared one (an English UI shows this). */
172
+ rankEn?: string
132
173
  rankEmoji: string
133
174
  pets: number
134
175
  feeds: number
@@ -144,11 +185,13 @@ export function affinityViewOf(
144
185
  state: AffinityState,
145
186
  nowMs: number,
146
187
  config: AffinityConfig = defaultAffinityConfig,
188
+ ladder?: readonly AffinityRankName[],
147
189
  ): PetAffinityView {
148
- const rank = rankOf(state.points)
190
+ const rank = rankOf(state.points, ladder)
149
191
  return {
150
192
  points: state.points,
151
193
  rank: rank.name,
194
+ ...(rank.nameEn === undefined ? {} : { rankEn: rank.nameEn }),
152
195
  rankEmoji: rank.emoji,
153
196
  pets: state.pets,
154
197
  feeds: state.feeds,
@@ -67,6 +67,11 @@ export type PetDockEntryProps =
67
67
  * own the whole pet surface as one unit.
68
68
  */
69
69
  portalTarget?: Element
70
+ /**
71
+ * Active UI locale id, forwarded to the sprite so a pet-declared English
72
+ * rank name (`rankEn`) applies when the UI language is English.
73
+ */
74
+ lang?: string
70
75
  }
71
76
 
72
77
  const DEFAULT_DISPLAY: PetDisplayConfig = { visible: true, size: 160, right: 24, bottom: 20, bubbleScale: 1 }
@@ -128,6 +133,7 @@ export function PetDockEntry(props: PetDockEntryProps): ReactElement {
128
133
  portalTarget={props.portalTarget}
129
134
  dragDisabled={snapshot.gameplay?.mode === 'work'}
130
135
  {...(aux === null ? {} : { bus: aux.bus })}
136
+ lang={props.lang}
131
137
  {...(gameplay === undefined || aux === null
132
138
  ? {}
133
139
  : {
@@ -195,6 +195,48 @@ describe('PetSprite affinity rank localization (#1226)', () => {
195
195
  document.documentElement.lang = 'zh'
196
196
  }
197
197
  })
198
+
199
+ it('uses a pet-declared English rank name when the UI locale is en', () => {
200
+ document.documentElement.lang = 'en'
201
+ try {
202
+ renderPet({
203
+ lang: 'en',
204
+ snapshot: {
205
+ ...snapshot,
206
+ affinity: { ...snapshot.affinity, rank: '小煤球', rankEn: 'Little Coal Ball' },
207
+ },
208
+ })
209
+ fireEvent.pointerOver(screen.getByRole('button', { name: '鲸鱼娘' }))
210
+ expect(screen.getByText('Affinity Little Coal Ball')).toBeTruthy()
211
+ } finally {
212
+ document.documentElement.lang = 'zh'
213
+ }
214
+ })
215
+
216
+ it('uses the default declared rank name outside English', () => {
217
+ renderPet({
218
+ lang: 'zh',
219
+ snapshot: {
220
+ ...snapshot,
221
+ affinity: { ...snapshot.affinity, rank: '小煤球', rankEn: 'Little Coal Ball' },
222
+ },
223
+ })
224
+ fireEvent.pointerOver(screen.getByRole('button', { name: '鲸鱼娘' }))
225
+ expect(screen.getByText('亲密度 小煤球')).toBeTruthy()
226
+ })
227
+
228
+ it('feeds the effective rank name into a custom panel stat format', () => {
229
+ renderPet({
230
+ lang: 'en',
231
+ definition: { ...petDefinition(), panel: { stats: { rank: 'Bond: {rank}' } } },
232
+ snapshot: {
233
+ ...snapshot,
234
+ affinity: { ...snapshot.affinity, rank: '小煤球', rankEn: 'Little Coal Ball' },
235
+ },
236
+ })
237
+ fireEvent.pointerOver(screen.getByRole('button', { name: '鲸鱼娘' }))
238
+ expect(screen.getByText('Bond: Little Coal Ball')).toBeTruthy()
239
+ })
198
240
  })
199
241
 
200
242
  describe('PetSprite rename input', () => {
@@ -103,6 +103,11 @@ export interface PetSpriteProps {
103
103
  portalTarget?: Element
104
104
  /** Locale translate seat (namespace-bound). */
105
105
  t: TranslateNS<typeof NS>
106
+ /**
107
+ * Active UI locale id, used to pick a pet-declared English rank name
108
+ * (`rankEn`). Defaults to the document language for direct mounts/tests.
109
+ */
110
+ lang?: string
106
111
  }
107
112
 
108
113
  /** Clamp a drag offset inside the viewport with a margin. */
@@ -304,6 +309,21 @@ export function PetSprite(props: PetSpriteProps): ReactPortal {
304
309
  const panel = definition.panel
305
310
  const panelLabel = (slot: 'feed' | 'rename' | 'hide' | 'confirm', i18n: string): string =>
306
311
  panel?.labels?.[slot] ?? i18n
312
+ // The active rank name is display-only: a pet-declared ladder may carry an
313
+ // English variant, while built-in names still resolve through the i18n
314
+ // dictionary. `lang` is handed down by the mount; the document language is
315
+ // the direct-mount/test fallback.
316
+ const englishUi = (props.lang ?? (typeof document === 'undefined' ? 'zh' : document.documentElement.lang))
317
+ .toLowerCase()
318
+ .startsWith('en')
319
+ const rankNameOf = (): string => {
320
+ const rawRank = snapshot?.affinity.rank ?? '?'
321
+ const rankEn = snapshot?.affinity.rankEn
322
+ if (englishUi && rankEn !== undefined) return rankEn
323
+ const rankKey = `pet.rank.name.${rawRank}`
324
+ const localized = props.t(rankKey as never)
325
+ return localized !== rankKey ? localized : rawRank
326
+ }
307
327
  const panelStat = (
308
328
  slot: 'rank' | 'treats' | 'points',
309
329
  i18nKey: 'pet.rank' | 'pet.treats' | 'pet.points',
@@ -314,8 +334,10 @@ export function PetSprite(props: PetSpriteProps): ReactPortal {
314
334
  // The host whitelists {rank}/{n}/{points} in every stat slot, so a pack
315
335
  // format may reference any of them; substitute all three live values
316
336
  // (the slot's own value plus the siblings) instead of only the slot's.
337
+ // {rank} carries the effective name, so a pet ladder's English variant
338
+ // also reaches a custom stat format.
317
339
  const all: Record<string, string | number> = {
318
- rank: snapshot?.affinity.rank ?? '?',
340
+ rank: values.rank !== undefined ? values.rank : rankNameOf(),
319
341
  n: snapshot?.treats.stocked ?? 0,
320
342
  points: snapshot?.affinity.points ?? 0,
321
343
  }
@@ -967,13 +989,7 @@ export function PetSprite(props: PetSpriteProps): ReactPortal {
967
989
  <div className={styles.rankRow}>
968
990
  <span className={styles.nameCell}>{displayName}</span>
969
991
  <span className={styles.statRank}>
970
- {(() => {
971
- const rawRank = snapshot?.affinity.rank ?? '?'
972
- const rankKey = `pet.rank.name.${rawRank}`
973
- const localized = props.t(rankKey as any)
974
- const rankName = localized !== rankKey ? localized : rawRank
975
- return panelStat('rank', 'pet.rank', { rank: rankName })
976
- })()}
992
+ {panelStat('rank', 'pet.rank', { rank: rankNameOf() })}
977
993
  </span>
978
994
  </div>
979
995
  <div className={styles.rankRow}>
@@ -180,6 +180,10 @@ function fakeContext(options: FakeContextOptions = {}): FakeClientLifecycle {
180
180
  localeSeats.push(namespace)
181
181
  return (key: string) => 'seat:' + key
182
182
  },
183
+ // The mount reads the active locale for a pet-declared English rank
184
+ // name and re-renders on a switch; this stub pins the zh default.
185
+ getLocale: () => ({ active: 'zh', locales: [], revision: 0 }),
186
+ subscribe: () => () => {},
183
187
  },
184
188
  // The family binder is optional (dsh-web-settings may be absent); both
185
189
  // answers are the shared per-entry form of this plugin's own profile entry.
@@ -662,7 +662,20 @@ export function apply(ctx: ClientContext): void {
662
662
  // the 'pet' namespace instead follows the active language, the English
663
663
  // fallback, and every language pack that registers a dictionary for it
664
664
  // (the settings section label already resolves through the same seat).
665
- petRoot.render(createElement(PetDockEntry, { ...injected(), t: ctx.locale.bind(NS), portalTarget: container }))
665
+ const renderPet = (): void => {
666
+ petRoot.render(createElement(PetDockEntry, {
667
+ ...injected(),
668
+ t: ctx.locale.bind(NS),
669
+ // The active locale rides the same mount as the translate seat so a
670
+ // pet-declared English rank name follows the UI language.
671
+ lang: ctx.locale.getLocale().active,
672
+ portalTarget: container,
673
+ }))
674
+ }
675
+ renderPet()
676
+ // Re-render on a language switch instead of waiting for the next poll
677
+ // tick: the declared rank ladder's nameEn applies immediately.
678
+ const unsubscribeLocale = ctx.locale.subscribe(renderPet)
666
679
 
667
680
  let uiGone = false
668
681
  disposeUi = () => {
@@ -670,6 +683,7 @@ export function apply(ctx: ClientContext): void {
670
683
  uiGone = true
671
684
  clearUiTeardown?.()
672
685
  clearUiTeardown = undefined
686
+ unsubscribeLocale()
673
687
  petRoot.unmount()
674
688
  container.remove()
675
689
  disposePoll()
package/src/index.ts CHANGED
@@ -48,6 +48,8 @@ export {
48
48
  } from './affinity.ts'
49
49
  export type {
50
50
  AffinityConfig,
51
+ AffinityRank,
52
+ AffinityRankName,
51
53
  AffinityState,
52
54
  InteractionOutcome,
53
55
  PetInteraction,
@@ -43,6 +43,25 @@ describe('PetLedger', () => {
43
43
  expect(ledger.takeDirty()).toBe(false)
44
44
  })
45
45
 
46
+ it('renames ranks from a declared ladder without touching points', () => {
47
+ const ledger = new PetLedger(emptyPersist(), {
48
+ rankLadder: [
49
+ { min: 0, name: '小煤球', nameEn: 'Little Coal Ball' },
50
+ { min: 25, name: '火星伙伴' },
51
+ ],
52
+ })
53
+ expect(ledger.affinityView(1_000_000).rank).toBe('小煤球')
54
+ expect(ledger.affinityView(1_000_000).rankEn).toBe('Little Coal Ball')
55
+ expect(ledger.snapshot.affinity.points).toBe(0)
56
+
57
+ // Re-seating on a pet switch swaps the ladder without a ledger write.
58
+ ledger.setRankLadder([{ min: 0, name: '新名字' }])
59
+ expect(ledger.affinityView(1_000_000).rank).toBe('新名字')
60
+ expect(ledger.affinityView(1_000_000).rankEn).toBeUndefined()
61
+ expect(ledger.takeDirty()).toBe(false)
62
+ expect(ledger.snapshot.affinity.points).toBe(0)
63
+ })
64
+
46
65
  it('grants and spends gameplay treats through the shared stock, capped', () => {
47
66
  const ledger = new PetLedger(emptyPersist())
48
67
  expect(ledger.grantTreats(3)).toBe(true)
package/src/ledger.ts CHANGED
@@ -13,6 +13,7 @@ import {
13
13
  applyTurnReward,
14
14
  defaultAffinityConfig,
15
15
  type AffinityConfig,
16
+ type AffinityRankName,
16
17
  type PetAffinityView,
17
18
  type PetInteraction,
18
19
  } from './affinity.ts'
@@ -34,6 +35,8 @@ export interface LedgerConfig {
34
35
  remarks?: PetRemarks
35
36
  /** Voice-pack fallback remark pools (global or pet voice pack). */
36
37
  voiceRemarks?: PetRemarks
38
+ /** Display-only rank ladder for the selected pet (voice.json panel.ranks). */
39
+ rankLadder?: readonly AffinityRankName[]
37
40
  }
38
41
 
39
42
  /** Result of one ledger interaction (the shape the pet RPC returns). */
@@ -56,6 +59,8 @@ export class PetLedger {
56
59
  private readonly treatConfig: TreatConfig
57
60
  /** Round-robin reaction picker; rebuilt when the selected pet changes. */
58
61
  private picker: RemarkPicker
62
+ /** Declared rank ladder; undefined keeps the built-in whale ladder. */
63
+ private rankLadder: readonly AffinityRankName[] | undefined
59
64
  private current: PetPersist
60
65
  /** Completed turns already rewarded, per session (turn numbers are per-session). */
61
66
  private rewardedTurns = new Map<string, number>()
@@ -66,6 +71,7 @@ export class PetLedger {
66
71
  this.affinityConfig = { ...defaultAffinityConfig, ...(config.affinity ?? {}) }
67
72
  this.treatConfig = { ...defaultTreatConfig, ...(config.treats ?? {}) }
68
73
  this.picker = new RemarkPicker(config.remarks, config.voiceRemarks)
74
+ this.rankLadder = config.rankLadder
69
75
  this.current = persist
70
76
  }
71
77
 
@@ -156,6 +162,14 @@ export class PetLedger {
156
162
  this.picker = new RemarkPicker(remarks, voiceRemarks)
157
163
  }
158
164
 
165
+ /**
166
+ * Swap the display-only rank ladder to the selected pet's declared one
167
+ * (called on pet selection). Undefined restores the built-in ladder.
168
+ */
169
+ setRankLadder(ladder?: readonly AffinityRankName[]): void {
170
+ this.rankLadder = ladder
171
+ }
172
+
159
173
  /**
160
174
  * Settle the treat economy (work + time output since the last settlement).
161
175
  * A zero-gain first settlement still starts the time clock (anchor write),
@@ -279,6 +293,6 @@ export class PetLedger {
279
293
 
280
294
  /** Current affinity view for the RPC snapshot. */
281
295
  affinityView(nowMs: number): PetAffinityView {
282
- return affinityViewOf(this.current.affinity, nowMs, this.affinityConfig)
296
+ return affinityViewOf(this.current.affinity, nowMs, this.affinityConfig, this.rankLadder)
283
297
  }
284
298
  }
@@ -37,9 +37,32 @@ interface LookupCtx {
37
37
  */
38
38
  export function isPairedOrLoopbackAllowed(ctx: LookupCtx, request: IncomingMessage): boolean {
39
39
  if (isLoopbackRequest(request)) return true
40
- const fromGet = typeof ctx.get === 'function' ? ctx.get('remoteWebUiPairing', false) : undefined
41
- const pairing = (isPairingAccess(fromGet) ? fromGet : ctx.remoteWebUiPairing)
42
- return pairing?.isPairedDevice(request) === true
40
+ return lookupPairing(ctx)?.isPairedDevice(request) === true
41
+ }
42
+
43
+ /**
44
+ * The pairing service, or undefined when this composition does not expose it.
45
+ *
46
+ * Two lookups exist because the fence is shared with test harnesses that hand
47
+ * over a bare object: a real cordis context resolves services through `get`, a
48
+ * harness may carry the property directly. `get(name, false)` is the
49
+ * non-strict form, so an unloaded service answers undefined rather than
50
+ * throwing. Reading an un-injected service as a PROPERTY throws instead
51
+ * (`cannot get property "remoteWebUiPairing" without inject`); a trust fence
52
+ * must answer "not paired" in that case, never leak the error into the route
53
+ * handler, where the host web server turns it into an empty-body 400 (#1942).
54
+ */
55
+ function lookupPairing(ctx: LookupCtx): PairingAccess | undefined {
56
+ if (typeof ctx.get === 'function') {
57
+ const viaGet = ctx.get('remoteWebUiPairing', false)
58
+ return isPairingAccess(viaGet) ? viaGet : undefined
59
+ }
60
+ try {
61
+ const viaProperty = ctx.remoteWebUiPairing
62
+ return isPairingAccess(viaProperty) ? viaProperty : undefined
63
+ } catch {
64
+ return undefined
65
+ }
43
66
  }
44
67
 
45
68
  function isPairingAccess(value: unknown): value is PairingAccess {
@@ -73,6 +73,39 @@ function serviceWithPetVoicePack(id: string, remarks: Record<string, string[]>):
73
73
  return new PetService(fakeRootContext(), { registry, persistDir: tempDir() })
74
74
  }
75
75
 
76
+ /**
77
+ * A service whose global voice pack and one pet directory each declare a
78
+ * display-only rank ladder, so the merge precedence is observable end to end.
79
+ */
80
+ function serviceWithRankLadders(): PetService {
81
+ const petsDir = tempDir()
82
+ writeFileSync(join(petsDir, '.voice.json'), JSON.stringify({
83
+ voicePackVersion: 1,
84
+ panel: { ranks: [{ min: 0, name: '通用小鲸' }, { min: 25, name: '通用伙伴' }] },
85
+ }), 'utf8')
86
+ const petDir = join(petsDir, 'coalball')
87
+ mkdirSync(petDir, { recursive: true })
88
+ writeFileSync(join(petDir, 'pet.json'), JSON.stringify({
89
+ petManifestVersion: 2,
90
+ id: 'coalball',
91
+ displayName: '黑煤球',
92
+ license: 'CC0-1.0',
93
+ renderer: 'sprite2d',
94
+ sprite2d: { spritesheetPath: 'spritesheet.webp' },
95
+ }), 'utf8')
96
+ writeFileSync(join(petDir, 'spritesheet.webp'), 'webp', 'utf8')
97
+ writeFileSync(join(petDir, 'voice.json'), JSON.stringify({
98
+ voicePackVersion: 1,
99
+ panel: { ranks: [{ min: 0, name: '小煤球', nameEn: 'Little Coal Ball' }] },
100
+ }), 'utf8')
101
+ const registry = loadPetRegistry({
102
+ packageRoot: petPackageRoot(import.meta.url),
103
+ petsDir: '',
104
+ dshPetsDir: petsDir,
105
+ })
106
+ return new PetService(fakeRootContext(), { registry, persistDir: tempDir() })
107
+ }
108
+
76
109
  /** The display fields the settings surface always commits. */
77
110
  function section(petId: string): PetSettingsSection {
78
111
  return { petId, visible: true, size: 160, right: 24, bottom: 20 }
@@ -111,6 +144,34 @@ describe('PetService remark layers', () => {
111
144
  expect((await service.interact('feed')).reaction).toBe(voice.noTreats[0])
112
145
  })
113
146
 
147
+ it('uses the declared rank ladder and keeps it across switches and settings applies', async () => {
148
+ const service = serviceWithRankLadders()
149
+ const whale = service.selectedPetId()
150
+ expect(whale).not.toBe('coalball')
151
+
152
+ // A pet with no ladder of its own inherits the global one.
153
+ const whaleView = await service.state()
154
+ expect(whaleView.affinity.rank).toBe('通用小鲸')
155
+ expect(whaleView.affinity.rankEn).toBeUndefined()
156
+
157
+ // The pet's own ladder replaces the global ladder whole.
158
+ expect(await service.setPetId('coalball')).toEqual({ ok: true, petId: 'coalball' })
159
+ const petView = await service.state()
160
+ expect(petView.affinity.rank).toBe('小煤球')
161
+ expect(petView.affinity.rankEn).toBe('Little Coal Ball')
162
+
163
+ // The settings surface re-seats the pet on every change; the ladder rides
164
+ // the same resolver as the remarks, so it must survive that apply.
165
+ service.applySettingsSection(section('coalball'))
166
+ const applied = await service.state()
167
+ expect(applied.affinity.rank).toBe('小煤球')
168
+ expect(applied.affinity.rankEn).toBe('Little Coal Ball')
169
+
170
+ // Switching back restores the global ladder.
171
+ await service.setPetId(whale)
172
+ expect((await service.state()).affinity.rank).toBe('通用小鲸')
173
+ })
174
+
114
175
  it('user keeps a pet-directory voice pack remarks after the settings surface applies a section', async () => {
115
176
  const voice = { pet: ['呼……好多了'], noTreats: ['现在不困啦~'] }
116
177
  const service = serviceWithPetVoicePack('mumbler', voice)
package/src/service.ts CHANGED
@@ -15,7 +15,7 @@
15
15
  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
- import type { AffinityConfig, PetAffinityView, PetInteraction } from './affinity.ts'
18
+ import type { AffinityConfig, AffinityRankName, PetAffinityView, PetInteraction } from './affinity.ts'
19
19
  import { announcementFresh, MAX_ANNOUNCEMENTS, parseAnnouncement, type PetAnnouncement } from './announce.ts'
20
20
  import type { TreatConfig } from './treats.ts'
21
21
  import {
@@ -407,7 +407,7 @@ export class PetService extends Service {
407
407
  const ledgerConfig: LedgerConfig = {
408
408
  affinity: config.affinity,
409
409
  treats: config.treats,
410
- ...this.remarkLayers(selected),
410
+ ...this.voiceLayers(selected),
411
411
  }
412
412
  this.ledger = new PetLedger(persist, ledgerConfig)
413
413
  this.stateConfig = { ...defaultPetStateConfig, ...(config.state ?? {}) }
@@ -442,27 +442,36 @@ export class PetService extends Service {
442
442
  }
443
443
 
444
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.
445
+ * The voice layers one pet contributes to the ledger: its manifest remark
446
+ * pools first, then the voice packs (a pet directory's voice.json over the
447
+ * global `$DSH_HOME/pets/.voice.json`). The voice pack's `panel.ranks`
448
+ * ladder rides the same merge, so a ladder declared by either layer applies
449
+ * with the documented precedence. Every path that seats these layers
450
+ * resolves them here, so no call site can apply the manifest pools and
451
+ * silently drop the voice layer: doing that reverted a pet whose lines a
452
+ * voice pack had translated back to the built-in pools the moment the
453
+ * settings surface applied.
454
+ * @param entry - the pet whose layers apply.
455
+ * @returns the layers `PetLedger` takes.
454
456
  */
455
- private remarkLayers(entry: PetEntry): { remarks?: PetRemarks; voiceRemarks?: PetRemarks } {
457
+ private voiceLayers(entry: PetEntry): {
458
+ remarks?: PetRemarks
459
+ voiceRemarks?: PetRemarks
460
+ rankLadder?: readonly AffinityRankName[]
461
+ } {
462
+ const voice = mergeVoicePacks(this.registry.globalVoice, entry.voice)
456
463
  return {
457
464
  remarks: entry.remarks,
458
- voiceRemarks: mergeVoicePacks(this.registry.globalVoice, entry.voice)?.remarks,
465
+ voiceRemarks: voice?.remarks,
466
+ rankLadder: voice?.panel?.ranks,
459
467
  }
460
468
  }
461
469
 
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)
470
+ /** Re-seat the ledger's remark pools and rank ladder from one pet's layers. */
471
+ private applyVoiceLayers(entry: PetEntry): void {
472
+ const layers = this.voiceLayers(entry)
465
473
  this.ledger.setRemarks(layers.remarks, layers.voiceRemarks)
474
+ this.ledger.setRankLadder(layers.rankLadder)
466
475
  }
467
476
 
468
477
  /** RPC: current pet state snapshot. */
@@ -608,7 +617,7 @@ export class PetService extends Service {
608
617
  const entry = this.registry.byId(petId)
609
618
  if (entry === undefined) return { ok: false, error: 'unknown-pet' }
610
619
  this.ledger.setPetId(entry.id)
611
- this.applyRemarks(entry)
620
+ this.applyVoiceLayers(entry)
612
621
  this.flush()
613
622
  this.syncSettingsFromPet()
614
623
  return { ok: true, petId: entry.id }
@@ -997,7 +1006,7 @@ export class PetService extends Service {
997
1006
  const selected = typeof section.petId === 'string' ? this.registry.byId(section.petId) : undefined
998
1007
  if (selected !== undefined) {
999
1008
  this.ledger.setPetId(selected.id)
1000
- this.applyRemarks(selected)
1009
+ this.applyVoiceLayers(selected)
1001
1010
  } else if (section.petId !== undefined) {
1002
1011
  // The stored selection names a pet the registry no longer has: keep the
1003
1012
  // current selection and repair the settings document.