@linxin666/dsh-pet 0.4.14 → 0.4.15

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.
package/lib/client.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","names":["useRef","styles","useState","createPortal","useRef","useState","useRef","useState","useRef","isValidElement","cloneElement","useSyncExternalStore","useState","useRef","styles","useSyncExternalStore","useRef","styles","useState","useRef","css","useRef","Children","css","createContext","useState","useRef","css","useContext","useCallback","sectionCss","sectionCss","createRoot","createElement"],"sources":["../src/client/pet-store.ts","../src/client/work-tick-gate.ts","../node_modules/.pnpm/clsx@2.1.1/node_modules/clsx/dist/clsx.mjs","../src/persist.ts","../src/announce.ts","../src/state.ts","../src/client/spritesheet.ts","../src/client/sequences.ts","../src/client/PetSprite.tsx","../src/client/drag-stream.ts","../src/client/renderers/registry.ts","../src/client/phase-stream.ts","../src/client/renderers/live2d/Live2dVisualMount.tsx","../src/client/renderers/Frames2dVisualMount.tsx","../src/client/renderers/PetRendererSwitch.tsx","../src/gameplay.ts","../src/client/gameplay-hud.tsx","../src/client/PetDockEntry.tsx","../src/contracts/renderer.ts","../src/client/renderers/live2d/runtime.ts","../src/client/renderers/live2d.ts","../src/client/renderers/frames2d.ts","../src/client/ui-teardown.ts","../src/client/RangeBubble.tsx","../src/client/SegmentGroup.tsx","../src/client/PluginSettingsCard.tsx","../src/client/PetPreview.tsx","../src/client/settings-form.ts","../src/client/PetSettingsCard.tsx","../src/client/locales.ts","../src/client/web-extension-page.ts","../src/client/settings-registration.ts","../src/client/main-session.ts","../src/client/telemetry.ts","../src/client/index.ts"],"sourcesContent":["/**\n * Browser-side pet store: the pet state snapshot plus transient UI feedback\n * (reaction bubbles), written only through the store's audit actions. The\n * RPC polling and interactions live in the plugin apply body; components\n * only ever read snapshots.\n * @module @linxin666/dsh-pet/client/pet-store\n */\n\nimport { defineStore } from '@deepseek-ai/dsh-client-store'\nimport type { EngineStoreHandle, EngineStoreInstance } from '@deepseek-ai/dsh-client-store'\nimport type { PetGameplayStateView, PetStateView } from '../service.ts'\nimport type { PetInteraction } from '../affinity.ts'\nimport type { PetDefinition } from '../registry.ts'\n\n/** One transient reaction bubble on the pet. */\nexport interface PetFeedback {\n /** Bubble copy. */\n text: string\n /** Interaction kind driving the reaction animation. */\n kind: PetInteraction | 'none'\n /** Epoch ms when the bubble appeared (for expiry). */\n at: number\n}\n\n/** Pet UI state as consumers see it. */\nexport interface PetUiState {\n /** Latest host snapshot; null before the first successful fetch. */\n snapshot: PetStateView | null\n /** The registry list the host serves (atlas URLs + geometry + tracks). */\n pets: PetDefinition[]\n /** Fetch lifecycle. */\n state: 'loading' | 'ready' | 'error'\n /** Transport error message (for the debug surface), when any. */\n error: string | null\n /** Active reaction bubble, if any. */\n feedback: PetFeedback | null\n}\n\n/** Store write set. */\nexport type PetUiActions = {\n /** Replace the host snapshot (poll result). */\n setSnapshot: (draft: PetUiState, snapshot: PetStateView) => void\n /** Replace the registry list. */\n setPets: (draft: PetUiState, pets: PetDefinition[]) => void\n /** Mark the fetch lifecycle. */\n setState: (draft: PetUiState, state: PetUiState['state'], error: string | null) => void\n /** Show a reaction bubble. */\n setFeedback: (draft: PetUiState, feedback: PetFeedback | null) => void\n /**\n * Patch the gameplay slice of the snapshot (verb write-back), so the HUD\n * reflects a touch/mode/buy result immediately instead of waiting one\n * poll tick (2 s).\n */\n setGameplayView: (draft: PetUiState, view: PetGameplayStateView) => void\n}\n\n/** Create the pet store handle (apply world only; never module-level). */\nexport function createPetStore(): EngineStoreHandle<PetUiState, PetUiActions> {\n return defineStore({\n init: (): PetUiState => ({\n snapshot: null,\n pets: [],\n state: 'loading',\n error: null,\n feedback: null,\n }),\n actions: {\n setSnapshot: (draft, snapshot) => {\n // The 2 s poll republishes the full snapshot even while the pet is\n // idle. Skipping an unchanged payload keeps immer's produce at zero\n // modifications, so zustand never notifies and the whole sprite tree\n // skips the re-render. Equality is JSON-based and skip-only: both\n // sides come from the same host serializer, and any mismatch falls\n // through to the normal publish — the failure mode is one extra\n // render, never a stale pet.\n if (draft.state === 'ready' && draft.error === null && sameSnapshot(draft.snapshot, snapshot)) return\n draft.snapshot = snapshot\n draft.state = 'ready'\n draft.error = null\n },\n setPets: (draft, pets) => {\n draft.pets = pets\n },\n setState: (draft, state, error) => {\n draft.state = state\n draft.error = error\n },\n setFeedback: (draft, feedback) => {\n draft.feedback = feedback\n },\n setGameplayView: (draft, view) => {\n if (draft.snapshot !== null) draft.snapshot = { ...draft.snapshot, gameplay: view }\n },\n },\n })\n}\n\nexport type { PetInteraction }\n\n/**\n * Content equality for consecutive poll snapshots. JSON compare, not field\n * enumeration: an exact string match is the only way to skip the publish, so\n * a missed field can never freeze the UI — it can only cost the render the\n * optimization exists to save.\n */\nfunction sameSnapshot(previous: PetStateView | null, next: PetStateView): boolean {\n return previous !== null && JSON.stringify(previous) === JSON.stringify(next)\n}\n\n/**\n * A live pet store instance (one per host, owned by the plugin apply body —\n * the pet itself is host-global, so its UI state must not ride the slot\n * system's per-session store scoping).\n */\nexport type PetStoreInstance = EngineStoreInstance<PetUiState, PetUiActions>\n\n","/**\n * Page-wide work-tick gate for the pet's work mode. Hot reloads can leave\n * several GameplayHud instances alive, each running its own work interval;\n * without a shared gate every interval would call workTick and each stale call\n * re-rolls, re-grants treats and re-plays the success/fail track, so the\n * outcome appears to play several times per window. The gate accepts the first\n * adjudication of a window and silently suppresses the duplicates that follow.\n *\n * The window is the active pet's own `gameplay.work.tickMs`, not a constant: a\n * pet configured with a shorter cadence must actually adjudicate that often,\n * while a fixed window would downgrade it without saying so (#1494).\n * @module @linxin666/dsh-pet/client/work-tick-gate\n */\n\n/** Window used when the active pet declares no work cadence. */\nexport const DEFAULT_WORK_TICK_MS = 10_000\n\n/** Manifest bounds for `gameplay.work.tickMs` (src/gameplay.ts). */\nconst MIN_WORK_TICK_MS = 1_000\nconst MAX_WORK_TICK_MS = 60_000\n\n/**\n * The gate window for one pet: its configured cadence, clamped to the manifest's\n * own bounds so a malformed registry entry cannot disable or flood the gate.\n * @param tickMs - the active definition's `gameplay.work.tickMs`, when it has one.\n * @returns the window in milliseconds.\n */\nexport function workTickWindowMs(tickMs: number | undefined): number {\n if (typeof tickMs !== 'number' || !Number.isFinite(tickMs)) return DEFAULT_WORK_TICK_MS\n return Math.min(MAX_WORK_TICK_MS, Math.max(MIN_WORK_TICK_MS, tickMs))\n}\n\n/** The shared work-tick gate. */\nexport interface WorkTickGate {\n /**\n * Admit one adjudication for the current window.\n * @param tickMs - the active pet's configured work cadence.\n * @returns true when this call may adjudicate, false for a duplicate.\n */\n allow: (tickMs: number | undefined) => boolean\n /** Forget the last adjudication (used when work mode is entered). */\n reset: () => void\n}\n\n/**\n * Create a gate.\n * @param now - the clock, injectable so tests control the window.\n * @returns the gate over that clock.\n */\nexport function createWorkTickGate(now: () => number = Date.now): WorkTickGate {\n let lastAdjudicatedAt = 0\n return {\n allow: (tickMs) => {\n const at = now()\n if (at - lastAdjudicatedAt < workTickWindowMs(tickMs)) return false\n lastAdjudicatedAt = at\n return true\n },\n reset: () => {\n lastAdjudicatedAt = 0\n },\n }\n}\n","function r(e){var t,f,n=\"\";if(\"string\"==typeof e||\"number\"==typeof e)n+=e;else if(\"object\"==typeof e)if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(f=r(e[t]))&&(n&&(n+=\" \"),n+=f)}else for(f in e)e[f]&&(n&&(n+=\" \"),n+=f);return n}export function clsx(){for(var e,t,f=0,n=\"\",o=arguments.length;f<o;f++)(e=arguments[f])&&(t=r(e))&&(n&&(n+=\" \"),n+=t);return n}export default clsx;","/**\n * Pet persistence — tiny JSON store for affinity + display config, written\n * under $DSH_HOME (defaults to ~/.dsh) as `pet.json`. Deliberately minimal:\n * one file, atomic rename write, tolerant read (corrupt file → defaults).\n * @module @linxin666/dsh-pet/persist\n */\n\nimport { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { dshHome } from './dsh-home.ts'\nimport { AFFINITY_MAX, emptyAffinity, type AffinityState } from './affinity.ts'\nimport { defaultTreatConfig, emptyTreatLedger, type TreatLedger } from './treats.ts'\nimport { DEFAULT_PET_ID, DEFAULT_PET_NAME } from './defaults.ts'\nimport type { PetGameplayState } from './gameplay.ts'\n\nexport { DEFAULT_PET_ID, DEFAULT_PET_NAME } from './defaults.ts'\n\n/** Display configuration the user can tweak. */\nexport interface PetDisplayConfig {\n /** Master switch. */\n visible: boolean\n /** Scale of the rendered pet in px (sprite cell height). */\n size: number\n /** Horizontal inset from the viewport right edge, px. */\n right: number\n /** Vertical inset from the viewport bottom edge, px. */\n bottom: number\n /**\n * Multiplier on the bubble typography's automatic size following (#1549).\n * The rendered bubble scale is `size / 160 * bubbleScale`, bounded by\n * {@link BUBBLE_FONT_MIN_PX}..{@link BUBBLE_FONT_MAX_PX}, so 1 keeps the\n * 12px baseline the stylesheet was drawn for at the default 160px pet.\n */\n bubbleScale: number\n}\n\nexport const defaultDisplayConfig: PetDisplayConfig = {\n visible: true,\n size: 160,\n right: 24,\n bottom: 120,\n bubbleScale: 1,\n}\n\n/** Display value bounds (shared by load-time validation and setConfig). */\nexport const DISPLAY_SIZE_MIN = 32\nexport const DISPLAY_SIZE_MAX = 1024\nexport const DISPLAY_INSET_MAX = 10_000\n\n/** Bubble typography bounds (issue #1549). */\nexport const BUBBLE_SCALE_MIN = 0.5\nexport const BUBBLE_SCALE_MAX = 2\n/** Pixel size the bubble stylesheet was drawn for, at the default pet size. */\nexport const BUBBLE_BASE_FONT_PX = 12\n/** Pet size that baseline matches; other sizes scale the bubble with them. */\nexport const BUBBLE_BASE_SIZE_PX = 160\n/** Readability floor and layout ceiling of the scaled bubble text. */\nexport const BUBBLE_FONT_MIN_PX = 10\nexport const BUBBLE_FONT_MAX_PX = 24\n\n/**\n * Bubble typography scale for one display config (issue #1549): the bubble\n * follows the pet's own size so a shrunk pet does not carry a full-size\n * bubble, and the user's multiplier rides on top. The result is a CSS ratio\n * against {@link BUBBLE_BASE_FONT_PX}, bounded so the text never drops below\n * the readability floor or outgrows the pet. `bubbleScale` is optional at\n * runtime: a host that predates the field (a rolling update, or any snapshot\n * that omits it) falls back to the baseline, because a NaN ratio written into\n * `--pet-bubble-scale` collapses every bubble's text to zero.\n * @param display - display config; `bubbleScale` may be absent on older hosts.\n * @returns the ratio written to `--pet-bubble-scale` (always finite).\n */\nexport function bubbleScaleFor(display: Pick<PetDisplayConfig, 'size'> & { bubbleScale?: number }): number {\n // Guard the arithmetic, not just the clamp: Math.min/max propagate NaN, so a\n // missing or non-finite field would otherwise reach the stylesheet.\n const size = Number.isFinite(display.size) ? display.size : BUBBLE_BASE_SIZE_PX\n const multiplier = typeof display.bubbleScale === 'number' && Number.isFinite(display.bubbleScale)\n ? display.bubbleScale\n : 1\n const scaled = (size / BUBBLE_BASE_SIZE_PX) * multiplier\n const min = BUBBLE_FONT_MIN_PX / BUBBLE_BASE_FONT_PX\n const max = BUBBLE_FONT_MAX_PX / BUBBLE_BASE_FONT_PX\n return Math.round(Math.min(max, Math.max(min, scaled)) * 100) / 100\n}\n\n/** Everything persisted for the pet. */\nexport interface PetPersist {\n /** Selected pet id (a registry entry; clamped at service startup). */\n petId: string\n /**\n * Per-pet display names keyed by pet id. A pet without an entry falls back\n * to its manifest displayName, so only user renames are stored here.\n */\n names: Record<string, string>\n /**\n * Per-pet selected frames2d skin id (keyed by pet id). Skin ids are manifest\n * data, so a stale entry (skin renamed or removed, pet swapped) is ignored\n * when the state view is built instead of pinning an unresolvable track.\n */\n skins: Record<string, string>\n affinity: AffinityState\n /** Treat (小鱼干) stock ledger. */\n treats: TreatLedger\n display: PetDisplayConfig\n /** Per-pet gameplay state (stats/currencies/mode), keyed by pet id. */\n gameplay: Record<string, PetGameplayState>\n}\n\n/** Name constraints. */\nexport const PET_NAME_MAX_LENGTH = 20\n\nexport function emptyPersist(): PetPersist {\n return {\n petId: DEFAULT_PET_ID,\n names: {},\n skins: {},\n affinity: emptyAffinity(),\n treats: emptyTreatLedger(),\n display: { ...defaultDisplayConfig },\n gameplay: {},\n }\n}\n\n/**\n * Resolve the persistence directory ($DSH_HOME or ~/.dsh). Delegates to the\n * shared {@link dshHome} resolution so the plugin family keeps one DSH_HOME\n * definition (env override, ~ expansion, cwd-joined relative values).\n */\nexport function petHomeDir(): string {\n return dshHome()\n}\n\n/** Numeric field guard: finite numbers only, else the fallback. */\nfunction finiteNum(value: unknown, fallback: number): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : fallback\n}\n\n/** A persisted document from any schema era (legacy carried a flat `name`). */\ntype PetPersistDocument = Partial<PetPersist> & { name?: unknown }\n\n/** Sanitize the per-pet names map (string keys, non-empty trimmed values). */\nfunction loadPetNames(parsed: PetPersistDocument): Record<string, string> {\n const names: Record<string, string> = {}\n if (typeof parsed.names !== 'object' || parsed.names === null) return names\n for (const [id, value] of Object.entries(parsed.names as Record<string, unknown>)) {\n if (id === '' || typeof value !== 'string') continue\n const name = value.trim()\n if (name === '') continue\n names[id] = name.slice(0, PET_NAME_MAX_LENGTH)\n }\n return names\n}\n\n/** Sanitize the per-pet skin selection map (string keys, non-empty trimmed values). */\nfunction loadPetSkins(parsed: PetPersistDocument): Record<string, string> {\n const skins: Record<string, string> = {}\n if (typeof parsed.skins !== 'object' || parsed.skins === null) return skins\n for (const [id, value] of Object.entries(parsed.skins as Record<string, unknown>)) {\n if (id === '' || typeof value !== 'string') continue\n const skin = value.trim()\n if (skin === '') continue\n skins[id] = skin\n }\n return skins\n}\n\n/** Clamp one count/score into [0, max]. */\nfunction clamp(value: number, max: number): number {\n return Math.min(max, Math.max(0, value))\n}\n\n/** Absolute numeric ceilings applied at load (manifest clamps refine these). */\nconst GAMEPLAY_LOAD_STAT_CAP = 1_000_000\nconst GAMEPLAY_LOAD_CURRENCY_CAP = 9_999_999\n\n/** Sanitize the persisted per-pet gameplay map. */\nfunction loadGameplay(parsed: PetPersistDocument): Record<string, PetGameplayState> {\n const result: Record<string, PetGameplayState> = {}\n if (typeof parsed.gameplay !== 'object' || parsed.gameplay === null) return result\n for (const [petId, raw] of Object.entries(parsed.gameplay as Record<string, unknown>)) {\n if (petId === '' || typeof raw !== 'object' || raw === null) continue\n const record = raw as Partial<PetGameplayState>\n const stats: Record<string, number> = {}\n if (typeof record.stats === 'object' && record.stats !== null) {\n for (const [key, value] of Object.entries(record.stats)) {\n if (key === '' || typeof value !== 'number' || !Number.isFinite(value)) continue\n stats[key] = Math.min(GAMEPLAY_LOAD_STAT_CAP, Math.max(0, value))\n }\n }\n const currencies: Record<string, number> = {}\n if (typeof record.currencies === 'object' && record.currencies !== null) {\n for (const [key, value] of Object.entries(record.currencies)) {\n if (key === '' || typeof value !== 'number' || !Number.isFinite(value)) continue\n currencies[key] = Math.min(GAMEPLAY_LOAD_CURRENCY_CAP, Math.max(0, Math.floor(value)))\n }\n }\n const item: PetGameplayState = {\n stats,\n currencies,\n // Any non-empty id survives the round trip; whether it is still declared\n // is settled against the manifest when the mode is read back.\n mode: typeof record.mode === 'string' && record.mode.length > 0 && record.mode.length <= 24 ? record.mode : null,\n settledAt: clamp(finiteNum(record.settledAt, 0), Number.MAX_SAFE_INTEGER),\n }\n if (typeof record.incomeCarryMs === 'number' && Number.isFinite(record.incomeCarryMs)) {\n item.incomeCarryMs = Math.max(0, record.incomeCarryMs)\n }\n if (typeof record.restoreCarryMs === 'number' && Number.isFinite(record.restoreCarryMs)) {\n item.restoreCarryMs = Math.max(0, record.restoreCarryMs)\n }\n result[petId] = item\n }\n return result\n}\n\n/** Load persisted state; missing or corrupt files fall back to defaults. */\nexport function loadPetPersist(dir: string = petHomeDir()): PetPersist {\n try {\n const raw = readFileSync(join(dir, 'pet.json'), 'utf8')\n const parsed = JSON.parse(raw) as PetPersistDocument\n const base = emptyPersist()\n const rawAffinity = (parsed.affinity ?? {}) as Partial<AffinityState>\n const affinity: AffinityState = {\n points: clamp(finiteNum(rawAffinity.points, 0), AFFINITY_MAX),\n lastPetAt: clamp(finiteNum(rawAffinity.lastPetAt, 0), Number.MAX_SAFE_INTEGER),\n lastFeedAt: clamp(finiteNum(rawAffinity.lastFeedAt, 0), Number.MAX_SAFE_INTEGER),\n pets: clamp(finiteNum(rawAffinity.pets, 0), Number.MAX_SAFE_INTEGER),\n feeds: clamp(finiteNum(rawAffinity.feeds, 0), Number.MAX_SAFE_INTEGER),\n petRejects: clamp(finiteNum(rawAffinity.petRejects, 0), Number.MAX_SAFE_INTEGER),\n feedRejects: clamp(finiteNum(rawAffinity.feedRejects, 0), Number.MAX_SAFE_INTEGER),\n turns: clamp(finiteNum(rawAffinity.turns, 0), Number.MAX_SAFE_INTEGER),\n }\n const rawTreats = (parsed.treats ?? {}) as Partial<TreatLedger>\n const treats: TreatLedger = {\n treats: clamp(finiteNum(rawTreats.treats, 0), defaultTreatConfig.maxTreats),\n lastTreatGrantAt: clamp(finiteNum(rawTreats.lastTreatGrantAt, 0), Number.MAX_SAFE_INTEGER),\n turnsAtLastTreatGrant: clamp(finiteNum(rawTreats.turnsAtLastTreatGrant, 0), Number.MAX_SAFE_INTEGER),\n }\n const rawDisplay = (parsed.display ?? {}) as Partial<PetDisplayConfig>\n const display: PetDisplayConfig = {\n visible: typeof rawDisplay.visible === 'boolean' ? rawDisplay.visible : base.display.visible,\n // The settings schema requires whole pixels; drag positions are\n // clamped but not integral, so round at the persistence boundary.\n size: Math.round(Math.min(DISPLAY_SIZE_MAX, Math.max(DISPLAY_SIZE_MIN, finiteNum(rawDisplay.size, base.display.size)))),\n right: Math.round(clamp(finiteNum(rawDisplay.right, base.display.right), DISPLAY_INSET_MAX)),\n bottom: Math.round(clamp(finiteNum(rawDisplay.bottom, base.display.bottom), DISPLAY_INSET_MAX)),\n // Fractional on purpose: the multiplier is a ratio, not a pixel count.\n bubbleScale: Math.min(BUBBLE_SCALE_MAX, Math.max(BUBBLE_SCALE_MIN, finiteNum(rawDisplay.bubbleScale, base.display.bubbleScale))),\n }\n const petId = typeof parsed.petId === 'string' && parsed.petId.trim() !== ''\n ? parsed.petId.trim()\n : base.petId\n const names = loadPetNames(parsed)\n // Legacy migration: pre-registry installs persisted one flat `name`\n // field. Move it onto the selected pet (the legacy whale-girl unless the\n // file already names another pet) so renames survive the upgrade.\n if (typeof parsed.name === 'string' && parsed.name.trim() !== '' && names[petId] === undefined) {\n names[petId] = parsed.name.trim().slice(0, PET_NAME_MAX_LENGTH)\n }\n return {\n petId,\n names,\n skins: loadPetSkins(parsed),\n affinity,\n treats,\n display,\n gameplay: loadGameplay(parsed),\n }\n } catch {\n return emptyPersist()\n }\n}\n\n/** Atomically persist state (write temp + rename). */\nexport function savePetPersist(data: PetPersist, dir: string = petHomeDir()): void {\n mkdirSync(dir, { recursive: true })\n const target = join(dir, 'pet.json')\n const tmp = `${target}.tmp`\n writeFileSync(tmp, JSON.stringify(data, null, 2), 'utf8')\n renameSync(tmp, target)\n}\n","/**\n * The pet announcement-bubble contract: a sibling plugin\n * pushes one structured announcement through `pet.announce(...)`, the host\n * validates it into a bounded payload, and the browser half renders it as a\n * dedicated, specially styled bubble above the session bubble stack.\n *\n * One slot per publisher (issue #1812): `source` is the slot key, so two\n * announcing plugins coexist instead of displacing each other, and each keeps\n * its own TTL. The single-slot contract this replaced is kept on the wire as\n * the freshest entry, so an older browser half keeps working unchanged.\n *\n * The validation lives in this pure module so the wire contract has exactly\n * one home and stays testable without the cordis service.\n * @module @linxin666/dsh-pet/announce\n */\n\n/** One plugin-authored announcement bubble. */\nexport interface PetAnnouncement {\n /** Authoring plugin's source tag (its own package short name). */\n source: string\n /** Bubble content kind: a spend estimate, an account balance, or a plan-quota status. */\n kind: 'balance' | 'cost' | 'plan'\n /** Lead text (usually the provider display name). */\n title: string\n /** Balance or today-spend amount, formatted for display (kinds `balance` and `cost`). */\n amount?: string\n /** Plan usage percent 0-100 (kind `plan`). */\n percent?: number\n /** ISO 8601 reset instant (kind `plan`). */\n resetAt?: string\n /** Short trailing note (plan tier name, peak-period status, currency code, ...). */\n note?: string\n /** Visual tone; drives the bubble's accent color. */\n tone: 'ok' | 'warn' | 'low'\n /** Freshness window in ms; an expired announcement stops rendering. */\n ttlMs: number\n /** Epoch ms the announcement arrived. */\n at: number\n}\n\n/** Default freshness window. */\nexport const ANNOUNCE_DEFAULT_TTL_MS = 10_000\n\n/**\n * How many publishers can hold an announcement bubble at once (issue #1812).\n *\n * The contract has exactly one slot per `source` — that is the whole upgrade\n * from the single-slot design — but the pet's bubble stack is a finite column,\n * so the table is bounded rather than open. The bound is deliberately above the\n * realistic publisher count (a quota bubble, a balance bubble, a notification):\n * it exists so a misbehaving publisher that rotates `source` per bubble cannot\n * grow the pet's stack without limit.\n */\nexport const MAX_ANNOUNCEMENTS = 4\n\n/**\n * Hard TTL ceiling. A repeating announcer declares its poll cadence as\n * the TTL, so an always-on bubble stays continuous across polls; the\n * ceiling means a source that dies unmounts its bubble within at most one\n * missed refresh cycle rather than lingering forever.\n */\nexport const ANNOUNCE_MAX_TTL_MS = 7_200_000\n\n/** Hard bounds: lengths and the TTL range (1 s .. 60 s). */\nconst TITLE_MAX = 80\nconst TEXT_MAX = 120\nconst SOURCE_MAX = 64\n\nfunction boundedString(value: unknown, max: number): string | undefined {\n if (typeof value !== 'string') return undefined\n const trimmed = value.trim()\n if (trimmed === '') return undefined\n return trimmed.length <= max ? trimmed : trimmed.slice(0, max)\n}\n\n/**\n * Validate one announce payload. Unknown fields are dropped, oversized text\n * is truncated, and anything structurally wrong resolves to undefined — a\n * malformed announcement never reaches the pet's bubble surface.\n * @param input - the payload a sibling plugin passed to `pet.announce`.\n * @param now - epoch ms the announcement arrived.\n */\nexport function parseAnnouncement(input: unknown, now: number): PetAnnouncement | undefined {\n if (typeof input !== 'object' || input === null) return undefined\n const data = input as Record<string, unknown>\n const source = boundedString(data.source, SOURCE_MAX)\n const title = boundedString(data.title, TITLE_MAX)\n if (source === undefined || title === undefined) return undefined\n const kind = data.kind === 'balance' || data.kind === 'cost' || data.kind === 'plan' ? data.kind : undefined\n if (kind === undefined) return undefined\n const amount = boundedString(data.amount, TEXT_MAX)\n const resetAt = boundedString(data.resetAt, TEXT_MAX)\n const note = boundedString(data.note, TITLE_MAX)\n const percent = typeof data.percent === 'number' && Number.isFinite(data.percent)\n ? Math.max(0, Math.min(100, data.percent))\n : undefined\n if ((kind === 'balance' || kind === 'cost') && amount === undefined) return undefined\n if (kind === 'plan' && percent === undefined) return undefined\n const tone = data.tone === 'warn' || data.tone === 'low' ? data.tone : 'ok'\n const ttlMs = typeof data.ttlMs === 'number' && Number.isFinite(data.ttlMs)\n ? Math.max(1000, Math.min(ANNOUNCE_MAX_TTL_MS, data.ttlMs))\n : ANNOUNCE_DEFAULT_TTL_MS\n return {\n source,\n kind,\n title,\n ...(amount !== undefined ? { amount } : {}),\n ...(percent !== undefined ? { percent } : {}),\n ...(resetAt !== undefined ? { resetAt } : {}),\n ...(note !== undefined ? { note } : {}),\n tone,\n ttlMs,\n at: now,\n }\n}\n\n/** Whether an announcement is still fresh at `now`. */\nexport function announcementFresh(announcement: PetAnnouncement, now: number): boolean {\n return now - announcement.at < announcement.ttlMs\n}\n","/**\n * Pet state machine — pure, clock-injected. Maps official DSH session activity\n * and the legacy `activity/status` vocabulary onto the 9-state Codex pet\n * animation contract, plus turn-end celebration and no-session idle.\n *\n * The machine is deliberately dumb: it holds the last input phase, the\n * animation decision, and a one-shot \"celebration\" window after `done` so the\n * pet visibly jumps before settling back to idle. Everything here is a pure\n * function of (input, nowMs); persistence and RPC live in the service.\n * @module @linxin666/dsh-pet/state\n */\n\n/** Activity phases understood by the pet host. */\nexport type ActivityPhase = 'idle' | 'waiting' | 'thinking' | 'tool' | 'review' | 'done' | 'failed'\n\n/** The Codex-compatible 9-state animation contract (spritesheet rows). */\nexport type PetAnimation =\n | 'idle'\n | 'running-right'\n | 'running-left'\n | 'waving'\n | 'jumping'\n | 'failed'\n | 'waiting'\n | 'running'\n | 'review'\n\n/** One input snapshot consumed by the machine. */\nexport interface PetStateInput {\n /** Current activity phase of the active session. */\n phase: ActivityPhase\n /** Human-readable status line (plain text). */\n line?: string\n /** Playful phrase from the activity tracker, when any. */\n phrase?: string\n}\n\n/** Animation decision plus the copy the pet should show. */\nexport interface PetStateSnapshot {\n /** Which animation track to play. */\n animation: PetAnimation\n /** Optional status bubble copy (line or phrase), shown while active. */\n bubble?: string\n /** Wall-clock ms this animation started (client can sync loops). */\n animationStartedAt: number\n /** Raw phase, for debugging and client-side rendering decisions. */\n phase: ActivityPhase\n /** True when there is an active session (pet mounted). */\n sessionActive: boolean\n}\n\n/** Machine configuration. */\nexport interface PetStateConfig {\n /** Celebration window after `done` before settling to idle, ms (default 2400). */\n celebrateMs: number\n /** Failure display window before settling to idle, ms (default 2400). */\n failureMs: number\n}\n\nexport const defaultPetStateConfig: PetStateConfig = { celebrateMs: 2400, failureMs: 2400 }\n\n/**\n * Map one activity phase onto the animation contract.\n * - thinking → `running` and tool → `running-right` (focused work).\n * - review → `review` while answer text is streaming.\n * - waiting → `waiting` (expectant pose, needs user input).\n * - done → `jumping` (celebration), then back to `idle` after the window.\n * - failed → `failed` briefly, then back to `idle`.\n * - idle → `idle` (calm breathing loop).\n */\nexport function animationForPhase(phase: ActivityPhase): PetAnimation {\n switch (phase) {\n case 'thinking': return 'running'\n case 'tool': return 'running-right'\n case 'review': return 'review'\n case 'waiting': return 'waiting'\n case 'done': return 'jumping'\n case 'failed': return 'failed'\n case 'idle': return 'idle'\n }\n}\n\n/** The spritesheet row index for one animation track. */\nexport function rowOf(animation: PetAnimation): number {\n const rows: Record<PetAnimation, number> = {\n 'idle': 0,\n 'running-right': 1,\n 'running-left': 2,\n 'waving': 3,\n 'jumping': 4,\n 'failed': 5,\n 'waiting': 6,\n 'running': 7,\n 'review': 8,\n }\n return rows[animation]\n}\n\n/**\n * PetStateMachine — one instance per host process. Holds only the latest\n * input snapshot and terminal-state timing; no storage, no side effects.\n */\nexport class PetStateMachine {\n private phase: ActivityPhase = 'idle'\n private line: string | undefined\n private phrase: string | undefined\n private sessionActive = false\n private doneAt: number | undefined\n private failedAt: number | undefined\n private readonly config: PetStateConfig\n\n constructor(\n config: Partial<PetStateConfig> = defaultPetStateConfig,\n private readonly now: () => number = Date.now,\n ) {\n this.config = { ...defaultPetStateConfig, ...config }\n }\n\n /** Consume one projected activity update. */\n onActivityStatus(input: PetStateInput): void {\n this.phase = input.phase\n this.line = input.line\n this.phrase = input.phrase\n this.doneAt = input.phase === 'done' ? this.now() : undefined\n this.failedAt = input.phase === 'failed' ? this.now() : undefined\n }\n\n /** A session became the active one (or a fresh session started). */\n onSessionActive(): void {\n this.sessionActive = true\n }\n\n /** The active session was disposed (or none left). */\n onSessionDisposed(): void {\n this.sessionActive = false\n this.phase = 'idle'\n this.line = undefined\n this.phrase = undefined\n this.doneAt = undefined\n this.failedAt = undefined\n }\n\n /** Render the current animation decision. */\n render(): PetStateSnapshot {\n const nowMs = this.now()\n let animation = animationForPhase(this.phase)\n const doneSettled = this.phase === 'done'\n && this.doneAt !== undefined\n && nowMs - this.doneAt >= this.config.celebrateMs\n const failedSettled = this.phase === 'failed'\n && this.failedAt !== undefined\n && nowMs - this.failedAt >= this.config.failureMs\n if (doneSettled || failedSettled) animation = 'idle'\n // Settled sessions never bubble: idle (e.g. an aborted/stopped turn),\n // completed celebration expiry, and failed display expiry all fall silent.\n const settled = this.phase === 'idle' || doneSettled || failedSettled\n const bubble = settled ? undefined : this.phrase ?? this.line\n return {\n animation,\n ...(bubble === undefined ? {} : { bubble }),\n animationStartedAt: nowMs,\n phase: this.phase,\n sessionActive: this.sessionActive,\n }\n }\n}\n","/**\n * Spritesheet geometry helpers — parameterized by the pet definition the\n * host serves over '/api/pet/pets', so the browser half renders any registry\n * entry without per-pet code. The per-track tables (frames, durations, loop,\n * fallback) also come from the registry; these helpers only place frames,\n * guard track lengths, and map the fixed 9-row animation contract.\n * @module @linxin666/dsh-pet/client/spritesheet\n */\n\nimport { rowOf, type PetAnimation } from '../state.ts'\nimport type { PetCell, PetTrackDef } from '../registry.ts'\n\n/** Animation track shape the frame loop consumes. */\nexport type TrackDef = PetTrackDef\n\n/** Row index of one animation track (the fixed 9-row contract). */\nexport function rowOfTrack(animation: PetAnimation): number {\n // The table itself lives in state.ts (rowOf) — the single source of truth.\n return rowOf(animation)\n}\n\n/**\n * Integer size of one cell after `scale`, in device-independent px.\n *\n * Rounding happens here, once, so the rendered atlas grid is integral end to\n * end (issue #17): `background-size` is this size times the column/row count\n * and every frame offset is an exact multiple of it. A fractional cell size\n * leaves each frame on a sub-pixel boundary — 192px cells at `display.size`\n * 160 scale to 147.69px — and the compositor then has to resample the whole\n * scaled atlas on every frame change instead of translating an already-scaled\n * bitmap by whole pixels. The pet advances a frame every 300-700 ms, so that\n * resample was running continuously for a background surface the size of the\n * sprite. A floor of 1px keeps a legally tiny display.size from collapsing the\n * cell to zero and rendering nothing.\n */\nexport function scaledCellSize(cell: PetCell, scale: number): { width: number; height: number } {\n return {\n width: Math.max(1, Math.round(cell.width * scale)),\n height: Math.max(1, Math.round(cell.height * scale)),\n }\n}\n\n/**\n * Background-position (px) of one frame cell within the scaled atlas.\n * The background image is scaled by `scale` (element size ÷ cell size), and\n * background-position offsets are applied in SCALED coordinates — using raw\n * atlas coordinates here would drift each frame by the scale factor and\n * render torn/overlapping frames. The scaled cell is quantized by\n * {@link scaledCellSize}, so the offset of frame N is exactly N whole cells:\n * the atlas is snapped to the pixel grid and a frame change is a plain\n * translate of the scaled bitmap.\n */\nexport function framePosition(cell: PetCell, row: number, col: number, scale = 1): { x: number; y: number } {\n const scaled = scaledCellSize(cell, scale)\n return { x: -col * scaled.width, y: -row * scaled.height }\n}\n\n/**\n * Trim a track to the actual frame count of its row (the manifest's per-row\n * counts are authoritative; this is a last-line guard against a definition\n * whose row count disagrees with its track table). A row with 0 detected\n * frames degrades to the first frame so the pet never renders blank.\n */\nexport function trimTrack(track: TrackDef, frameCount: number): TrackDef {\n const n = Math.max(1, Math.min(frameCount, track.frames.length, track.durations.length))\n return {\n frames: track.frames.slice(0, n),\n durations: track.durations.slice(0, n),\n loop: track.loop,\n ...(track.fallback === undefined ? {} : { fallback: track.fallback }),\n }\n}\n","/** Pure timing helpers for manifest-defined scene animation sequences. */\n\nimport type { PetTrackDef } from '../registry.ts'\nimport type { PetAnimation } from '../state.ts'\n\nexport interface SequenceFrame {\n animation: PetAnimation\n frameIndex: number\n}\n\n/**\n * Precomputed timeline for one looping sequence: the per-item duration table\n * is built once instead of per query. The sprite frame loop asks once per\n * frame change, where the per-call map/reduce is pure waste.\n */\nexport interface SequenceTimeline {\n frameAt(elapsedMs: number): SequenceFrame\n /**\n * Milliseconds from `elapsedMs` until the frame it lands on ends. The sprite\n * loop sleeps for exactly this long instead of polling at the screen refresh\n * rate (issue #17); the floor of 1 ms keeps a zero-length frame from turning\n * into a busy timer.\n */\n remainingAt(elapsedMs: number): number\n}\n\n/** One sequence position, with the residual offset inside its own frame. */\ninterface SequencePoint {\n animation: PetAnimation\n track: PetTrackDef\n frameIndex: number\n offsetInFrame: number\n}\n\n/** Build a {@link SequenceTimeline} over one manifest sequence. */\nexport function createSequenceTimeline(\n sequence: readonly PetAnimation[],\n tracks: Record<PetAnimation, PetTrackDef>,\n): SequenceTimeline {\n const itemDurations = sequence.map(animation => tracks[animation].durations.reduce((sum, value) => sum + value, 0))\n const sequenceDuration = itemDurations.reduce((sum, value) => sum + value, 0)\n // One traversal serves both queries: frameAt needs the index it lands on and\n // remainingAt needs how far into that frame it is, so resolving them\n // separately would walk the same tables twice for one loop tick.\n const locate = (elapsedMs: number): SequencePoint => {\n let offset = sequenceDuration > 0 ? Math.max(0, elapsedMs) % sequenceDuration : 0\n let itemIndex = 0\n while (itemIndex < sequence.length - 1 && offset >= itemDurations[itemIndex]!) {\n offset -= itemDurations[itemIndex]!\n itemIndex += 1\n }\n const animation = sequence[itemIndex]!\n const track = tracks[animation]\n let frameIndex = 0\n while (frameIndex < track.frames.length - 1 && offset >= track.durations[frameIndex]!) {\n offset -= track.durations[frameIndex]!\n frameIndex += 1\n }\n return { animation, track, frameIndex, offsetInFrame: offset }\n }\n return {\n frameAt(elapsedMs: number): SequenceFrame {\n const point = locate(elapsedMs)\n return { animation: point.animation, frameIndex: point.frameIndex }\n },\n remainingAt(elapsedMs: number): number {\n const point = locate(elapsedMs)\n return Math.max(1, (point.track.durations[point.frameIndex] ?? 0) - point.offsetInFrame)\n },\n }\n}\n\n/** Resolve the active track and frame after elapsed milliseconds of a looping sequence. */\nexport function sequenceFrameAt(\n sequence: readonly PetAnimation[],\n tracks: Record<PetAnimation, PetTrackDef>,\n elapsedMs: number,\n): SequenceFrame {\n return createSequenceTimeline(sequence, tracks).frameAt(elapsedMs)\n}\n","/**\n * Pet sprite companion component — the browser half's centerpiece. Renders a\n * fixed-position floating sprite (React portal onto document.body), plays\n * the track matching the host animation snapshot, and exposes the\n * interaction surface: click to pet, hover panel with feed/rename/hide, drag\n * to reposition (persisted via setConfig). Everything visual comes from the\n * pet definition the host serves ('/api/pet/pets' + the state snapshot's\n * pet id), so one component renders every registry entry.\n * @module @linxin666/dsh-pet/client/PetSprite\n */\n\nimport { useEffect, useLayoutEffect, useRef, useState } from 'react'\nimport type { CSSProperties, PointerEvent as ReactPointerEvent, ReactElement, ReactNode, ReactPortal } from 'react'\nimport { createPortal } from 'react-dom'\nimport clsx from 'clsx'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport { bubbleScaleFor, type PetDisplayConfig } from '../persist.ts'\nimport type { PetStateView } from '../service.ts'\nimport { announcementFresh, type PetAnnouncement } from '../announce.ts'\nimport type { PetDefinition } from '../registry.ts'\nimport type { GameplayBus } from './gameplay-hud.ts'\nimport type { PetRoamDirection } from '../gameplay.ts'\nimport type { DecorationView } from '../contracts/status-decoration.ts'\nimport type { PetFeedback } from './pet-store.ts'\nimport { framePosition, rowOfTrack, scaledCellSize, trimTrack } from './spritesheet.ts'\nimport { createSequenceTimeline } from './sequences.ts'\nimport { animationForPhase, type ActivityPhase, type PetAnimation } from '../state.ts'\nimport { NS } from './locales.ts'\nimport styles from './pet.module.css'\n\n/** Props injected by the plugin apply body (store actions + locale). */\nexport interface PetSpriteProps {\n /** Latest host snapshot; null while loading. */\n snapshot: PetStateView | null\n /** The selected pet's registry definition (atlas URL + geometry + tracks). */\n definition: PetDefinition\n /** Display configuration (persisted by the host). */\n display: PetDisplayConfig\n /** Active reaction bubble, if any. */\n feedback: PetFeedback | null\n /** Pet the sprite (click). */\n onPet: () => void\n /** Feed the sprite (panel button). */\n onFeed: () => void\n /** Hide the sprite (panel button). */\n onHide: () => void\n /** Persist a drag position. */\n onDragEnd: (right: number, bottom: number) => void\n /** Drag gesture notifications for renderers with a drag track (frames2d). */\n onDraggingChange?: (dragging: boolean) => void\n /** Rename the selected pet (persisted by the host). */\n onRename: (name: string) => void\n /**\n * Report a click on one plugin-registered action (issue #6). The buttons\n * themselves come from the state snapshot's `panelActions` slice, so the\n * panel renders exactly the registrations the host serves and adds nothing\n * of its own.\n */\n onPanelAction: (id: string) => void\n /** Navigate to the session one status bubble reports on. */\n onOpenSession: (sessionId: string) => void\n /** Clear the reaction bubble (after its CSS animation). */\n onFeedbackDone: () => void\n /**\n * Custom visual replacing the sprite2d atlas animation (pet-center M3).\n * The chrome (drag, bubbles, panel, tap economy) is untouched: the visual\n * renders inside the sprite box, and the atlas load + frame loop skip.\n */\n visual?: ReactNode\n /**\n * Gameplay overlay (miku-pet generalization): rendered inside the float\n * container so hover containment and stacking work unchanged. Absent for\n * pets without a gameplay block.\n */\n hud?: ReactNode\n /**\n * Gameplay tap sink: receives the tap point as sprite-box fractions\n * (0..1). When present the chrome reports the tap IN ADDITION to the\n * affinity pet; the HUD decides zones/no-ops.\n */\n onGameplayTap?: (fractionX: number, fractionY: number) => void\n /**\n * Gameplay entry (miku-pet generalization): when present the hover panel\n * renders a 玩法 action that opens/closes the gameplay card. The chrome\n * wires it to the HUD through the per-pet bus (openCard), mirroring the\n * onGameplayTap sink. Absent for pets without a gameplay block.\n */\n onGameplayMenu?: () => void\n /** Disable the drag gesture (gameplay work mode blocks dragging). */\n dragDisabled?: boolean\n /**\n * Per-pet coordination bus. The chrome registers `walk` here so the gameplay\n * HUD can roam the pet (the same two-way shape the HUD's `tap` uses).\n */\n bus?: GameplayBus\n /**\n * DOM node the floating chrome portals into. Defaults to document.body\n * (the legacy behavior); the plugin apply passes its owning root (the\n * [data-dsh-plugin=\"pet\"] container) so the root owns the whole surface\n * and a root-keyed suppressor (the portrait mobile layer) hides the pet\n * as one unit instead of missing the portaled sprite.\n */\n portalTarget?: Element\n /** Locale translate seat (namespace-bound). */\n t: TranslateNS<typeof NS>\n /**\n * Active UI locale id, used to pick a pet-declared English rank name\n * (`rankEn`). Defaults to the document language for direct mounts/tests.\n */\n lang?: string\n}\n\n/** Clamp a drag offset inside the viewport with a margin. */\nfunction clampOffset(value: number, max: number): number {\n return Math.max(0, Math.min(max, value))\n}\n\n/**\n * The status decoration ornament (pet-center M5, #567). Renders the active\n * phase's frame segment as a CSS-background strip at a compact bubble\n * height; prefers-reduced-motion holds the segment's first frame, and a\n * missing or undecodable asset simply paints nothing (CSS background\n * failure) — the bubble text is never disturbed. The span is aria-hidden;\n * the bubble keeps its own semantics untouched.\n */\nfunction StatusOrnament(props: { decoration: DecorationView; phase: ActivityPhase }): ReactElement | null {\n const { decoration, phase } = props\n const segment = decoration.phases[phase]\n const shown = segment !== undefined && segment !== 'hide'\n const segmentKey = segment !== undefined && segment !== 'hide' ? segment.from + ':' + segment.to : 'none'\n const spanRef = useRef<HTMLSpanElement | null>(null)\n const scale = 18 / decoration.cell.height\n const frameWidth = Math.round(decoration.cell.width * scale)\n const stripWidth = decoration.columns * frameWidth\n // Value-stable dependency key: the host serves a fresh DecorationView\n // object on every state poll (2 s), so the effect must not depend on the\n // object identity — otherwise each poll would cancel and restart the\n // frame loop and the animation would jump back to its first frame.\n const durationsKey = decoration.durations.join(',')\n useEffect(() => {\n if (segment === undefined || segment === 'hide') return\n const el = spanRef.current\n if (el === null) return\n const position = (index: number): string => (-index * frameWidth) + 'px 0px'\n const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches === true\n el.style.backgroundPosition = position(segment.from)\n // A single-frame segment (from === to) has nothing to animate: with\n // loop=true the wrap branch would reset index to the same frame and the\n // tick would keep rescheduling a no-op rAF forever. Settle on the one\n // frame instead — same as the reduced-motion static hold.\n if (reduceMotion || segment.from === segment.to) return\n let timer = 0\n let index = segment.from\n let elapsed = 0\n let last = performance.now()\n const tick = (): void => {\n const now = performance.now()\n const delta = now - last\n last = now\n elapsed += delta\n let duration = decoration.durations[index] ?? 120\n // The segment's frame rate (duration ms, typically 90-160) is far\n // below the rAF cadence, so a 60fps loop would spend ~90% of its\n // ticks doing nothing. Schedule by the remaining time to the next\n // frame instead — the ornament wakes once per frame, not once per\n // screen refresh. A late wake (background tab, jank) carries extra\n // elapsed time, so catch up every due frame like the sprite loop.\n if (elapsed >= duration) {\n do {\n elapsed -= duration\n if (index < segment.to) index += 1\n else if (decoration.loop) index = segment.from\n // Durations are per frame: a catch-up that crosses frames must\n // subtract and schedule with the frame it lands on, not the one\n // the tick started from.\n duration = decoration.durations[index] ?? 120\n } while (elapsed >= duration)\n // Only advance the background when the frame actually changes.\n el.style.backgroundPosition = position(index)\n }\n // A non-looping segment settles on its last frame; stop scheduling\n // instead of repainting the same position every frame.\n if (!decoration.loop && index === segment.to) return\n timer = window.setTimeout(tick, Math.max(1, duration - elapsed))\n }\n timer = window.setTimeout(tick, 0)\n return () => window.clearTimeout(timer)\n }, [shown, segmentKey, frameWidth, decoration.loop, durationsKey])\n if (!shown) return null\n return (\n <span\n ref={spanRef}\n aria-hidden=\"true\"\n data-dsh-pet-decoration={decoration.id}\n style={{\n display: 'inline-block',\n width: frameWidth,\n height: 18,\n marginRight: 6,\n verticalAlign: 'middle',\n flexShrink: 0,\n backgroundImage: 'url(' + decoration.entryUrl + ')',\n backgroundSize: stripWidth + 'px 18px',\n backgroundRepeat: 'no-repeat',\n backgroundPosition: '0px 0px',\n }}\n />\n )\n}\n\n/**\n * The announcement bubble (dsh-usage linkage): a dedicated, specially\n * designed surface for sibling-plugin facts — a balance or today-spend pill,\n * or a plan-quota card with a tone-tinted accent, a mini meter for percent\n * windows, and the reset instant. It rides the top of the session bubble\n * stack (column-reverse puts the DOM-last child farthest from the sprite)\n * and persists for its TTL instead of the short feedback pop.\n */\nfunction UsageAnnouncementBubble(props: { announcement: PetAnnouncement }): ReactNode {\n const { announcement } = props\n const tone = announcement.tone === 'low'\n ? styles.bubbleUsageLow\n : announcement.tone === 'warn'\n ? styles.bubbleUsageWarn\n : styles.bubbleUsageOk\n return (\n <div\n className={clsx(styles.bubble, styles.bubbleUsage, tone)}\n role=\"status\"\n aria-live=\"polite\"\n data-dsh-pet-announcement={announcement.source}\n >\n <span className={styles.bubbleUsageHead}>\n <span className={styles.bubbleUsageTitle}>{announcement.title}</span>\n {(announcement.kind === 'balance' || announcement.kind === 'cost') && announcement.amount !== undefined && (\n <span className={styles.bubbleUsageValue}>{announcement.amount}</span>\n )}\n {announcement.kind === 'plan' && announcement.percent !== undefined && (\n <span className={styles.bubbleUsageValue}>{Math.round(announcement.percent) + '%'}</span>\n )}\n </span>\n {announcement.kind === 'plan' && announcement.percent !== undefined && (\n <span className={styles.bubbleUsageMeter}>\n <span\n className={styles.bubbleUsageMeterFill}\n style={{ width: Math.min(100, Math.max(0, announcement.percent)) + '%' }}\n />\n </span>\n )}\n {announcement.note !== undefined && (\n <span className={styles.bubbleUsageNote}>{announcement.note}</span>\n )}\n </div>\n )\n}\n\n/**\n * The floating pet. The spritesheet frame advances on a timer scheduled for the\n * current frame's remaining time (per-frame durations come from the\n * definition's tracks), so the loop wakes once per frame change instead of once\n * per screen refresh; the atlas image is loaded once and the background\n * position is written straight to the sprite element (no per-frame React\n * state). Roaming writes the sprite's position the same way (issue #17).\n */\nexport function PetSprite(props: PetSpriteProps): ReactPortal {\n const { snapshot, definition, display, feedback } = props\n const spriteRef = useRef<HTMLDivElement | null>(null)\n const floatRef = useRef<HTMLDivElement | null>(null)\n const panelRef = useRef<HTMLDivElement | null>(null)\n // Whichever bubble surface is currently rendered (feedback, the session\n // stack, or the legacy status bubble) — only one exists at a time.\n const bubbleRef = useRef<HTMLDivElement | null>(null)\n const [imageReady, setImageReady] = useState(false)\n const [hovered, setHovered] = useState(false)\n // Multi-session bubble stack: collapsed by default (only the display\n // session's bubble + a '+N' badge), expanded on stack hover (peek) or by\n // tapping the badge (pinned, for touch). The display session's bubble\n // anchors the bottom of the stack and never moves when extras open above\n // it, so the pointer target cannot flicker.\n const [stackPeek, setStackPeek] = useState(false)\n const [stackPinned, setStackPinned] = useState(false)\n const [renaming, setRenaming] = useState(false)\n const [panelAbove, setPanelAbove] = useState(false)\n // Extra margin-bottom for the above-panel so it stacks clear of the\n // bubbles instead of overlapping them (both anchor at the sprite's top).\n const [panelLift, setPanelLift] = useState(0)\n const [nameDraft, setNameDraft] = useState('')\n // Explicit IME composition tracking: some input methods (WeChat IME on\n // Windows) report keydowns with isComposing === false mid-composition, so\n // the native flag alone is not a safe submit/cancel guard (#303).\n const composingRef = useRef(false)\n const [dragPos, setDragPos] = useState<{ right: number; bottom: number } | null>(null)\n const dragRef = useRef<{ startX: number; startY: number; right: number; bottom: number } | null>(null)\n const hideTimerRef = useRef<number | null>(null)\n const frameRef = useRef<{ track: PetAnimation | null; index: number; elapsed: number }>({\n track: null,\n index: 0,\n elapsed: 0,\n })\n\n const cell = definition.cell\n const columns = definition.columns\n const rows = definition.rows\n const tracks = definition.tracks\n const sequences = definition.sequences\n // Hover-panel chrome from the pet's voice pack (pet-center M4, issue\n // #677): every slot falls back to the i18n dictionary when unset. Stat\n // formats carry {rank}/{n}/{points} placeholders the host validated.\n const panel = definition.panel\n const panelLabel = (slot: 'feed' | 'rename' | 'hide' | 'confirm', i18n: string): string =>\n panel?.labels?.[slot] ?? i18n\n // The active rank name is display-only: a pet-declared ladder may carry an\n // English variant, while built-in names still resolve through the i18n\n // dictionary. `lang` is handed down by the mount; the document language is\n // the direct-mount/test fallback.\n const englishUi = (props.lang ?? (typeof document === 'undefined' ? 'zh' : document.documentElement.lang))\n .toLowerCase()\n .startsWith('en')\n const rankNameOf = (): string => {\n const rawRank = snapshot?.affinity.rank ?? '?'\n const rankEn = snapshot?.affinity.rankEn\n if (englishUi && rankEn !== undefined) return rankEn\n const rankKey = `pet.rank.name.${rawRank}`\n const localized = props.t(rankKey as never)\n return localized !== rankKey ? localized : rawRank\n }\n const panelStat = (\n slot: 'rank' | 'treats' | 'points',\n i18nKey: 'pet.rank' | 'pet.treats' | 'pet.points',\n values: Record<string, string | number>,\n ): string => {\n const format = panel?.stats?.[slot] ?? props.t(i18nKey, values)\n if (panel?.stats?.[slot] === undefined) return format\n // The host whitelists {rank}/{n}/{points} in every stat slot, so a pack\n // format may reference any of them; substitute all three live values\n // (the slot's own value plus the siblings) instead of only the slot's.\n // {rank} carries the effective name, so a pet ladder's English variant\n // also reaches a custom stat format.\n const all: Record<string, string | number> = {\n rank: values.rank !== undefined ? values.rank : rankNameOf(),\n n: snapshot?.treats.stocked ?? 0,\n points: snapshot?.affinity.points ?? 0,\n }\n let text = format\n for (const [name, value] of Object.entries(all)) text = text.replaceAll('{' + name + '}', String(value))\n return text\n }\n const panelShows = (action: 'feed' | 'rename' | 'hide'): boolean =>\n panel?.actions === undefined || panel.actions.includes(action)\n\n // Load the atlas once; the definition carries the authoritative per-row\n // frame counts and per-track durations, so nothing else is fetched. A\n // custom visual (pet-center M3) replaces the atlas entirely.\n useEffect(() => {\n if (props.visual !== undefined) return\n setImageReady(false)\n let cancelled = false\n let retryTimer: ReturnType<typeof setTimeout> | undefined\n let attempt = 0\n const maxAttempts = 3\n let activeImg: HTMLImageElement | null = null\n\n const loadAtlas = () => {\n const img = new Image()\n activeImg = img\n img.onload = () => {\n if (!cancelled) setImageReady(true)\n }\n img.onerror = () => {\n if (cancelled) return\n if (attempt < maxAttempts) {\n attempt += 1\n const delay = Math.min(1000 * Math.pow(2, attempt - 1), 8000)\n retryTimer = setTimeout(loadAtlas, delay)\n }\n }\n img.src = definition.atlasUrl\n }\n\n loadAtlas()\n\n return () => {\n cancelled = true\n if (retryTimer !== undefined) clearTimeout(retryTimer)\n if (activeImg !== null) {\n activeImg.onload = null\n activeImg.onerror = null\n }\n }\n }, [definition.atlasUrl, props.visual])\n\n // Frame loop: advance the current track and write background-position.\n // Offsets must be in SCALED coordinates (background-position applies to the\n // scaled background image), so the current sprite scale rides a ref that\n // the loop reads every tick. Under prefers-reduced-motion the sprite holds\n // its track's first frame instead of animating (presentation-only; the\n // animation state machine is untouched).\n const spriteScale = display.size / cell.height\n const phase = snapshot?.phase ?? 'idle'\n const animation = snapshot?.animation ?? 'idle'\n const scaleRef = useRef(spriteScale)\n scaleRef.current = spriteScale\n // The frame the loop painted last. A settled non-looping track leaves the\n // loop stopped, so a later scale change repaints it from here instead of\n // waking the loop.\n const paintedRef = useRef<{ row: number; col: number } | null>(null)\n useEffect(() => {\n if (props.visual !== undefined) return\n const reduceMotion = typeof window !== 'undefined'\n && window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches === true\n const sequence = animation === animationForPhase(phase) ? sequences?.[phase] : undefined\n // Sequence state hoisted into the effect scope: the cumulative duration\n // table and each item's trimmed track would otherwise be recomputed every\n // tick (map/reduce plus two slices per frame), the same waste the\n // single-track branch below avoids.\n const timeline = sequence === undefined ? undefined : createSequenceTimeline(sequence, tracks)\n const sequenceItems = sequence === undefined ? undefined : new Map(\n sequence.map(itemAnimation => {\n const itemRow = rowOfTrack(itemAnimation)\n return [itemAnimation, {\n row: itemRow,\n track: trimTrack(tracks[itemAnimation], rows[itemRow] ?? tracks[itemAnimation].frames.length),\n }]\n }),\n )\n const leadAnimation = sequence?.[0] ?? animation\n const row = rowOfTrack(leadAnimation)\n const track = trimTrack(tracks[leadAnimation], rows[row] ?? tracks[leadAnimation].frames.length)\n // Write one frame's offset to the sprite element, skipping the assignment\n // when the coordinates did not change. lastPosStr is the cache the whole\n // loop shares, so a tick that changes nothing costs no style write.\n let lastPosStr = ''\n const paint = (frameRow: number, col: number): void => {\n paintedRef.current = { row: frameRow, col }\n const pos = framePosition(cell, frameRow, col, scaleRef.current)\n const posStr = pos.x + 'px ' + pos.y + 'px'\n if (posStr === lastPosStr) return\n lastPosStr = posStr\n if (spriteRef.current !== null) {\n spriteRef.current.style.backgroundPosition = posStr\n }\n }\n // Paint one static sprite frame up front either way, so the pet is never\n // blank while the loop heat-up runs.\n paint(row, track.frames[0]!)\n if (reduceMotion) return\n let timer = 0\n let last = performance.now()\n let sequenceElapsed = 0\n // Sleep to the next frame boundary instead of waking on every screen\n // refresh: track durations are 300-700 ms, so a 60 Hz loop spent the vast\n // majority of its ticks proving that nothing had changed -- the same rule\n // StatusOrnament already follows. A late wake (throttled tab, jank) still\n // catches up every due frame, so the track keeps its own clock.\n const schedule = (delay: number): void => {\n timer = window.setTimeout(tick, Math.max(1, delay))\n }\n const tick = (): void => {\n timer = 0\n const now = performance.now()\n const delta = now - last\n last = now\n if (timeline !== undefined && sequenceItems !== undefined) {\n sequenceElapsed += delta\n const current = timeline.frameAt(sequenceElapsed)\n const item = sequenceItems.get(current.animation)!\n paint(item.row, item.track.frames[current.frameIndex]!)\n schedule(timeline.remainingAt(sequenceElapsed))\n return\n }\n // row/track come from the effect scope: they were computed once above\n // and this effect re-runs when animation/tracks/rows change, so the\n // per-frame recompute (trimTrack slices fresh arrays) is pure waste.\n const st = frameRef.current\n if (st.track !== animation) {\n st.track = animation\n st.index = 0\n st.elapsed = 0\n }\n st.elapsed += delta\n const maxIndex = track.frames.length - 1\n while (st.elapsed >= (track.durations[st.index] ?? 0) && st.index < maxIndex) {\n st.elapsed -= track.durations[st.index] ?? 0\n st.index += 1\n }\n if (st.elapsed >= (track.durations[st.index] ?? 0)) {\n if (!track.loop) {\n // Hold the final frame; the host owns the switch to the fallback, so\n // stop scheduling instead of re-painting the same frame forever.\n st.index = maxIndex\n paint(row, track.frames[st.index]!)\n return\n }\n st.elapsed = 0\n st.index = 0\n }\n paint(row, track.frames[st.index]!)\n schedule((track.durations[st.index] ?? 0) - st.elapsed)\n }\n schedule(0)\n return () => window.clearTimeout(timer)\n }, [animation, phase, cell, columns, rows, tracks, sequences, props.visual])\n\n // A stopped loop is woken by nothing, so a sprite scale change repaints the\n // frame it settled on: without this a resized pet would keep the old scale's\n // cell offsets and show a neighbouring cell until the track changed.\n useLayoutEffect(() => {\n const painted = paintedRef.current\n if (props.visual !== undefined || painted === null || spriteRef.current === null) return\n const pos = framePosition(cell, painted.row, painted.col, spriteScale)\n spriteRef.current.style.backgroundPosition = pos.x + 'px ' + pos.y + 'px'\n }, [spriteScale, cell, props.visual])\n\n // Auto-clear the feedback bubble after its CSS animation. The callback\n // rides a ref so re-renders never reset the timer: the 2s poll rebuilds\n // `props` every tick, and depending on it would starve the timeout.\n const feedbackDoneRef = useRef(props.onFeedbackDone)\n feedbackDoneRef.current = props.onFeedbackDone\n useEffect(() => {\n if (feedback === null) return\n const timer = window.setTimeout(() => feedbackDoneRef.current(), 2600)\n return () => window.clearTimeout(timer)\n }, [feedback])\n\n // Dragging: pointer events on the sprite; position is right/bottom based.\n // `draggedRef` records whether the pointer actually moved, so the browser's\n // trailing click (fired after pointerup) does not pet the sprite.\n const draggedRef = useRef(false)\n const clearHideTimer = (): void => {\n if (hideTimerRef.current !== null) {\n window.clearTimeout(hideTimerRef.current)\n hideTimerRef.current = null\n }\n }\n\n // Clear any pending auto-hide timer on unmount: a stray callback after\n // teardown reads window through react-dom and failed CI runs with\n // \"window is not defined\" (slow-runner timing, PetSprite.test.tsx).\n useEffect(() => () => clearHideTimer(), [])\n\n const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>): void => {\n if (props.dragDisabled === true) return\n // Read the live position before ending a walk: the walk keeps it in a ref\n // rather than React state, so a drag grabbed mid-walk starts where the pet\n // actually is instead of snapping back to where the walk began.\n const current = walkTargetRef.current ?? dragPosRef.current ?? { right: display.right, bottom: display.bottom }\n endWalk(false)\n e.preventDefault()\n ;(e.target as HTMLElement).setPointerCapture?.(e.pointerId)\n dragRef.current = { startX: e.clientX, startY: e.clientY, ...current }\n draggedRef.current = false\n setHovered(false)\n }\n const onPointerMove = (e: ReactPointerEvent<HTMLDivElement>): void => {\n const drag = dragRef.current\n if (drag === null) return\n const dx = e.clientX - drag.startX\n const dy = e.clientY - drag.startY\n if (Math.abs(dx) > 4 || Math.abs(dy) > 4) {\n if (!draggedRef.current) props.onDraggingChange?.(true)\n draggedRef.current = true\n }\n const right = clampOffset(drag.right - dx, window.innerWidth - 40)\n const bottom = clampOffset(drag.bottom - dy, window.innerHeight - 40)\n setDragPos({ right, bottom })\n }\n const onPointerUp = (): void => {\n if (dragRef.current === null) return\n dragRef.current = null\n if (draggedRef.current) props.onDraggingChange?.(false)\n if (dragPos !== null) props.onDragEnd(dragPos.right, dragPos.bottom)\n }\n\n // --- roaming ---------------------------------------------------------\n // The gameplay HUD rolls when the pet may wander; this side owns the motion\n // (clamped to the viewport), the walk art's facing and the persisted resting\n // spot -- the walk ends on the same write a drag ends with. The walk art\n // faces left, so a rightward walk mirrors the sprite (a vertical walk keeps\n // the side view); every other track stays unmirrored.\n const [facingRight, setFacingRight] = useState(false)\n const walkRafRef = useRef(0)\n // Live position while a walk is in flight. The walk writes the element's\n // right/bottom directly and mirrors them here instead of calling setState:\n // a walk is 1-3 s of 60 fps motion, and each frame used to re-render the\n // whole sprite tree (bubble stack, dock panel) for a position the DOM already\n // knew. Keeping it in a ref means a render that lands mid-walk (a poll, a\n // hover) still sees where the sprite actually is (issue #17).\n const walkTargetRef = useRef<{ right: number; bottom: number } | null>(null)\n const dragPosRef = useRef(dragPos)\n dragPosRef.current = dragPos\n\n const pos = walkTargetRef.current ?? dragPos ?? { right: display.right, bottom: display.bottom }\n // One integral cell size for the sprite box, the atlas grid and every frame\n // offset: background-size is this size times the column/row count, so the\n // scaled atlas shares a pixel grid with the box that shows one cell (#17).\n const scaled = scaledCellSize(cell, spriteScale)\n const spriteWidth = scaled.width\n const spriteHeight = scaled.height\n\n /** Stop an active walk; `persist` lands the pet on the spot it reached. */\n const endWalk = (persist: boolean): void => {\n if (walkRafRef.current === 0) return\n window.cancelAnimationFrame(walkRafRef.current)\n walkRafRef.current = 0\n setFacingRight(false)\n const settled = walkTargetRef.current\n walkTargetRef.current = null\n if (settled === null) return\n // Hand the reached spot back to React state: the walk's own frames never\n // updated it, and a render (or a drag that starts here) would otherwise\n // put the sprite back where the walk began.\n setDragPos(settled)\n if (persist) props.onDragEnd(settled.right, settled.bottom)\n }\n\n useEffect(() => {\n const bus = props.bus\n if (bus === undefined) return undefined\n bus.walk = (direction: PetRoamDirection, distance: number, speed: number): number => {\n if (dragRef.current !== null || walkRafRef.current !== 0) return 0\n const current = dragPosRef.current ?? { right: display.right, bottom: display.bottom }\n // Keep the whole sprite on screen with an 8px breathing margin. `right`\n // and `bottom` are CSS offsets: right grows leftwards, bottom upwards.\n const margin = 8\n const maxRight = Math.max(margin, window.innerWidth - spriteWidth - margin)\n const maxBottom = Math.max(margin, window.innerHeight - spriteHeight - margin)\n const wanted = { ...current }\n if (direction === 'left') wanted.right = current.right + distance\n else if (direction === 'right') wanted.right = current.right - distance\n else if (direction === 'up') wanted.bottom = current.bottom + distance\n else wanted.bottom = current.bottom - distance\n const target = {\n right: Math.max(margin, clampOffset(wanted.right, maxRight)),\n bottom: Math.max(margin, clampOffset(wanted.bottom, maxBottom)),\n }\n const travelled = direction === 'left' ? target.right - current.right\n : direction === 'right' ? current.right - target.right\n : direction === 'up' ? target.bottom - current.bottom\n : current.bottom - target.bottom\n if (travelled < 1) return 0\n const duration = Math.max(150, (travelled / Math.max(1, speed)) * 1000)\n const startedAt = performance.now()\n // The crawl art faces left, so only a rightward walk mirrors it; a\n // vertical walk keeps the side view (there is no front/back art).\n setFacingRight(direction === 'right')\n walkTargetRef.current = current\n const step = (now: number): void => {\n const t = Math.min(1, (now - startedAt) / duration)\n const next = {\n right: current.right + (target.right - current.right) * t,\n bottom: current.bottom + (target.bottom - current.bottom) * t,\n }\n walkTargetRef.current = next\n // The position goes straight to the element: a walk is the one motion\n // that moved every frame, and a setState here re-rendered the bubble\n // stack and the dock panel for a value the DOM already knew (issue\n // #17). React state takes over once, on the landing frame.\n const el = floatRef.current\n if (el !== null) {\n el.style.right = next.right + 'px'\n el.style.bottom = next.bottom + 'px'\n }\n if (t < 1) {\n walkRafRef.current = window.requestAnimationFrame(step)\n return\n }\n walkRafRef.current = 0\n walkTargetRef.current = null\n setFacingRight(false)\n setDragPos(next)\n props.onDragEnd(next.right, next.bottom)\n }\n walkRafRef.current = window.requestAnimationFrame(step)\n return travelled\n }\n return () => {\n bus.walk = undefined\n if (walkRafRef.current !== 0) {\n window.cancelAnimationFrame(walkRafRef.current)\n walkRafRef.current = 0\n }\n // A cancelled walk must not leave the sprite mirrored.\n setFacingRight(false)\n walkTargetRef.current = null\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps -- one registration per sprite\n }, [props.bus, definition.id, display.right, display.bottom, spriteWidth])\n // Bubble typography follows the sprite's own scale (#1549), bounded so a\n // shrunk pet never carries unreadably small text.\n const bubbleScale = bubbleScaleFor(display)\n\n // Concurrent sessions share one bubble slot: only the display session\n // speaks by default, and the rest hide behind a '+N' badge until the stack\n // is hovered/pinned open. The legacy single 'bubble' is the fallback when\n // the host serves no per-session list. The hover panel normally sits below\n // the sprite, so the bubbles stay visible and clickable — no region swap.\n // Whether the pet renders its OWN session/status bubbles (issue #6). Only\n // these are gated: the interaction feedback bubble and a sibling plugin's\n // announcement bubble are separate surfaces and keep rendering, so a plugin\n // that drives its own bubble can switch the built-in ones off. A host that\n // predates the field serves no mode at all, which reads as 'auto' — the\n // behavior that shipped before the switch existed.\n const statusBubblesOn = (snapshot?.statusBubbles ?? 'auto') !== 'off'\n const sessionBubbles = statusBubblesOn ? (snapshot?.sessions ?? []) : []\n const stackOpen = stackPeek || stackPinned\n const collapsed = !stackOpen && sessionBubbles.length > 1\n const visibleSessions = collapsed ? sessionBubbles.slice(0, 1) : sessionBubbles\n const statusBubble = statusBubblesOn && feedback === null && sessionBubbles.length === 0\n ? snapshot?.bubble\n : undefined\n // The plugin-authored announcements: one dedicated, specially styled bubble\n // per publishing plugin above the session stack (issue #1812 — the contract\n // used to hold a single slot, so a second publisher displaced the first).\n // The host already TTL-filters; this client-side check covers the last poll\n // tick. A host predating the array serves the singular field only, and a\n // browser half predating it (this file, before the upgrade) renders the same\n // one bubble, so neither side of a rolling upgrade loses a publisher.\n const announced = snapshot?.announcements ?? (snapshot?.announcement !== undefined ? [snapshot.announcement] : [])\n const now = Date.now()\n const usageAnnouncements = feedback === null ? announced.filter(entry => announcementFresh(entry, now)) : []\n // Each session's inner whisper (碎碎念) rides its own bubble — short\n // inner-voice copy woken by that session's activity, never the model's or\n // another session's. Instead of a second bubble of its own, a fresh\n // whisper takes over its session's bubble and re-tints it, so the pet\n // never wears two voices at once. Interaction feedback takes over the\n // whole bubble area while it plays, so whispers yield to it like status\n // copy.\n const bubblePresent = feedback !== null || sessionBubbles.length > 0 || statusBubble !== undefined || usageAnnouncements.length > 0\n const displayName = snapshot?.name ?? definition.displayName\n // The host-served status decoration (M5, #567); absent = text-only bubbles.\n const decoration = snapshot?.decoration\n\n // A settled session list can no longer stay pinned open.\n useEffect(() => {\n if (sessionBubbles.length <= 1) setStackPinned(false)\n }, [sessionBubbles.length])\n\n useLayoutEffect(() => {\n if (!hovered) {\n setPanelAbove(false)\n setPanelLift(0)\n return\n }\n const updatePanelPlacement = (): void => {\n const sprite = spriteRef.current\n const panel = panelRef.current\n if (sprite === null || panel === null) return\n const availableBelow = window.innerHeight - sprite.getBoundingClientRect().bottom\n const above = availableBelow < panel.getBoundingClientRect().height + 8\n setPanelAbove(above)\n // The fallback above-placement shares the sprite's top edge with the\n // bubble(s); lift the panel by the bubble area's height so the two\n // never overlap (8px base gap + 6px clearance above the top bubble).\n const bubbleHeight = above ? bubbleRef.current?.getBoundingClientRect().height ?? 0 : 0\n setPanelLift(bubbleHeight > 0 ? Math.ceil(bubbleHeight) + 14 : 0)\n }\n updatePanelPlacement()\n window.addEventListener('resize', updatePanelPlacement)\n return () => window.removeEventListener('resize', updatePanelPlacement)\n }, [hovered, renaming, pos.right, pos.bottom, display.size, bubblePresent, sessionBubbles.length, stackOpen, feedback])\n\n const float = (\n <div\n ref={floatRef}\n className={styles.float}\n style={{\n right: pos.right,\n bottom: pos.bottom,\n zIndex: 2147483000,\n // Read by .bubble / .bubbleStatus in pet.module.css.\n ...({ '--pet-bubble-scale': String(bubbleScale) } as CSSProperties),\n }}\n onPointerEnter={() => {\n clearHideTimer()\n setHovered(true)\n }}\n onPointerLeave={(e) => {\n // The panel renders OUTSIDE the container's box (absolute, below\n // the sprite), so moving onto it fires pointerleave on the container.\n // Treat a target still inside the container's DOM (the overflowed\n // panel) as \"still hovering\"; otherwise give the pointer a short\n // grace period to reach the panel across the gap below the sprite.\n // The bridge ('.panel::after') keeps the pointer inside the hit\n // area, and the grace period covers a slow mouse crossing the\n // remaining sliver.\n const next = e.relatedTarget\n if (next instanceof Node && floatRef.current?.contains(next)) return\n // Never auto-hide while the rename box is open: moving the pointer\n // onto an IME candidate window (an OS-level window outside the\n // webview) fires pointerleave, and unmounting the input mid-IME-\n // composition crashes some input methods / the renderer (#303).\n if (renaming) return\n clearHideTimer()\n hideTimerRef.current = window.setTimeout(() => setHovered(false), 300)\n }}\n >\n <div\n className={styles.spriteWrap}\n style={{ width: spriteWidth, height: spriteHeight }}\n >\n <div\n ref={spriteRef}\n className={styles.sprite}\n style={{\n width: spriteWidth,\n height: spriteHeight,\n ...(props.visual === undefined\n ? {\n backgroundImage: imageReady ? 'url(' + definition.atlasUrl + ')' : undefined,\n backgroundSize: (scaled.width * columns) + 'px ' + (scaled.height * (definition.atlasRows ?? rows.length)) + 'px',\n backgroundRepeat: 'no-repeat',\n backgroundPosition: '0 0',\n }\n : {}),\n cursor: dragRef.current === null ? 'grab' : 'grabbing',\n ...(facingRight ? { transform: 'scaleX(-1)' } : {}),\n }}\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n onPointerUp={onPointerUp}\n onClick={(e) => {\n // A pointer sequence that moved (dragged) still fires a trailing\n // click; skip the pet when that happened.\n if (draggedRef.current) return\n if (props.onGameplayTap !== undefined && spriteRef.current !== null) {\n const rect = spriteRef.current.getBoundingClientRect()\n if (rect.width > 0 && rect.height > 0) {\n props.onGameplayTap((e.clientX - rect.left) / rect.width, (e.clientY - rect.top) / rect.height)\n }\n }\n props.onPet()\n }}\n role=\"button\"\n aria-label={definition.displayName}\n >\n {props.visual}\n </div>\n </div>\n {props.hud}\n {feedback !== null && (\n <div key={feedback.at} ref={bubbleRef} className={clsx(styles.bubble, feedback.kind === 'feed' ? styles.bubbleFeed : styles.bubblePet)}>\n {feedback.text}\n </div>\n )}\n {feedback === null && (sessionBubbles.length > 0 || statusBubble !== undefined || usageAnnouncements.length > 0) && (\n <div\n ref={bubbleRef}\n className={styles.bubbleStack}\n onPointerEnter={() => setStackPeek(true)}\n onPointerLeave={() => setStackPeek(false)}\n >\n {visibleSessions.map((session, index) => {\n // A session's whisper rides ITS OWN bubble (the stack lead when\n // the current session has one, any bubble when the stack is\n // expanded). The key swap restarts the entrance animation so the\n // mood change reads as the bubble re-speaking.\n const speaksWhisper = session.whisper !== undefined\n const bubble = (\n <button\n key={speaksWhisper ? 'whisper:' + session.whisper : session.sessionId}\n type=\"button\"\n className={clsx(\n styles.bubble,\n styles.bubbleStatus,\n styles.bubbleClickable,\n speaksWhisper && styles.bubbleWhisper,\n )}\n title={props.t('pet.openSessionHint')}\n onClick={() => { props.onOpenSession(session.sessionId) }}\n >\n {index === 0 && !speaksWhisper && decoration !== undefined && (\n <StatusOrnament decoration={decoration} phase={phase} />\n )}\n {session.whisper ?? session.bubble}\n </button>\n )\n // The primary bubble carries the '+N' badge while other sessions\n // hide behind it; the badge toggles the pinned (touch) expansion.\n if (index !== 0 || sessionBubbles.length <= 1) return bubble\n return (\n <span key=\"primary\" className={styles.bubbleAnchor}>\n {bubble}\n <button\n type=\"button\"\n className={styles.bubbleMore}\n title={stackOpen\n ? props.t('pet.collapseSessions')\n : props.t('pet.moreSessions', { n: sessionBubbles.length - 1 })}\n aria-label={stackOpen\n ? props.t('pet.collapseSessions')\n : props.t('pet.moreSessions', { n: sessionBubbles.length - 1 })}\n aria-expanded={stackOpen}\n onClick={(e) => {\n e.stopPropagation()\n setStackPinned(open => !open)\n }}\n >\n {stackOpen ? '×' : '+' + String(sessionBubbles.length - 1)}\n </button>\n </span>\n )\n })}\n {sessionBubbles.length === 0 && statusBubble !== undefined && (\n <div\n key=\"status\"\n className={clsx(styles.bubble, styles.bubbleStatus)}\n role=\"status\"\n aria-live=\"polite\"\n >\n {decoration !== undefined && (\n <StatusOrnament decoration={decoration} phase={phase} />\n )}\n {statusBubble}\n </div>\n )}\n {/*\n One bubble per publishing plugin, in the order the host serves\n them. Keyed by `source`, not by arrival: a repeating publisher\n updates its own bubble in place instead of remounting (which would\n replay the entrance animation on every poll), and two publishers on\n different cadences keep their positions.\n */}\n {usageAnnouncements.map(entry => (\n <UsageAnnouncementBubble key={entry.source} announcement={entry} />\n ))}\n </div>\n )}\n {hovered && dragRef.current === null && (\n <div\n ref={panelRef}\n className={clsx(styles.panel, panelAbove && styles.panelAbove)}\n data-placement={panelAbove ? 'above' : 'below'}\n style={panelAbove && panelLift > 0\n ? ({ marginBottom: panelLift } as CSSProperties)\n : undefined}\n onPointerEnter={() => {\n // Reaching the panel (or its bridge) must cancel any hide timer\n // the container's pointerleave may have armed while the pointer\n // crossed the sliver between the sprite and the panel.\n clearHideTimer()\n }}\n >\n {renaming ? (\n <div className={styles.renameRow}>\n <input\n className={styles.nameInput}\n value={nameDraft}\n maxLength={20}\n placeholder={props.t('pet.namePlaceholder')}\n autoFocus\n onChange={(e) => setNameDraft(e.target.value)}\n onCompositionStart={() => { composingRef.current = true }}\n onCompositionEnd={() => { composingRef.current = false }}\n onKeyDown={(e) => {\n // While an IME composition is active (e.g. selecting a\n // Chinese candidate), Enter/Escape keydowns belong to the\n // input method: ignore them so candidate selection can\n // neither submit the draft nor close the rename box. The\n // explicit ref and the 'Process' key cover IMEs that mark\n // composition keydowns with isComposing === false (#303).\n if (composingRef.current || e.nativeEvent.isComposing || e.key === 'Process') return\n if (e.key === 'Enter') {\n const trimmed = nameDraft.trim()\n if (trimmed !== '') {\n props.onRename(trimmed)\n setRenaming(false)\n }\n } else if (e.key === 'Escape') {\n setRenaming(false)\n }\n }}\n />\n <button\n type=\"button\"\n className={styles.action}\n onClick={() => {\n const trimmed = nameDraft.trim()\n if (trimmed !== '') {\n props.onRename(trimmed)\n setRenaming(false)\n }\n }}\n >\n {panelLabel('confirm', props.t('pet.confirm'))}\n </button>\n </div>\n ) : (\n <>\n <div className={styles.rankRow}>\n <span className={styles.nameCell}>{displayName}</span>\n <span className={styles.statRank}>\n {panelStat('rank', 'pet.rank', { rank: rankNameOf() })}\n </span>\n </div>\n <div className={styles.rankRow}>\n <span className={styles.statTreats}>{panelStat('treats', 'pet.treats', { n: snapshot?.treats.stocked ?? 0 })}</span>\n <span className={styles.statPoints}>{panelStat('points', 'pet.points', { points: snapshot?.affinity.points ?? 0 })}</span>\n </div>\n <div className={styles.actions}>\n {panelShows('feed') && (\n <button type=\"button\" className={styles.action} onClick={props.onFeed}>\n {panelLabel('feed', props.t('pet.feed'))}\n </button>\n )}\n {panelShows('rename') && (\n <button\n type=\"button\"\n className={styles.action}\n onClick={() => {\n // Cancel any pending hide so the rename box cannot\n // unmount right as the user starts typing (#303).\n clearHideTimer()\n setNameDraft(displayName)\n setRenaming(true)\n }}\n >\n {panelLabel('rename', props.t('pet.rename'))}\n </button>\n )}\n {panelShows('hide') && (\n <button type=\"button\" className={styles.action} onClick={props.onHide}>\n {panelLabel('hide', props.t('pet.hide'))}\n </button>\n )}\n {props.onGameplayMenu !== undefined && (\n <button type=\"button\" className={styles.action} onClick={props.onGameplayMenu}>\n {props.t('pet.gameplay.menu')}\n </button>\n )}\n {/*\n Plugin-registered actions (issue #6). They follow the built-in\n ones so the pet's own row keeps its fixed order, and they\n carry their registration id as a data attribute so a test (or\n a skin) can address one action without depending on its label.\n */}\n {(snapshot?.panelActions ?? []).map(action => (\n <button\n key={action.id}\n type=\"button\"\n className={styles.action}\n data-dsh-pet-panel-action={action.id}\n {...(action.title === undefined ? {} : { title: action.title })}\n onClick={() => { props.onPanelAction(action.id) }}\n >\n {action.label}\n </button>\n ))}\n </div>\n </>\n )}\n </div>\n )}\n </div>\n )\n\n return createPortal(float, props.portalTarget ?? document.body)\n}\n","/**\n * Drag stream — bridges the chrome's pointer drag state onto the renderer\n * contract's { get, subscribe } shape, so renderers with a dedicated drag\n * track (frames2d) can follow the chrome-owned drag gesture. Dispatch is\n * change-only, mirroring the phase stream.\n * @module @linxin666/dsh-pet/client/drag-stream\n */\n\n/** The renderer-facing drag stream. */\nexport interface DragStream {\n /** Whether the chrome reports an active drag gesture. */\n get(): boolean\n /** Subscribe to drag state changes; returns the unsubscribe. */\n subscribe(listener: (dragging: boolean) => void): () => void\n /** Feed a fresh drag state; no-op when unchanged. */\n push(dragging: boolean): void\n}\n\n/** Create the stream (one per pet activation, owned by the renderer switch). */\nexport function createDragStream(): DragStream {\n let current = false\n const listeners = new Set<(dragging: boolean) => void>()\n return {\n get: () => current,\n subscribe(listener) {\n listeners.add(listener)\n return () => { listeners.delete(listener) }\n },\n push(dragging) {\n if (dragging === current) return\n current = dragging\n for (const listener of [...listeners]) listener(dragging)\n },\n }\n}\n","/**\n * Renderer registry — dispatches a manifest's renderer kind to its\n * implementation (pet-center M2 P4, issue #623). Unknown kinds never blank\n * the pet: a fallback card names the problem and reports the kinds this\n * build actually supports.\n * @module @linxin666/dsh-pet/client/renderers/registry\n */\n\nimport type { PetRenderer, PetRendererContext, PetRendererHandle } from '../../contracts/renderer.ts'\n\n/** Renderer dispatch table. */\nexport class RendererRegistry {\n private readonly renderers = new Map<string, PetRenderer>()\n\n /** Register one renderer implementation (id wins on re-register). */\n register(renderer: PetRenderer): void {\n this.renderers.set(renderer.id, renderer)\n }\n\n /** Whether a renderer kind is available in this build. */\n has(id: string): boolean {\n return this.renderers.has(id)\n }\n\n /** The registered renderer kinds (for diagnostics). */\n kinds(): string[] {\n return [...this.renderers.keys()].sort()\n }\n\n /** Remove every registration (tests; the client index registers once). */\n clear(): void {\n this.renderers.clear()\n }\n\n /**\n * Mount a renderer for one activation. An unknown kind renders a clear\n * diagnostic card into the container instead of failing silently.\n */\n mount(kind: string, ctx: PetRendererContext, config: unknown): PetRendererHandle {\n const renderer = this.renderers.get(kind)\n if (renderer === undefined) {\n const note = document.createElement('div')\n note.dataset.dshPetRendererFallback = kind\n note.textContent = 'Pet renderer \"' + kind + '\" is not available in this build (supported: ' + this.kinds().join(', ') + ').'\n ctx.container.appendChild(note)\n ctx.onCleanup(() => note.remove())\n return { dispose: () => note.remove() }\n }\n return renderer.mount(ctx, renderer.validateConfig(config))\n }\n}\n\n/**\n * The plugin-wide renderer registry. The client entry registers the\n * built-in renderers at apply time; the renderer switch and the live2d\n * bridge dispatch through this instance.\n */\nexport const defaultPetRendererRegistry = new RendererRegistry()\n","/**\n * Phase stream — bridges the polled host snapshots onto the renderer\n * contract's { get, subscribe } shape (pet-center M2 P4, issue #623). The\n * existing poll loop pushes each snapshot's ActivityPhase; subscribers are\n * dispatched on CHANGE only (phase transitions are sparse — done/failed hold\n * a timed window before falling back to idle — and renderers like Live2D pay\n * per transition, not per tick).\n * @module @linxin666/dsh-pet/client/phase-stream\n */\n\nimport type { ActivityPhase } from '../state.ts'\n\n/** The renderer-facing phase stream. */\nexport interface PhaseStream {\n /** The latest pushed phase. */\n get(): ActivityPhase\n /** Subscribe to phase changes; returns the unsubscribe. */\n subscribe(listener: (phase: ActivityPhase) => void): () => void\n /** Feed a fresh snapshot phase; no-op when unchanged. */\n push(phase: ActivityPhase): void\n}\n\n/** Create the stream (one per pet entry lifetime, owned by the plugin body). */\nexport function createPhaseStream(initial: ActivityPhase = 'idle'): PhaseStream {\n let current = initial\n const listeners = new Set<(phase: ActivityPhase) => void>()\n return {\n get: () => current,\n subscribe(listener) {\n listeners.add(listener)\n return () => { listeners.delete(listener) }\n },\n push(phase) {\n if (phase === current) return\n current = phase\n for (const listener of [...listeners]) listener(phase)\n },\n }\n}\n","/**\n * Live2D visual mount (pet-center M3) — the React bridge between the pet\n * center chrome and the imperative live2d renderer. The bridge owns the\n * contract context (asset base, phase stream, interaction write-back,\n * activation cleanups), feeds the polled phase into the stream, forwards\n * sub-4px taps as hit-test coordinates, and renders the localized error\n * card when the renderer reports a fatal boot failure.\n * @module @linxin666/dsh-pet/client/renderers/live2d/Live2dVisualMount\n */\n\nimport { useEffect, useRef, useState, type ReactElement } from 'react'\nimport type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { PetDefinition } from '../../../registry.ts'\nimport type { ActivityPhase } from '../../../state.ts'\nimport { createPhaseStream, type PhaseStream } from '../../phase-stream.ts'\nimport type { PetRendererContext } from '../../../contracts/renderer.ts'\nimport { defaultPetRendererRegistry } from '../registry.ts'\nimport type { Live2dErrorCode, Live2dRendererHandle } from '../live2d.ts'\nimport type { NS } from '../../locales.ts'\n\n/** Mount the live2d renderer as the sprite's visual (inside the chrome). */\nexport function Live2dVisualMount(props: {\n definition: PetDefinition\n phase: ActivityPhase\n onPet: () => void\n t: PropsLocale<typeof NS>['t']\n}): ReactElement {\n const containerRef = useRef<HTMLDivElement | null>(null)\n const streamRef = useRef<PhaseStream | null>(null)\n const handleRef = useRef<Live2dRendererHandle | null>(null)\n const downRef = useRef<{ x: number; y: number } | null>(null)\n const [error, setError] = useState<Live2dErrorCode | null>(null)\n\n // One activation per pet definition: build the contract context and mount.\n useEffect(() => {\n setError(null)\n const container = containerRef.current\n const live2d = props.definition.live2d\n if (container === null || live2d === undefined) return undefined\n streamRef.current ??= createPhaseStream(props.phase)\n const cleanups: (() => void)[] = []\n const ctx: PetRendererContext = {\n petId: props.definition.id,\n assetBase: '/pet/' + encodeURIComponent(props.definition.id),\n container,\n phase: streamRef.current,\n interact: props.onPet,\n onCleanup: (fn) => { cleanups.push(fn) },\n }\n let handle: Live2dRendererHandle\n try {\n handle = defaultPetRendererRegistry.mount('live2d', ctx, live2d) as Live2dRendererHandle\n } catch {\n setError('load-failed')\n return () => { for (const fn of cleanups.splice(0)) fn() }\n }\n handleRef.current = handle\n handle.onError?.(setError)\n return () => {\n handleRef.current = null\n for (const fn of cleanups.splice(0)) fn()\n handle.dispose()\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps -- one activation per pet identity\n }, [props.definition])\n\n // Feed the polled phase into the activation's stream (change-only).\n useEffect(() => {\n streamRef.current?.push(props.phase)\n }, [props.phase])\n\n return (\n <div\n ref={containerRef}\n data-dsh-pet-live2d={props.definition.id}\n style={{ width: '100%', height: '100%' }}\n onPointerDown={(e) => { downRef.current = { x: e.clientX, y: e.clientY } }}\n onPointerUp={(e) => {\n const down = downRef.current\n downRef.current = null\n if (down === null) return\n // A moved pointer is a drag (the chrome owns it), not a tap.\n if (Math.abs(e.clientX - down.x) > 4 || Math.abs(e.clientY - down.y) > 4) return\n const rect = e.currentTarget.getBoundingClientRect()\n handleRef.current?.tap(e.clientX - rect.left, e.clientY - rect.top)\n }}\n >\n {error !== null && (\n <span data-dsh-pet-live2d-error={error}>\n {error === 'core-missing'\n ? props.t('pet.live2d.core-missing')\n : error === 'vendor-missing'\n ? props.t('pet.live2d.vendor-missing')\n : props.t('pet.live2d.load-failed')}\n </span>\n )}\n </div>\n )\n}\n","/**\n * Frames2d visual mount — the React bridge between the pet center chrome\n * and the imperative frames2d renderer, mirroring the live2d mount. The\n * bridge owns the contract context (asset base, phase stream, interaction\n * write-back, activation cleanups), feeds the polled phase into the stream,\n * forwards the chrome's drag gesture onto the conventional 'drag' track\n * (when the pet declares one), and renders the localized fallback card when\n * the served config is invalid.\n * @module @linxin666/dsh-pet/client/renderers/Frames2dVisualMount\n */\n\nimport { useEffect, useRef, useState, type ReactElement } from 'react'\nimport type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { PetDefinition } from '../../registry.ts'\nimport type { ActivityPhase } from '../../state.ts'\nimport { createPhaseStream, type PhaseStream } from '../phase-stream.ts'\nimport type { DragStream } from '../drag-stream.ts'\nimport type { PetRendererContext } from '../../contracts/renderer.ts'\nimport { defaultPetRendererRegistry } from './registry.ts'\nimport type { Frames2dRendererHandle } from './frames2d.ts'\nimport type { GameplayBus } from '../gameplay-hud.tsx'\nimport type { NS } from '../locales.ts'\n\n/** Mount the frames2d renderer as the sprite's visual (inside the chrome). */\nexport function Frames2dVisualMount(props: {\n definition: PetDefinition\n phase: ActivityPhase\n onPet: () => void\n /** Chrome drag gesture stream (the renderer switch owns it). */\n drag: DragStream\n /** Gameplay coordination bus; the mount registers its track override. */\n bus?: GameplayBus\n t: PropsLocale<typeof NS>['t']\n}): ReactElement {\n const containerRef = useRef<HTMLDivElement | null>(null)\n const streamRef = useRef<PhaseStream | null>(null)\n const handleRef = useRef<Frames2dRendererHandle | null>(null)\n const [invalid, setInvalid] = useState(false)\n\n // One activation per pet definition: build the contract context and mount.\n useEffect(() => {\n setInvalid(false)\n const container = containerRef.current\n const frames2d = props.definition.frames2d\n if (container === null || frames2d === undefined) return undefined\n streamRef.current ??= createPhaseStream(props.phase)\n const cleanups: (() => void)[] = []\n const ctx: PetRendererContext = {\n petId: props.definition.id,\n assetBase: '/pet/' + encodeURIComponent(props.definition.id),\n container,\n phase: streamRef.current,\n interact: props.onPet,\n onCleanup: (fn) => { cleanups.push(fn) },\n }\n let handle: Frames2dRendererHandle\n try {\n handle = defaultPetRendererRegistry.mount('frames2d', ctx, frames2d) as Frames2dRendererHandle\n } catch {\n setInvalid(true)\n return () => { for (const fn of cleanups.splice(0)) fn() }\n }\n handleRef.current = handle\n // The gameplay HUD steers one shared override slot through the bus;\n // mode rules (work blocks drag, sleep wakes on it) keep the two\n // producers from fighting over the slot.\n if (props.bus !== undefined) {\n const gameplayBus = props.bus\n gameplayBus.setTrack = (track) => { handleRef.current?.setState(track) }\n gameplayBus.setIdleTrack = (track) => { handleRef.current?.setIdleTrack(track) }\n // The HUD latches the wanted base idle (skin selection, restored from the\n // host snapshot): apply it on activation, so a late or repeated mount\n // never repaints the pet with the default look.\n if (gameplayBus.idleTrack !== undefined) handle.setIdleTrack(gameplayBus.idleTrack)\n cleanups.push(() => {\n gameplayBus.setTrack = undefined\n gameplayBus.setIdleTrack = undefined\n })\n }\n // The drag gesture drives the conventional 'drag' track when declared.\n // On release, a declared gameplay.dragEndState (miku: standup) plays\n // once; its fallback auto-releases the override back to the phase map.\n const dragTrack = props.definition.gameplay?.dragState ?? (frames2d.tracks.drag === undefined ? undefined : 'drag')\n const offDrag = props.drag.subscribe((dragging) => {\n if (dragTrack === undefined) return\n if (dragging) {\n handle.setState(dragTrack)\n return\n }\n handle.setState(props.definition.gameplay?.dragEndState)\n })\n cleanups.push(offDrag)\n return () => {\n handleRef.current = null\n for (const fn of cleanups.splice(0)) fn()\n handle.dispose()\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps -- one activation per pet identity\n }, [props.definition])\n\n // Feed the polled phase into the activation's stream (change-only).\n useEffect(() => {\n streamRef.current?.push(props.phase)\n }, [props.phase])\n\n return (\n <div\n ref={containerRef}\n data-dsh-pet-frames2d={props.definition.id}\n style={{ width: '100%', height: '100%', pointerEvents: 'none' }}\n >\n {invalid && (\n <span data-dsh-pet-frames2d-error=\"invalid-config\">\n {props.t('pet.renderer.unavailable', { renderer: 'frames2d' })}\n </span>\n )}\n </div>\n )\n}\n","/**\n * Renderer switch — the client dispatch seam of the pet center (issue #623,\n * milestone M2 P5 / M3). The pet's manifest picks the renderer: sprite2d\n * hands straight through to the sprite; live2d injects its visual INTO the\n * sprite chrome (the dock, bubbles and panel belong to the pet center, not\n * the renderer); a renderer this build cannot serve renders a clear\n * diagnostic card instead of blanking.\n * @module @linxin666/dsh-pet/client/renderers/PetRendererSwitch\n */\n\nimport { cloneElement, isValidElement, useRef, type ReactElement, type ReactNode } from 'react'\nimport type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { PetDefinition } from '../../registry.ts'\nimport type { ActivityPhase } from '../../state.ts'\nimport type { PetSpriteProps } from '../PetSprite.tsx'\nimport { createDragStream, type DragStream } from '../drag-stream.ts'\nimport type { GameplayBus } from '../gameplay-hud.tsx'\nimport { defaultPetRendererRegistry } from './registry.ts'\nimport { Live2dVisualMount } from './live2d/Live2dVisualMount.tsx'\nimport { Frames2dVisualMount } from './Frames2dVisualMount.tsx'\nimport type { NS } from '../locales.ts'\n\n/** Dispatch one pet definition to its renderer; unknown kinds get a card. */\nexport function PetRendererSwitch(props: {\n definition: PetDefinition\n /** Current activity phase (fed to renderer visuals). */\n phase: ActivityPhase\n /** The chrome's pet interaction (affinity write-back owner). */\n onPet: () => void\n /** External drag stream (gameplay HUD shares it); created locally otherwise. */\n drag?: DragStream\n /** Gameplay coordination bus forwarded to the frames2d visual mount. */\n bus?: GameplayBus\n t: PropsLocale<typeof NS>['t']\n children?: ReactNode\n}): ReactElement {\n const renderer = props.definition.renderer ?? 'sprite2d'\n // The frames2d drag stream lives one level up: the chrome (PetSprite)\n // reports the gesture through onDraggingChange, the visual subscribes.\n const dragRef = useRef<{ id: string; stream: ReturnType<typeof createDragStream> } | null>(null)\n if (dragRef.current === null || dragRef.current.id !== props.definition.id) {\n dragRef.current = { id: props.definition.id, stream: createDragStream() }\n }\n const drag = props.drag ?? dragRef.current.stream\n if (renderer === 'sprite2d') return <>{props.children}</>\n if (renderer === 'frames2d' && defaultPetRendererRegistry.has('frames2d') && isValidElement<PetSpriteProps>(props.children)) {\n const visual = (\n <Frames2dVisualMount\n definition={props.definition}\n phase={props.phase}\n onPet={props.onPet}\n drag={drag}\n {...(props.bus === undefined ? {} : { bus: props.bus })}\n t={props.t}\n />\n )\n return cloneElement(props.children, { visual, onDraggingChange: (dragging: boolean) => drag.push(dragging) })\n }\n if (renderer === 'live2d' && defaultPetRendererRegistry.has('live2d') && isValidElement<PetSpriteProps>(props.children)) {\n const visual = (\n <Live2dVisualMount\n definition={props.definition}\n phase={props.phase}\n onPet={props.onPet}\n t={props.t}\n />\n )\n return cloneElement(props.children, { visual })\n }\n return (\n <span data-dsh-pet-renderer-fallback={renderer}>\n {props.t('pet.renderer.unavailable', { renderer })}\n </span>\n )\n}\n","/**\n * Pet gameplay — the optional manifest 'gameplay' block and its host engine.\n * The block layers an opt-in mini-game over any frames2d pet: decaying stat\n * bars, currencies, a weighted idle director, touch zones, a work loop, a\n * sleep loop, passive income and a shop (issue: miku-pet generalization).\n *\n * Discipline split matches manifest-v2: STRUCTURE is fail-closed (types,\n * ranges, references into stats/tracks); the host engine is pure — every\n * verb takes an explicit clock and rng so tests stay deterministic. Decay,\n * passive income and sleep restore are lazy-settled on read (the treats.ts\n * discipline): the host runs no timers for gameplay.\n * @module @linxin666/dsh-pet/gameplay\n */\n\n/** One roam direction the pet may walk in. */\nexport type PetRoamDirection = 'up' | 'down' | 'left' | 'right'\n\n/** Every roam direction, in roll order (equal chance each unless restricted). */\nexport const PET_ROAM_DIRECTIONS: readonly PetRoamDirection[] = ['up', 'down', 'left', 'right']\n\n/** One gameplay effect: add amount to a declared stat or a currency. */\nexport interface PetGameplayEffect {\n stat?: string\n currency?: string\n amount: number\n}\n\n/** One roll branch inside a touch zone; uncovered roll mass is a no-op. */\nexport interface PetGameplayTouchBranch {\n probability: number\n effects?: PetGameplayEffect[]\n /** Track played on hit (held for stateMs, then the renderer settles). */\n state?: string\n stateMs?: number\n /** Bubble phrase pool; one is picked on hit. */\n phrases?: string[]\n}\n\nexport interface PetGameplayTouchZone {\n name: string\n /** Vertical slice of the hit box (fractions, y0 < y1). */\n y0: number\n y1: number\n branches: PetGameplayTouchBranch[]\n}\n\nexport interface PetGameplayStatDef {\n max: number\n initial?: number\n decayPerMinute?: number\n /** Decay rate while the work mode is active (defaults to decayPerMinute). */\n workingDecayPerMinute?: number\n /** Extra decay rate while no session is active. */\n idleDecayPerMinute?: number\n}\n\nexport interface PetGameplayShopItem {\n id: string\n label: string\n /** Optional frame path (manifest-relative) shown as the item icon. */\n image?: string\n price: number\n currency: string\n effects?: PetGameplayEffect[]\n lottery?: {\n effects?: PetGameplayEffect[]\n /** Default currency the prize is paid in (tiers may override). */\n currency?: string\n tiers: { probability: number; prize: number; currency?: string }[]\n }\n}\n\n/**\n * One extra named gameplay mode beyond work/sleep (a bath, a play session…).\n * The host holds `state` while the mode is active and may restore a stat on\n * a fixed cadence — the same lazy-settle rule the sleep mode uses. A mode is\n * pure data: adding one to a manifest needs no host change.\n */\nexport interface PetGameplayModeDef {\n /** frames2d track held for as long as the mode is active. */\n state: string\n /** Action-button label (plain text); falls back to the i18n key pet.gameplay.<name>. */\n label?: string\n /** Label while the mode is active (plain text); falls back to `label`. */\n activeLabel?: string\n /** Periodic stat restore while the mode is active (omitted = no restore). */\n restore?: { stat: string; amount: number; intervalMs: number }\n}\n\n/** The validated manifest 'gameplay' block. */\nexport interface PetGameplayManifest {\n idleDirector?: {\n intervalMs: number\n maxMiss: number\n idleWeight: number\n acts: { track: string; weight: number; phrases?: string[] }[]\n }\n stats?: Record<string, PetGameplayStatDef>\n /** Click hit box inside the sprite box (fractions). */\n hitBox?: { x0: number; y0: number; x1: number; y1: number }\n touch?: {\n zones: PetGameplayTouchZone[]\n /** Plain-click effect while a touch animation holds (miku: mood +0..3). */\n clickBoost?: { stat: string; min: number; max: number }\n }\n work?: {\n state: string\n successState: string\n failState: string\n tickMs: number\n /** Hold time of the result track before the next round. */\n resultMs?: { success: number; fail: number }\n successProbability: number\n success?: { effects: PetGameplayEffect[] }\n fail?: { effects: PetGameplayEffect[] }\n }\n sleep?: {\n state: string\n wakeState?: string\n restore: { stat: string; amount: number; intervalMs: number }\n }\n /**\n * Extra named modes beyond work/sleep, keyed by a kebab mode id. Each one\n * gets its own menu button, holds its track while active and may restore a\n * stat on a cadence. 'work' and 'sleep' are reserved keys.\n */\n modes?: Record<string, PetGameplayModeDef>\n /**\n * Random roaming: on a slow interval the pet rolls whether to wander and\n * walks to a new spot on screen with `state` held for the travel time. The\n * chrome owns the motion (clamped to the viewport) and persists the resting\n * spot the way a drag does; the roll only runs while the pet is idle and no\n * mode, drag or touch animation owns it.\n */\n roam?: {\n /** frames2d track held while walking. */\n state: string\n /** Ms between roam decisions. */\n intervalMs: number\n /** Chance one decision actually walks (0, 1]. */\n probability: number\n /** Travel per roam in px (distanceMin <= distanceMax). */\n distanceMin: number\n distanceMax: number\n /** Walking speed in px per second. */\n speed: number\n /**\n * Directions the pet may walk in, rolled uniformly (equal chance each).\n * Omitted = all four. A side-view crawl reads best walking left/right, so\n * a pet may restrict the list to those two.\n */\n directions?: PetRoamDirection[]\n }\n passiveIncome?: { currency: string; amount: number; intervalMs: number }\n shop?: { state?: string; items: PetGameplayShopItem[] }\n /** Track played while the chrome reports dragging (default 'drag'). */\n dragState?: string\n /** Track played once when a drag ends (miku: standup), before settling. */\n dragEndState?: string\n}\n\n/* ------------------------------------------------------------------ *\n * Manifest parsing (fail-closed structure)\n * ------------------------------------------------------------------ */\n\nconst KEBAB = /^[a-z0-9][a-z0-9-]*$/\nconst MAX_STATS = 16\nconst MAX_ZONES = 8\nconst MAX_BRANCHES = 8\nconst MAX_ACTS = 16\nconst MAX_SHOP_ITEMS = 32\nconst MAX_LOTTERY_TIERS = 16\nconst MAX_PHRASES = 64\nconst PHRASE_MAX_LENGTH = 120\nconst MAX_MODES = 8\nconst MODE_LABEL_MAX_LENGTH = 40\nconst STAT_VALUE_MAX = 1_000_000\nconst CURRENCY_MAX = 9_999_999\n\nconst KNOWN_GAMEPLAY = new Set(['idleDirector', 'stats', 'hitBox', 'touch', 'work', 'sleep', 'modes', 'roam', 'passiveIncome', 'shop', 'dragState', 'dragEndState'])\nconst KNOWN_STAT = new Set(['max', 'initial', 'decayPerMinute', 'workingDecayPerMinute', 'idleDecayPerMinute'])\nconst KNOWN_ZONE = new Set(['name', 'y0', 'y1', 'branches'])\nconst KNOWN_TOUCH = new Set(['zones', 'clickBoost'])\nconst KNOWN_BRANCH = new Set(['probability', 'effects', 'state', 'stateMs', 'phrases'])\nconst KNOWN_EFFECT = new Set(['stat', 'currency', 'amount'])\nconst KNOWN_WORK = new Set(['state', 'successState', 'failState', 'tickMs', 'resultMs', 'successProbability', 'success', 'fail'])\nconst KNOWN_SLEEP = new Set(['state', 'wakeState', 'restore'])\nconst KNOWN_MODE = new Set(['state', 'label', 'activeLabel', 'restore'])\nconst KNOWN_ROAM = new Set(['state', 'intervalMs', 'probability', 'distanceMin', 'distanceMax', 'speed', 'directions'])\nconst KNOWN_RESTORE = new Set(['stat', 'amount', 'intervalMs'])\nconst KNOWN_SHOP_ITEM = new Set(['id', 'label', 'image', 'price', 'currency', 'effects', 'lottery'])\nconst KNOWN_LOTTERY = new Set(['effects', 'currency', 'tiers'])\nconst KNOWN_IDLE_DIRECTOR = new Set(['intervalMs', 'maxMiss', 'idleWeight', 'acts'])\nconst KNOWN_ACT = new Set(['track', 'weight', 'phrases'])\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction unknownKeys(source: Record<string, unknown>, known: Set<string>): string[] {\n return Object.keys(source).filter(key => !known.has(key))\n}\n\nexport interface GameplayParseHooks {\n /** State names the renderer can play (frames2d track ids). */\n stateNames: ReadonlySet<string>\n error: (message: string) => void\n}\n\nfunction validName(name: unknown, max = 32): name is string {\n return typeof name === 'string' && name.length <= max && KEBAB.test(name)\n}\n\nfunction intIn(value: unknown, min: number, max: number): value is number {\n return typeof value === 'number' && Number.isInteger(value) && value >= min && value <= max\n}\n\nfunction numIn(value: unknown, min: number, max: number): value is number {\n return typeof value === 'number' && Number.isFinite(value) && value >= min && value <= max\n}\n\nfunction parseEffects(raw: unknown, field: string, stats: Record<string, PetGameplayStatDef>, hooks: GameplayParseHooks): PetGameplayEffect[] | undefined {\n if (raw === undefined) return undefined\n if (!Array.isArray(raw) || raw.length === 0) {\n hooks.error(field + ' must be a non-empty array of effects')\n return undefined\n }\n const effects: PetGameplayEffect[] = []\n for (const entry of raw) {\n if (!isRecord(entry)) {\n hooks.error(field + ': every effect must be an object')\n continue\n }\n const extra = unknownKeys(entry, KNOWN_EFFECT)\n if (extra.length > 0) hooks.error(field + ': unknown effect field(s) ' + extra.map(k => JSON.stringify(k)).join(', '))\n const hasStat = typeof entry.stat === 'string'\n const hasCurrency = typeof entry.currency === 'string'\n if (hasStat === hasCurrency) {\n hooks.error(field + ': an effect needs exactly one of stat or currency')\n continue\n }\n if (!intIn(entry.amount, -STAT_VALUE_MAX, STAT_VALUE_MAX) || entry.amount === 0) {\n hooks.error(field + ': effect amount must be a non-zero integer within ±' + STAT_VALUE_MAX)\n continue\n }\n if (hasStat && stats[entry.stat as string] === undefined) {\n hooks.error(field + ': effect references undeclared stat ' + JSON.stringify(entry.stat))\n continue\n }\n if (hasCurrency && !validName(entry.currency, 24)) {\n hooks.error(field + ': effect currency must be a kebab id')\n continue\n }\n effects.push({\n ...(hasStat ? { stat: entry.stat as string } : {}),\n ...(hasCurrency ? { currency: entry.currency as string } : {}),\n amount: entry.amount as number,\n })\n }\n return effects.length === 0 ? undefined : effects\n}\n\nfunction parsePhrases(raw: unknown, field: string, hooks: GameplayParseHooks): string[] | undefined {\n if (raw === undefined) return undefined\n if (!Array.isArray(raw) || raw.length === 0 || raw.length > MAX_PHRASES\n || raw.some(line => typeof line !== 'string' || line.trim() === '' || line.length > PHRASE_MAX_LENGTH)) {\n hooks.error(field + ' must be 1..' + MAX_PHRASES + ' non-empty lines of at most ' + PHRASE_MAX_LENGTH + ' chars')\n return undefined\n }\n return raw as string[]\n}\n\nfunction parseStateRef(raw: unknown, field: string, hooks: GameplayParseHooks): string | undefined {\n if (raw === undefined) return undefined\n if (typeof raw !== 'string' || !hooks.stateNames.has(raw)) {\n hooks.error(field + ' must name a declared frames2d track')\n return undefined\n }\n return raw\n}\n\n/** Parse one mode restore rule \"{ stat (declared), amount, intervalMs }\". */\nfunction parseModeRestore(\n raw: unknown,\n field: string,\n stats: Record<string, PetGameplayStatDef>,\n fail: (message: string) => void,\n): { stat: string; amount: number; intervalMs: number } | undefined {\n if (!isRecord(raw)) {\n fail(field + ' must be an object { stat, amount, intervalMs }')\n return undefined\n }\n const extra = unknownKeys(raw, KNOWN_RESTORE)\n if (extra.length > 0) fail(field + ': unknown field(s) ' + extra.map(k => JSON.stringify(k)).join(', '))\n const stat = typeof raw.stat === 'string' && stats[raw.stat] !== undefined ? raw.stat : undefined\n if (stat === undefined) fail(field + '.stat must reference a declared stat')\n if (!intIn(raw.amount, 1, 1000)) fail(field + '.amount must be an integer in [1, 1000]')\n if (!intIn(raw.intervalMs, 1000, 600_000)) fail(field + '.intervalMs must be an integer in [1000, 600000]')\n if (stat === undefined || !intIn(raw.amount, 1, 1000) || !intIn(raw.intervalMs, 1000, 600_000)) return undefined\n return { stat, amount: raw.amount, intervalMs: raw.intervalMs }\n}\n\n/**\n * Validate the manifest 'gameplay' block (fail-closed). Only frames2d pets\n * may declare gameplay today: every state reference checks against the\n * declared track names.\n */\nexport function parseGameplayManifest(raw: unknown, hooks: GameplayParseHooks): PetGameplayManifest | undefined {\n const error = (message: string): void => hooks.error(message)\n if (!isRecord(raw)) {\n error('gameplay must be an object')\n return undefined\n }\n const extra = unknownKeys(raw, KNOWN_GAMEPLAY)\n if (extra.length > 0) error('gameplay: unknown field(s) ' + extra.map(k => JSON.stringify(k)).join(', '))\n let failed = false\n const fail = (message: string): void => { failed = true; error(message) }\n\n // --- stats (parsed first: effects reference them) ---\n const stats: Record<string, PetGameplayStatDef> = {}\n if (raw.stats !== undefined) {\n if (!isRecord(raw.stats)) fail('gameplay.stats must be an object keyed by stat id')\n else {\n const entries = Object.entries(raw.stats)\n if (entries.length > MAX_STATS) fail('gameplay.stats declares too many stats (max ' + MAX_STATS + ')')\n for (const [name, value] of entries) {\n if (!validName(name, 24)) {\n fail('gameplay.stats: invalid stat id ' + JSON.stringify(name))\n continue\n }\n if (!isRecord(value)) {\n fail('gameplay.stats.' + name + ' must be an object')\n continue\n }\n const statExtra = unknownKeys(value, KNOWN_STAT)\n if (statExtra.length > 0) fail('gameplay.stats.' + name + ': unknown field(s) ' + statExtra.map(k => JSON.stringify(k)).join(', '))\n if (!intIn(value.max, 1, STAT_VALUE_MAX)) {\n fail('gameplay.stats.' + name + '.max must be an integer in [1, ' + STAT_VALUE_MAX + ']')\n continue\n }\n const def: PetGameplayStatDef = { max: value.max }\n if (value.initial !== undefined) {\n if (!numIn(value.initial, 0, value.max)) fail('gameplay.stats.' + name + '.initial must be within [0, max]')\n else def.initial = value.initial\n }\n for (const key of ['decayPerMinute', 'workingDecayPerMinute', 'idleDecayPerMinute'] as const) {\n if (value[key] !== undefined) {\n if (!numIn(value[key], 0, 1000)) fail('gameplay.stats.' + name + '.' + key + ' must be a number in [0, 1000]')\n else def[key] = value[key] as number\n }\n }\n stats[name] = def\n }\n }\n }\n\n const block: PetGameplayManifest = {}\n if (Object.keys(stats).length > 0) block.stats = stats\n\n // --- idle director ---\n if (raw.idleDirector !== undefined) {\n if (!isRecord(raw.idleDirector) || !Array.isArray(raw.idleDirector.acts)) {\n fail('gameplay.idleDirector must be an object with an acts array')\n } else {\n const d = raw.idleDirector as Record<string, unknown> & { acts: unknown[] }\n const dExtra = unknownKeys(d, KNOWN_IDLE_DIRECTOR)\n if (dExtra.length > 0) fail('gameplay.idleDirector: unknown field(s) ' + dExtra.map(k => JSON.stringify(k)).join(', '))\n if (d.intervalMs !== undefined && !intIn(d.intervalMs, 1000, 60_000)) fail('gameplay.idleDirector.intervalMs must be an integer in [1000, 60000]')\n if (d.maxMiss !== undefined && !intIn(d.maxMiss, 0, 10)) fail('gameplay.idleDirector.maxMiss must be an integer in [0, 10]')\n if (d.idleWeight !== undefined && !intIn(d.idleWeight, 0, 10_000)) fail('gameplay.idleDirector.idleWeight must be an integer in [0, 10000]')\n if (d.acts.length === 0 || d.acts.length > MAX_ACTS) fail('gameplay.idleDirector.acts must declare 1..' + MAX_ACTS + ' acts')\n const acts: { track: string; weight: number; phrases?: string[] }[] = []\n for (const act of d.acts as unknown[]) {\n if (!isRecord(act) || !intIn(act.weight, 1, 10_000)) {\n fail('gameplay.idleDirector.acts entries need a weight integer in [1, 10000]')\n continue\n }\n const aExtra = unknownKeys(act, KNOWN_ACT)\n if (aExtra.length > 0) fail('gameplay.idleDirector.acts: unknown field(s) ' + aExtra.map(k => JSON.stringify(k)).join(', '))\n const track = parseStateRef(act.track, 'gameplay.idleDirector.acts.track', hooks)\n if (track === undefined) continue\n const entry: { track: string; weight: number; phrases?: string[] } = { track, weight: act.weight }\n const phrases = parsePhrases(act.phrases, 'gameplay.idleDirector.acts.phrases', hooks)\n if (phrases !== undefined) entry.phrases = phrases\n acts.push(entry)\n }\n if (acts.length > 0) {\n block.idleDirector = {\n intervalMs: intIn(d.intervalMs, 1000, 60_000) ? d.intervalMs as number : 5000,\n maxMiss: intIn(d.maxMiss, 0, 10) ? d.maxMiss as number : 2,\n idleWeight: intIn(d.idleWeight, 0, 10_000) ? d.idleWeight as number : 0,\n acts,\n }\n }\n }\n }\n\n // --- hit box ---\n if (raw.hitBox !== undefined) {\n const b = raw.hitBox\n if (!isRecord(b) || !numIn(b.x0, 0, 1) || !numIn(b.x1, 0, 1) || !numIn(b.y0, 0, 1) || !numIn(b.y1, 0, 1)\n || !(b.x0 < b.x1) || !(b.y0 < b.y1)) {\n fail('gameplay.hitBox must be { x0, y0, x1, y1 } fractions with x0 < x1 and y0 < y1')\n } else {\n block.hitBox = { x0: b.x0, y0: b.y0, x1: b.x1, y1: b.y1 }\n }\n }\n\n // --- touch zones ---\n if (raw.touch !== undefined) {\n if (!isRecord(raw.touch) || !Array.isArray(raw.touch.zones)) {\n fail('gameplay.touch must be an object with a zones array')\n } else {\n const tExtra = unknownKeys(raw.touch, KNOWN_TOUCH)\n if (tExtra.length > 0) fail('gameplay.touch: unknown field(s) ' + tExtra.map(k => JSON.stringify(k)).join(', '))\n let clickBoost: { stat: string; min: number; max: number } | undefined\n if (raw.touch.clickBoost !== undefined) {\n const cb = raw.touch.clickBoost\n if (!isRecord(cb) || typeof cb.stat !== 'string' || stats[cb.stat] === undefined\n || !intIn(cb.min, 0, 1000) || !intIn(cb.max, 0, 1000) || (cb.min as number) > (cb.max as number)) {\n fail('gameplay.touch.clickBoost must be { stat (declared), min, max } integers with 0 <= min <= max <= 1000')\n } else clickBoost = { stat: cb.stat, min: cb.min, max: cb.max }\n }\n const zones: PetGameplayTouchZone[] = []\n if (raw.touch.zones.length === 0 || raw.touch.zones.length > MAX_ZONES) fail('gameplay.touch.zones must declare 1..' + MAX_ZONES + ' zones')\n for (const zoneRaw of raw.touch.zones as unknown[]) {\n if (!isRecord(zoneRaw) || !validName(zoneRaw.name) || !numIn(zoneRaw.y0, 0, 1) || !numIn(zoneRaw.y1, 0, 1) || !(zoneRaw.y0 < zoneRaw.y1)) {\n fail('gameplay.touch.zones entries need a kebab name and 0 <= y0 < y1 <= 1')\n continue\n }\n const zExtra = unknownKeys(zoneRaw, KNOWN_ZONE)\n if (zExtra.length > 0) fail('gameplay.touch.' + zoneRaw.name + ': unknown field(s) ' + zExtra.map(k => JSON.stringify(k)).join(', '))\n if (!Array.isArray(zoneRaw.branches) || zoneRaw.branches.length === 0 || zoneRaw.branches.length > MAX_BRANCHES) {\n fail('gameplay.touch.' + zoneRaw.name + '.branches must declare 1..' + MAX_BRANCHES + ' branches')\n continue\n }\n let probabilitySum = 0\n const branches: PetGameplayTouchBranch[] = []\n for (const branchRaw of zoneRaw.branches as unknown[]) {\n if (!isRecord(branchRaw) || !numIn(branchRaw.probability, 0, 1) || branchRaw.probability === 0) {\n fail('gameplay.touch.' + zoneRaw.name + '.branches entries need a probability in (0, 1]')\n continue\n }\n const bExtra = unknownKeys(branchRaw, KNOWN_BRANCH)\n if (bExtra.length > 0) fail('gameplay.touch.' + zoneRaw.name + ': unknown branch field(s) ' + bExtra.map(k => JSON.stringify(k)).join(', '))\n probabilitySum += branchRaw.probability\n const branch: PetGameplayTouchBranch = { probability: branchRaw.probability }\n const effects = parseEffects(branchRaw.effects, 'gameplay.touch.' + zoneRaw.name + '.effects', stats, hooks)\n if (effects !== undefined) branch.effects = effects\n const state = parseStateRef(branchRaw.state, 'gameplay.touch.' + zoneRaw.name + '.state', hooks)\n if (state !== undefined) branch.state = state\n if (branchRaw.stateMs !== undefined) {\n if (!intIn(branchRaw.stateMs, 200, 10_000)) fail('gameplay.touch.' + zoneRaw.name + '.stateMs must be an integer in [200, 10000]')\n else branch.stateMs = branchRaw.stateMs\n }\n const phrases = parsePhrases(branchRaw.phrases, 'gameplay.touch.' + zoneRaw.name + '.phrases', hooks)\n if (phrases !== undefined) branch.phrases = phrases\n branches.push(branch)\n }\n if (probabilitySum > 1 + 1e-9) fail('gameplay.touch.' + zoneRaw.name + ': branch probabilities must sum to at most 1')\n if (branches.length > 0) zones.push({ name: zoneRaw.name, y0: zoneRaw.y0, y1: zoneRaw.y1, branches })\n }\n if (zones.length > 0 || clickBoost !== undefined) block.touch = { zones, ...(clickBoost === undefined ? {} : { clickBoost }) }\n }\n }\n\n // --- work ---\n if (raw.work !== undefined) {\n const w = raw.work\n if (!isRecord(w)) fail('gameplay.work must be an object')\n else {\n const wExtra = unknownKeys(w, KNOWN_WORK)\n if (wExtra.length > 0) fail('gameplay.work: unknown field(s) ' + wExtra.map(k => JSON.stringify(k)).join(', '))\n const state = parseStateRef(w.state, 'gameplay.work.state', hooks)\n const successState = parseStateRef(w.successState, 'gameplay.work.successState', hooks)\n const failState = parseStateRef(w.failState, 'gameplay.work.failState', hooks)\n if (!intIn(w.tickMs, 1000, 60_000)) fail('gameplay.work.tickMs must be an integer in [1000, 60000]')\n if (!numIn(w.successProbability, 0, 1)) fail('gameplay.work.successProbability must be a number in [0, 1]')\n if (state !== undefined && successState !== undefined && failState !== undefined\n && intIn(w.tickMs, 1000, 60_000) && numIn(w.successProbability, 0, 1)) {\n const work: NonNullable<PetGameplayManifest['work']> = {\n state, successState, failState,\n tickMs: w.tickMs,\n successProbability: w.successProbability,\n }\n if (w.resultMs !== undefined) {\n if (!isRecord(w.resultMs) || !intIn(w.resultMs.success, 200, 10_000) || !intIn(w.resultMs.fail, 200, 10_000)) {\n fail('gameplay.work.resultMs must be { success, fail } integers in [200, 10000]')\n } else work.resultMs = { success: w.resultMs.success, fail: w.resultMs.fail }\n }\n for (const key of ['success', 'fail'] as const) {\n if (w[key] !== undefined) {\n if (!isRecord(w[key])) fail('gameplay.work.' + key + ' must be an object { effects }')\n else {\n const effects = parseEffects((w[key] as Record<string, unknown>).effects, 'gameplay.work.' + key + '.effects', stats, hooks)\n if (effects !== undefined) work[key] = { effects }\n }\n }\n }\n block.work = work\n }\n }\n }\n\n // --- sleep ---\n if (raw.sleep !== undefined) {\n const s = raw.sleep\n if (!isRecord(s) || !isRecord(s.restore)) fail('gameplay.sleep must be an object with a restore block')\n else {\n const sExtra = unknownKeys(s, KNOWN_SLEEP)\n if (sExtra.length > 0) fail('gameplay.sleep: unknown field(s) ' + sExtra.map(k => JSON.stringify(k)).join(', '))\n const state = parseStateRef(s.state, 'gameplay.sleep.state', hooks)\n const wakeState = parseStateRef(s.wakeState, 'gameplay.sleep.wakeState', hooks)\n const restore = parseModeRestore(s.restore, 'gameplay.sleep.restore', stats, fail)\n if (state !== undefined && restore !== undefined) {\n block.sleep = {\n state,\n ...(wakeState === undefined ? {} : { wakeState }),\n restore,\n }\n }\n }\n }\n\n // --- extra modes (bath and friends) ---\n if (raw.modes !== undefined) {\n if (!isRecord(raw.modes)) fail('gameplay.modes must be an object keyed by mode id')\n else {\n const entries = Object.entries(raw.modes)\n if (entries.length > MAX_MODES) fail('gameplay.modes declares too many modes (max ' + MAX_MODES + ')')\n const modes: Record<string, PetGameplayModeDef> = {}\n for (const [name, value] of entries) {\n if (!validName(name, 24) || name === 'work' || name === 'sleep') {\n fail('gameplay.modes: invalid mode id ' + JSON.stringify(name) + ' (kebab, and not the reserved work/sleep)')\n continue\n }\n if (!isRecord(value)) {\n fail('gameplay.modes.' + name + ' must be an object')\n continue\n }\n const mExtra = unknownKeys(value, KNOWN_MODE)\n if (mExtra.length > 0) fail('gameplay.modes.' + name + ': unknown field(s) ' + mExtra.map(k => JSON.stringify(k)).join(', '))\n const state = parseStateRef(value.state, 'gameplay.modes.' + name + '.state', hooks)\n let usable = state !== undefined\n let label: string | undefined\n if (value.label !== undefined) {\n if (typeof value.label !== 'string' || value.label.trim() === '' || value.label.length > MODE_LABEL_MAX_LENGTH) {\n fail('gameplay.modes.' + name + '.label must be a non-empty string of at most ' + MODE_LABEL_MAX_LENGTH + ' chars')\n usable = false\n } else label = value.label.trim()\n }\n let activeLabel: string | undefined\n if (value.activeLabel !== undefined) {\n if (typeof value.activeLabel !== 'string' || value.activeLabel.trim() === '' || value.activeLabel.length > MODE_LABEL_MAX_LENGTH) {\n fail('gameplay.modes.' + name + '.activeLabel must be a non-empty string of at most ' + MODE_LABEL_MAX_LENGTH + ' chars')\n usable = false\n } else activeLabel = value.activeLabel.trim()\n }\n const restore = value.restore === undefined ? undefined : parseModeRestore(value.restore, 'gameplay.modes.' + name + '.restore', stats, fail)\n if (value.restore !== undefined && restore === undefined) usable = false\n if (usable && state !== undefined) {\n modes[name] = {\n state,\n ...(label === undefined ? {} : { label }),\n ...(activeLabel === undefined ? {} : { activeLabel }),\n ...(restore === undefined ? {} : { restore }),\n }\n }\n }\n if (Object.keys(modes).length > 0) block.modes = modes\n }\n }\n\n // --- random roaming ---\n if (raw.roam !== undefined) {\n const rm = raw.roam\n if (!isRecord(rm)) fail('gameplay.roam must be an object')\n else {\n const rExtra = unknownKeys(rm, KNOWN_ROAM)\n if (rExtra.length > 0) fail('gameplay.roam: unknown field(s) ' + rExtra.map(k => JSON.stringify(k)).join(', '))\n const state = parseStateRef(rm.state, 'gameplay.roam.state', hooks)\n if (!intIn(rm.intervalMs, 1000, 3_600_000)) fail('gameplay.roam.intervalMs must be an integer in [1000, 3600000]')\n if (!numIn(rm.probability, 0, 1) || rm.probability === 0) fail('gameplay.roam.probability must be a number in (0, 1]')\n if (!intIn(rm.distanceMin, 1, 2000)) fail('gameplay.roam.distanceMin must be an integer in [1, 2000]')\n if (!intIn(rm.distanceMax, 1, 2000)) fail('gameplay.roam.distanceMax must be an integer in [1, 2000]')\n if (intIn(rm.distanceMin, 1, 2000) && intIn(rm.distanceMax, 1, 2000) && rm.distanceMin > rm.distanceMax) {\n fail('gameplay.roam.distanceMin must not exceed distanceMax')\n }\n if (!intIn(rm.speed, 1, 2000)) fail('gameplay.roam.speed must be an integer in [1, 2000] (px per second)')\n let directions: PetRoamDirection[] | undefined\n if (rm.directions !== undefined) {\n if (!Array.isArray(rm.directions) || rm.directions.length === 0) {\n fail('gameplay.roam.directions must be a non-empty array of up, down, left, right')\n } else {\n const picked: PetRoamDirection[] = []\n for (const entry of rm.directions as unknown[]) {\n if (typeof entry !== 'string' || !PET_ROAM_DIRECTIONS.includes(entry as PetRoamDirection)) {\n fail('gameplay.roam.directions entries must be up, down, left or right')\n picked.length = 0\n break\n }\n if (picked.includes(entry as PetRoamDirection)) {\n fail('gameplay.roam.directions must not repeat ' + entry)\n picked.length = 0\n break\n }\n picked.push(entry as PetRoamDirection)\n }\n if (picked.length > 0) directions = picked\n }\n }\n // The guards are repeated inline: tsc only narrows the unknown fields\n // through a call in the condition itself.\n if (state !== undefined\n && intIn(rm.intervalMs, 1000, 3_600_000)\n && numIn(rm.probability, 0, 1) && rm.probability !== 0\n && intIn(rm.distanceMin, 1, 2000)\n && intIn(rm.distanceMax, 1, 2000)\n && rm.distanceMin <= rm.distanceMax\n && intIn(rm.speed, 1, 2000)) {\n block.roam = {\n state,\n intervalMs: rm.intervalMs,\n probability: rm.probability,\n distanceMin: rm.distanceMin,\n distanceMax: rm.distanceMax,\n speed: rm.speed,\n ...(directions === undefined ? {} : { directions }),\n }\n }\n }\n }\n\n // --- passive income ---\n if (raw.passiveIncome !== undefined) {\n const p = raw.passiveIncome\n if (!isRecord(p) || !validName(p.currency, 24) || !intIn(p.amount, 1, 10_000) || !intIn(p.intervalMs, 1000, 86_400_000)) {\n fail('gameplay.passiveIncome must be { currency (kebab), amount 1..10000, intervalMs 1000..86400000 }')\n } else {\n block.passiveIncome = { currency: p.currency, amount: p.amount, intervalMs: p.intervalMs }\n }\n }\n\n // --- shop ---\n if (raw.shop !== undefined) {\n const s = raw.shop\n if (!isRecord(s) || !Array.isArray(s.items) || s.items.length === 0 || s.items.length > MAX_SHOP_ITEMS) {\n fail('gameplay.shop must be an object with 1..' + MAX_SHOP_ITEMS + ' items')\n } else {\n const shopState = parseStateRef(s.state, 'gameplay.shop.state', hooks)\n const items: PetGameplayShopItem[] = []\n const seen = new Set<string>()\n for (const itemRaw of s.items as unknown[]) {\n if (!isRecord(itemRaw) || !validName(itemRaw.id, 24)) {\n fail('gameplay.shop.items entries need a kebab id')\n continue\n }\n if (seen.has(itemRaw.id)) {\n fail('gameplay.shop: duplicate item id ' + JSON.stringify(itemRaw.id))\n continue\n }\n seen.add(itemRaw.id)\n const iExtra = unknownKeys(itemRaw, KNOWN_SHOP_ITEM)\n if (iExtra.length > 0) fail('gameplay.shop.' + itemRaw.id + ': unknown field(s) ' + iExtra.map(k => JSON.stringify(k)).join(', '))\n if (typeof itemRaw.label !== 'string' || itemRaw.label.trim() === '' || itemRaw.label.length > 80) {\n fail('gameplay.shop.' + itemRaw.id + '.label must be a non-empty string of at most 80 chars')\n continue\n }\n if (!intIn(itemRaw.price, 1, 1_000_000)) {\n fail('gameplay.shop.' + itemRaw.id + '.price must be an integer in [1, 1000000]')\n continue\n }\n if (!validName(itemRaw.currency, 24)) {\n fail('gameplay.shop.' + itemRaw.id + '.currency must be a kebab id')\n continue\n }\n const item: PetGameplayShopItem = {\n id: itemRaw.id,\n label: itemRaw.label.trim(),\n price: itemRaw.price,\n currency: itemRaw.currency,\n }\n if (itemRaw.image !== undefined) {\n if (typeof itemRaw.image !== 'string' || itemRaw.image.includes('..') || itemRaw.image.includes('\\\\') || itemRaw.image.startsWith('/')) {\n fail('gameplay.shop.' + itemRaw.id + '.image must be a safe manifest-relative frame path')\n } else item.image = itemRaw.image\n }\n const effects = parseEffects(itemRaw.effects, 'gameplay.shop.' + itemRaw.id + '.effects', stats, hooks)\n if (effects !== undefined) item.effects = effects\n if (itemRaw.lottery !== undefined) {\n const l = itemRaw.lottery\n if (!isRecord(l) || !Array.isArray(l.tiers) || l.tiers.length === 0 || l.tiers.length > MAX_LOTTERY_TIERS) {\n fail('gameplay.shop.' + itemRaw.id + '.lottery needs 1..' + MAX_LOTTERY_TIERS + ' tiers')\n } else {\n const lExtra = unknownKeys(l, KNOWN_LOTTERY)\n if (lExtra.length > 0) fail('gameplay.shop.' + itemRaw.id + '.lottery: unknown field(s) ' + lExtra.map(k => JSON.stringify(k)).join(', '))\n if (l.currency !== undefined && !validName(l.currency, 24)) fail('gameplay.shop.' + itemRaw.id + '.lottery.currency must be a kebab id')\n let tierSum = 0\n const tiers: { probability: number; prize: number; currency?: string }[] = []\n for (const tierRaw of l.tiers as unknown[]) {\n if (!isRecord(tierRaw) || !numIn(tierRaw.probability, 0, 1) || tierRaw.probability === 0\n || !intIn(tierRaw.prize, 0, 1_000_000_000)) {\n fail('gameplay.shop.' + itemRaw.id + '.lottery.tiers entries need probability (0,1] and prize 0..1e9')\n continue\n }\n tierSum += tierRaw.probability\n const tier: { probability: number; prize: number; currency?: string } = {\n probability: tierRaw.probability,\n prize: tierRaw.prize,\n }\n if (tierRaw.currency !== undefined) {\n if (!validName(tierRaw.currency, 24)) fail('gameplay.shop.' + itemRaw.id + '.lottery tier currency must be a kebab id')\n else tier.currency = tierRaw.currency\n }\n tiers.push(tier)\n }\n if (tierSum > 1 + 1e-9) fail('gameplay.shop.' + itemRaw.id + '.lottery tier probabilities must sum to at most 1')\n if (tiers.length > 0) {\n const lotteryEffects = parseEffects(l.effects, 'gameplay.shop.' + itemRaw.id + '.lottery.effects', stats, hooks)\n item.lottery = {\n tiers,\n ...(lotteryEffects === undefined ? {} : { effects: lotteryEffects }),\n ...(validName(l.currency, 24) ? { currency: l.currency } : {}),\n }\n }\n }\n }\n if (item.effects === undefined && item.lottery === undefined) {\n fail('gameplay.shop.' + itemRaw.id + ' needs effects or a lottery')\n continue\n }\n items.push(item)\n }\n if (items.length > 0) block.shop = { ...(shopState === undefined ? {} : { state: shopState }), items }\n }\n }\n\n // --- drag state ---\n if (raw.dragState !== undefined) {\n const state = parseStateRef(raw.dragState, 'gameplay.dragState', hooks)\n if (state !== undefined) block.dragState = state\n }\n if (raw.dragEndState !== undefined) {\n const state = parseStateRef(raw.dragEndState, 'gameplay.dragEndState', hooks)\n if (state !== undefined) block.dragEndState = state\n }\n\n return failed ? undefined : block\n}\n\n/* ------------------------------------------------------------------ *\n * Host engine (pure; clock and rng injected)\n * ------------------------------------------------------------------ */\n\n/** Persisted per-pet gameplay state (pet.json 'gameplay' map values). */\nexport interface PetGameplayState {\n stats: Record<string, number>\n currencies: Record<string, number>\n /** Active gameplay mode id ('work' | 'sleep' | a declared extra mode) or null. */\n mode: string | null\n /** Epoch ms of the last lazy settle. */\n settledAt: number\n /** Accumulated remainder ms towards the next passive income tick. */\n incomeCarryMs?: number\n /** Accumulated remainder ms towards the next mode restore tick. */\n restoreCarryMs?: number\n}\n\n/**\n * One declared extra mode, by OWN key only. A plain `modes[id]` lookup also\n * answers for Object.prototype members ('constructor', 'toString', …), which\n * would let a crafted mode id pass the \"is it declared?\" test.\n */\nfunction declaredModeOf(manifest: PetGameplayManifest, mode: string): PetGameplayModeDef | undefined {\n const modes = manifest.modes\n if (modes === undefined || !Object.prototype.hasOwnProperty.call(modes, mode)) return undefined\n return modes[mode]\n}\n\n/** Every mode the menu offers, in manifest order (sleep first, then extras). */\nexport function declaredModes(manifest: PetGameplayManifest): string[] {\n return [\n ...(manifest.sleep === undefined ? [] : ['sleep']),\n ...Object.keys(manifest.modes ?? {}),\n ]\n}\n\n/**\n * The frames2d track one active mode holds. 'work' is owned by the work loop\n * (its state, result and fallback are its own), so it resolves to undefined.\n */\nexport function modeStateOf(manifest: PetGameplayManifest, mode: string): string | undefined {\n if (mode === 'sleep') return manifest.sleep?.state\n if (mode === 'work') return manifest.work?.state\n return declaredModeOf(manifest, mode)?.state\n}\n\n/** The restore rule of one active mode, when it declares one. */\nexport function modeRestoreOf(\n manifest: PetGameplayManifest,\n mode: string | null,\n): { stat: string; amount: number; intervalMs: number } | undefined {\n if (mode === null) return undefined\n if (mode === 'sleep') return manifest.sleep?.restore\n if (mode === 'work') return undefined\n return declaredModeOf(manifest, mode)?.restore\n}\n\n/** Whether the manifest still declares this gameplay mode id. */\nexport function isDeclaredMode(manifest: PetGameplayManifest, mode: string): boolean {\n if (mode === 'work') return manifest.work !== undefined\n if (mode === 'sleep') return manifest.sleep !== undefined\n return declaredModeOf(manifest, mode) !== undefined\n}\n\n/** Fresh state for one pet: stats at their initial (default max), no currency. */\nexport function initialGameplayState(manifest: PetGameplayManifest, now: number): PetGameplayState {\n const stats: Record<string, number> = {}\n for (const [name, def] of Object.entries(manifest.stats ?? {})) {\n stats[name] = def.initial ?? def.max\n }\n return { stats, currencies: {}, mode: null, settledAt: now }\n}\n\n/** Clamp one stat value into [0, max]; currencies into [0, CURRENCY_MAX]. */\nexport function clampGameplay(state: PetGameplayState, manifest: PetGameplayManifest): void {\n for (const [name, def] of Object.entries(manifest.stats ?? {})) {\n const value = state.stats[name]\n if (value === undefined) state.stats[name] = def.initial ?? def.max\n else state.stats[name] = Math.min(def.max, Math.max(0, value))\n }\n for (const [name, value] of Object.entries(state.currencies)) {\n state.currencies[name] = Math.min(CURRENCY_MAX, Math.max(0, Math.floor(value)))\n }\n}\n\n/**\n * Lazy settle: apply stat decay, passive income and the active mode's restore\n * rule (sleep restores energy, a declared extra mode restores whatever it\n * declares) for the elapsed wall time since the last settle. Mirrors the\n * treats.ts discipline (no host timers; read paths settle). Returns whether\n * anything changed.\n */\nexport function settleGameplay(\n state: PetGameplayState,\n manifest: PetGameplayManifest,\n now: number,\n options: { sessionActive: boolean },\n): boolean {\n const elapsedMs = now - state.settledAt\n if (elapsedMs <= 0) return false\n const minutes = elapsedMs / 60_000\n let changed = false\n for (const [name, def] of Object.entries(manifest.stats ?? {})) {\n const current = state.stats[name]\n if (current === undefined || current <= 0) continue\n let rate = def.decayPerMinute ?? 0\n if (state.mode === 'work' && def.workingDecayPerMinute !== undefined) rate = def.workingDecayPerMinute\n if (!options.sessionActive) rate += def.idleDecayPerMinute ?? 0\n if (rate <= 0) continue\n const next = Math.max(0, current - rate * minutes)\n if (next !== current) {\n state.stats[name] = next\n changed = true\n }\n }\n if (manifest.passiveIncome !== undefined) {\n const incomeElapsed = elapsedMs + (state.incomeCarryMs ?? 0)\n const interval = manifest.passiveIncome.intervalMs\n const ticks = Math.floor(incomeElapsed / interval)\n state.incomeCarryMs = incomeElapsed % interval\n if (ticks > 0) {\n const currency = manifest.passiveIncome.currency\n state.currencies[currency] = (state.currencies[currency] ?? 0) + ticks * manifest.passiveIncome.amount\n changed = true\n }\n }\n const restore = modeRestoreOf(manifest, state.mode)\n if (restore !== undefined) {\n const restoreElapsed = elapsedMs + (state.restoreCarryMs ?? 0)\n const interval = restore.intervalMs\n const ticks = Math.floor(restoreElapsed / interval)\n state.restoreCarryMs = restoreElapsed % interval\n if (ticks > 0) {\n state.stats[restore.stat] = (state.stats[restore.stat] ?? 0) + ticks * restore.amount\n changed = true\n }\n } else {\n state.restoreCarryMs = 0\n }\n state.settledAt = now\n clampGameplay(state, manifest)\n return changed\n}\n\n/** Apply one effect vector (touch/work/shop), clamped. */\nexport function applyGameplayEffects(state: PetGameplayState, manifest: PetGameplayManifest, effects: readonly PetGameplayEffect[]): void {\n for (const effect of effects) {\n if (effect.stat !== undefined) {\n state.stats[effect.stat] = (state.stats[effect.stat] ?? 0) + effect.amount\n } else if (effect.currency !== undefined) {\n state.currencies[effect.currency] = (state.currencies[effect.currency] ?? 0) + effect.amount\n }\n }\n clampGameplay(state, manifest)\n}\n\n/** Roll one touch zone branch; undefined when the roll lands in no-op mass. */\nexport function rollTouchBranch(zone: PetGameplayTouchZone, rng: () => number): PetGameplayTouchBranch | undefined {\n const roll = rng()\n let acc = 0\n for (const branch of zone.branches) {\n acc += branch.probability\n if (roll < acc) return branch\n }\n return undefined\n}\n\n/** Roll one work tick outcome. */\nexport function rollWorkOutcome(work: NonNullable<PetGameplayManifest['work']>, rng: () => number): 'success' | 'fail' {\n return rng() < work.successProbability ? 'success' : 'fail'\n}\n\n/** Draw one lottery prize tier; uncovered mass falls through to the last tier. */\nexport function drawLotteryTier(\n lottery: NonNullable<PetGameplayShopItem['lottery']>,\n rng: () => number,\n): { probability: number; prize: number; currency?: string } {\n const roll = rng()\n let acc = 0\n for (const tier of lottery.tiers) {\n acc += tier.probability\n if (roll < acc) return tier\n }\n return lottery.tiers[lottery.tiers.length - 1]!\n}\n\n/** The zone one normalized hit-box point lands in, if any. */\nexport function touchZoneAt(touch: { zones: PetGameplayTouchZone[] }, yFraction: number): PetGameplayTouchZone | undefined {\n return touch.zones.find(zone => yFraction >= zone.y0 && yFraction < zone.y1)\n}\n","/**\n * Gameplay HUD — the client half of the manifest 'gameplay' block (miku-pet\n * generalization). One component owns everything the block needs: the stat\n * bars and shop card (menu / shop pages), the touch-zone tap\n * handling, the idle director rolls, the work and sleep loops, and the\n * float-text toasts. It talks to the host through the injected verb API,\n * writes results straight back into the store (the 2 s poll stays the\n * backstop), and steers the frames2d renderer through the per-pet bus.\n * @module @linxin666/dsh-pet/client/GameplayHud\n */\n\nimport { useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, type ReactElement } from 'react'\nimport type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { PetDefinition, PetSkinDefinition } from '../registry.ts'\nimport type { PetGameplayVerbResult } from '../service.ts'\nimport { declaredModes, modeStateOf, PET_ROAM_DIRECTIONS, touchZoneAt, type PetRoamDirection } from '../gameplay.ts'\nimport type { PetStoreInstance } from './pet-store.ts'\nimport type { DragStream } from './drag-stream.ts'\nimport type { NS } from './locales.ts'\nimport styles from './pet.module.css'\n\n/** The gameplay verb API the plugin apply body injects (host-authoritative). */\nexport interface GameplayApi {\n touch: (zone?: string) => Promise<PetGameplayVerbResult>\n setMode: (mode: string | null) => Promise<PetGameplayVerbResult>\n workTick: () => Promise<PetGameplayVerbResult>\n buy: (item: string) => Promise<PetGameplayVerbResult>\n /**\n * Persist the selected skin for the current pet (host-authoritative;\n * `undefined` restores the pet's default look).\n */\n setSkin: (skin: string | undefined) => Promise<{ ok: boolean; error?: string }>\n}\n\n/**\n * The per-pet coordination bus. The frames2d visual mount registers the\n * track override (setTrack); the HUD registers the sprite tap handler; the\n * chrome calls into whatever is registered. Optional chaining everywhere —\n * either side may be mid-remount during a hot reload.\n */\nexport interface GameplayBus {\n setTrack?: (track?: string) => void\n /** Swap the pet's base idle track (skin switch); undefined restores default. */\n setIdleTrack?: (track?: string) => void\n /**\n * The base idle track the HUD wants right now, latched on the bus so a\n * renderer that registers late (or remounts: hidden/summoned, StrictMode's\n * double mount) still applies the restored skin instead of snapping back to\n * the default look. Mutating it never requires a re-render.\n */\n idleTrack?: string\n tap?: (fx: number, fy: number) => void\n /**\n * Card open/close request from the chrome (the hover panel's 玩法 action):\n * the HUD registers this, and calling it with no argument toggles the card\n * while a boolean pins the state (same chrome -> HUD direction as tap).\n */\n openCard?: (open?: boolean) => void\n /**\n * Walk the sprite in `direction` by `distance` px at `speed` px/s, clamped\n * to the viewport, and persist the resting spot like a drag. Returns the\n * distance actually travelled (0 when it cannot move), so the caller can\n * hold the walk art for exactly that long. Registered by the chrome\n * (PetSprite); absent while the sprite is unmounted.\n */\n walk?: (direction: PetRoamDirection, distance: number, speed: number) => number\n}\n\ntype HudPage = 'root' | 'shop' | 'skins'\n\n/** One floating toast (prize / insufficient funds). */\ninterface HudFloat {\n id: number\n text: string\n}\n\nlet floatSeq = 0\n\n/** The gameplay overlay for one frames2d pet that declares 'gameplay'. */\nexport function GameplayHud(props: {\n definition: PetDefinition\n store: PetStoreInstance\n api: GameplayApi\n bus: GameplayBus\n drag: DragStream\n t: PropsLocale<typeof NS>['t']\n}): ReactElement | null {\n const { definition, store, api, bus } = props\n const ui = useSyncExternalStore(store.subscribe, store.getSnapshot)\n const def = definition.gameplay\n const view = ui.snapshot?.gameplay\n // Host-persisted skin selection for this pet (undefined = default look).\n const persistedSkin = ui.snapshot?.skin\n\n const [open, setOpen] = useState(false)\n const [page, setPage] = useState<HudPage>('root')\n // Currently selected skin id (base idle swap); undefined = default look.\n const [skinId, setSkinId] = useState<string | undefined>(undefined)\n const skinIdRef = useRef<string | undefined>(undefined)\n skinIdRef.current = skinId\n const hudRef = useRef<HTMLDivElement | null>(null)\n const cardRef = useRef<HTMLDivElement | null>(null)\n const [floats, setFloats] = useState<HudFloat[]>([])\n // Mutable driver state (refs so intervals never re-arm on a poll tick).\n const modeRef = useRef<string | null>(view?.mode ?? null)\n modeRef.current = view?.mode ?? null\n /** Live gameplay view for the interval loops (def identity is stable, view is not). */\n const viewRef = useRef(view)\n viewRef.current = view\n const draggingRef = useRef(false)\n const touchLockUntilRef = useRef(0)\n const missRef = useRef(0)\n const busyRef = useRef(false)\n /** A roam walk owns the visual right now (the idle director must not steal it). */\n const roamHeldRef = useRef(false)\n /** A one-shot idle-director act owns the visual right now (the roam must not cut in). */\n const actHeldRef = useRef(false)\n /** Pending release of the roam's walk track (cleared when another owner takes it). */\n const roamTimerRef = useRef(0)\n\n // Dynamic-key lookups (stat ids / currency ids are manifest data).\n const tr = props.t as unknown as (key: string, values?: Record<string, string | number>) => string\n const statLabel = (name: string): string => tr('pet.gameplay.stat.' + name)\n const currencyLabel = (name: string): string => tr('pet.gameplay.currency.' + name)\n\n const pushFloat = (text: string): void => {\n const id = ++floatSeq\n setFloats(list => [...list.slice(-3), { id, text }])\n window.setTimeout(() => {\n setFloats(list => list.filter(entry => entry.id !== id))\n }, 1100)\n }\n\n const applyResult = (result: PetGameplayVerbResult): void => {\n if (result.view !== undefined) store.actions.setGameplayView(result.view)\n }\n\n /**\n * Give up the roam's claim on the shared track-override slot. Every other\n * owner (a mode, a touch reaction, a drag) calls this before it takes the\n * slot, so a walk that is still in flight can never release someone else's\n * track when its own hold window elapses.\n */\n const yieldRoam = (): void => {\n if (roamTimerRef.current !== 0) {\n window.clearTimeout(roamTimerRef.current)\n roamTimerRef.current = 0\n }\n roamHeldRef.current = false\n }\n\n // Tap handling (registered on the bus; PetSprite reports sprite-box\n // fractions). Sleep wakes on tap; work blocks taps; a held touch\n // animation turns taps into the plain-click boost.\n // Skin contract: while a skin is selected, taps only ever play that\n // skin's own click actions — a miss resolves to the plain click boost,\n // never the default touch zones (so a skinned pet cannot trigger the\n // default pet's shy/work reactions).\n useEffect(() => {\n if (def === undefined) return undefined\n // Play a one-shot override track and lock tap input for its duration so\n // consecutive taps cannot retrigger mid-play (skin click actions and\n // default touch-zone reactions share this path).\n const holdTrack = (track: string, holdMs: number): void => {\n yieldRoam()\n bus.setTrack?.(track)\n touchLockUntilRef.current = Date.now() + holdMs\n window.setTimeout(() => {\n if (Date.now() >= touchLockUntilRef.current) bus.setTrack?.(undefined)\n }, holdMs)\n }\n const speak = (phrases?: string[]): void => {\n if (phrases !== undefined && phrases.length > 0) {\n const phrase = phrases[Math.floor(Math.random() * phrases.length)]!\n store.actions.setFeedback({ text: phrase, kind: 'none', at: Date.now() })\n }\n }\n // Total play time of a track in ms (its fallback lands back in the skin\n // base idle, so holding the lock for the full loop is unnecessary).\n const trackDuration = (track: string): number =>\n definition.frames2d?.tracks[track]?.durations.reduce((sum, ms) => sum + ms, 0) ?? 0\n bus.tap = (fx, fy) => {\n // Any non-work mode ends on a tap (sleep wakes up, a bath steps out);\n // work keeps swallowing taps while its round is running.\n if (modeRef.current !== null && modeRef.current !== 'work') {\n void api.setMode(null).then(applyResult, () => undefined)\n return\n }\n if (modeRef.current === 'work') return\n const box = def.hitBox ?? { x0: 0, y0: 0, x1: 1, y1: 1 }\n const hx = (fx - box.x0) / (box.x1 - box.x0)\n const hy = (fy - box.y0) / (box.y1 - box.y0)\n if (hx < 0 || hx > 1 || hy < 0 || hy > 1) return\n if (Date.now() < touchLockUntilRef.current) {\n void api.touch().then(applyResult, () => undefined)\n return\n }\n const activeSkin = definition.frames2d?.skins?.find(skin => skin.id === skinIdRef.current)\n if (activeSkin !== undefined) {\n // Skin click actions roll first (declared order, cumulative\n // probabilities); on a hit play the action's track once. A miss\n // stays on the plain click boost — never the default touch zones.\n const actions = activeSkin.clickActions ?? []\n if (actions.length > 0) {\n let roll = Math.random()\n const fired = actions.find(action => {\n if (roll < action.probability) return true\n roll -= action.probability\n return false\n })\n if (fired !== undefined) {\n holdTrack(fired.track, trackDuration(fired.track) || 3000)\n speak(fired.phrases)\n return\n }\n }\n void api.touch().then(applyResult, () => undefined)\n return\n }\n const zone = def.touch === undefined ? undefined : touchZoneAt(def.touch, hy)\n if (zone === undefined) return\n void api.touch(zone.name).then((result) => {\n applyResult(result)\n if (result.hit !== true) return\n if (result.state !== undefined) holdTrack(result.state, result.stateMs ?? 3000)\n if (result.phrase !== undefined) {\n store.actions.setFeedback({ text: result.phrase, kind: 'none', at: Date.now() })\n }\n }, () => undefined)\n }\n return () => { bus.tap = undefined }\n // eslint-disable-next-line react-hooks/exhaustive-deps -- one registration per pet definition\n }, [definition.id, def])\n\n // Panel entry (chrome -> HUD): the hover panel's 玩法 button drives the\n // card through this channel so the chrome never needs the card's state.\n useEffect(() => {\n bus.openCard = (next?: boolean) => {\n setOpen(prev => next ?? !prev)\n setPage('root')\n }\n return () => { bus.openCard = undefined }\n // eslint-disable-next-line react-hooks/exhaustive-deps -- one registration per bus\n }, [bus])\n\n // Card placement: the card must not enter the bubble band above the sprite\n // or the hover-panel band below it, so it opens beside the sprite instead\n // of growing upward from the pet's feet. It is vertically centered on the\n // sprite box, clamped to the sprite's height, and the side is chosen by\n // the space available to each side (right first; a pet parked near the\n // right viewport edge flips the card to the left).\n useLayoutEffect(() => {\n if (!open) return undefined\n const hud = hudRef.current\n const card = cardRef.current\n if (hud === null || card === null) return undefined\n const place = (): void => {\n const box = hud.parentElement?.getBoundingClientRect()\n if (box === undefined) return\n const gap = 8\n const width = card.getBoundingClientRect().width\n const toRight = window.innerWidth - box.right\n const x = toRight >= width + gap ? box.width + gap : -(width + gap)\n card.style.transform = 'translate(' + Math.round(x) + 'px, ' + Math.round(-box.height / 2) + 'px) translateY(50%)'\n card.style.maxHeight = Math.round(box.height) + 'px'\n }\n place()\n window.addEventListener('resize', place)\n return () => { window.removeEventListener('resize', place) }\n // eslint-disable-next-line react-hooks/exhaustive-deps -- one placement per open/page change\n }, [open, page])\n\n // Drag gestures end any non-work mode (sleep wakes, a bath steps out); the\n // drag stream also feeds the idle director's suppression check.\n useEffect(() => {\n return props.drag.subscribe((dragging) => {\n draggingRef.current = dragging\n if (dragging) yieldRoam()\n if (dragging && modeRef.current !== null && modeRef.current !== 'work') {\n void api.setMode(null).then(applyResult, () => undefined)\n }\n })\n // eslint-disable-next-line react-hooks/exhaustive-deps -- one subscription per drag stream\n }, [props.drag])\n\n // Idle director: weighted rolls between staying idle and playing an act.\n // Rolls in every phase -- an ambient act is not a waiting-room performance,\n // and the idle phase only appears when neither the agent nor the user is busy\n // -- but only while nothing else owns the visual: no mode, no drag, no held\n // touch animation, no roam walk and no act already playing. maxMiss forces an\n // act after too many idle rolls in a row.\n useEffect(() => {\n const director = def?.idleDirector\n if (def === undefined || director === undefined) return undefined\n const total = director.idleWeight + director.acts.reduce((sum, act) => sum + act.weight, 0)\n if (total <= 0) return undefined\n let actTimer = 0\n const timer = window.setInterval(() => {\n if (modeRef.current !== null || draggingRef.current) return\n if (Date.now() < touchLockUntilRef.current) return\n if (roamHeldRef.current) return // a roam walk owns the visual\n if (actHeldRef.current) return // the previous act is still playing\n let pickedAct: { track: string; weight: number; phrases?: string[] } | undefined\n if (missRef.current >= director.maxMiss) {\n // Forced act: pick among the acts only.\n const actTotal = director.acts.reduce((sum, act) => sum + act.weight, 0)\n let actRoll = Math.random() * actTotal\n for (const act of director.acts) {\n actRoll -= act.weight\n if (actRoll < 0) { pickedAct = act; break }\n }\n } else {\n let roll = Math.random() * total\n for (const act of director.acts) {\n roll -= act.weight\n if (roll < 0) { pickedAct = act; break }\n }\n }\n if (pickedAct === undefined) {\n missRef.current += 1\n return\n }\n missRef.current = 0\n actHeldRef.current = true\n bus.setTrack?.(pickedAct.track)\n // A one-shot act owns the visual until its own duration elapses (the\n // renderer then falls back to the phase map); the roam must not cut in.\n const holdMs = definition.frames2d?.tracks[pickedAct.track]?.durations.reduce((sum, ms) => sum + ms, 0) ?? 0\n window.clearTimeout(actTimer)\n actTimer = window.setTimeout(() => { actHeldRef.current = false }, holdMs > 0 ? holdMs : 3000)\n // Acts with a phrase pool speak one line while they play (miku parity).\n if (pickedAct.phrases !== undefined && pickedAct.phrases.length > 0) {\n const phrase = pickedAct.phrases[Math.floor(Math.random() * pickedAct.phrases.length)]!\n store.actions.setFeedback({ text: phrase, kind: 'none', at: Date.now() })\n }\n }, director.intervalMs)\n return () => {\n window.clearInterval(timer)\n window.clearTimeout(actTimer)\n actHeldRef.current = false\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps -- one director per pet definition\n }, [definition.id, def])\n\n // Work loop: hold the work track, adjudicate one round per tick, play the\n // result track for its hold window, then resume. Leaving the mode\n // releases the override so the phase mapping takes over. A skin that\n // declares gameplayTracks for the work states plays its own art instead.\n useEffect(() => {\n const work = def?.work\n if (def === undefined || work === undefined || view?.mode !== 'work') return undefined\n const skinGameplay = definition.frames2d?.skins?.find(skin => skin.id === skinIdRef.current)?.gameplayTracks\n /** The state's track, swapped for the skin's override when it declares one. */\n const trackOf = (state: string): string => skinGameplay?.[state] ?? state\n bus.setTrack?.(trackOf(work.state))\n let resultTimer = 0\n const timer = window.setInterval(() => {\n if (busyRef.current) return\n busyRef.current = true\n void api.workTick().then((result) => {\n busyRef.current = false\n // Leaving work mode while the adjudication is in flight drops the late\n // result: writing it back would show work rewards and play the result\n // track for a mode the user has already left (#1495).\n if (modeRef.current !== 'work') return\n applyResult(result)\n if (result.ok !== true || result.outcome === undefined) return\n const resultTrack = trackOf(result.outcome === 'success' ? work.successState : work.failState)\n const hold = result.outcome === 'success' ? work.resultMs?.success ?? 1300 : work.resultMs?.fail ?? 1900\n bus.setTrack?.(resultTrack)\n resultTimer = window.setTimeout(() => {\n if (modeRef.current === 'work') bus.setTrack?.(trackOf(work.state))\n }, hold)\n }, () => { busyRef.current = false })\n }, work.tickMs)\n return () => {\n window.clearInterval(timer)\n window.clearTimeout(resultTimer)\n bus.setTrack?.(undefined)\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps -- the loop keys on the mode and the selected skin\n }, [definition.id, def, view?.mode, skinId])\n\n // Mode loop: hold the active non-work mode's track (sleep, a bath, any\n // extra 'modes' entry). The stat restore is host-side (lazy settle). While a\n // skin with a matching gameplayTracks override is selected, the skin's own\n // track replaces the default one (e.g. a skin-specific doze).\n useEffect(() => {\n const active = view?.mode\n if (def === undefined || active === undefined || active === null || active === 'work') return undefined\n const hold = modeStateOf(def, active)\n if (hold === undefined) return undefined\n const skinGameplay = definition.frames2d?.skins?.find(skin => skin.id === skinIdRef.current)?.gameplayTracks\n yieldRoam()\n bus.setTrack?.(skinGameplay?.[active] ?? hold)\n return () => bus.setTrack?.(undefined)\n // eslint-disable-next-line react-hooks/exhaustive-deps -- the loop keys on the mode value\n }, [definition.id, def, view?.mode, skinId])\n\n // Random roaming (manifest 'roam'): on a slow interval -- in any phase, as long\n // as no mode, drag, touch animation or director act owns the pet -- roll a\n // wander. The chrome walks the sprite and persists the new spot; this side\n // holds the walk track for exactly the travel time.\n useEffect(() => {\n const roam = def?.roam\n if (def === undefined || roam === undefined) return undefined\n const roll = (): void => {\n // Every phase: a wandering pet is ambient, not a performance, so she\n // keeps walking while the agent works (the idle director's acts stay\n // idle-only). A mode, a drag, a touch animation and a director\n // act all still own the pet and suppress the roll.\n if (modeRef.current !== null || draggingRef.current) return\n if (Date.now() < touchLockUntilRef.current) return\n if (roamHeldRef.current || actHeldRef.current) return\n if (Math.random() >= roam.probability) return\n const span = roam.distanceMax - roam.distanceMin\n const distance = roam.distanceMin + Math.random() * span\n const directions = roam.directions ?? PET_ROAM_DIRECTIONS\n const direction = directions[Math.floor(Math.random() * directions.length)] ?? 'left'\n const travelled = bus.walk?.(direction, distance, roam.speed) ?? 0\n if (travelled === 0) return\n roamHeldRef.current = true\n bus.setTrack?.(roam.state)\n roamTimerRef.current = window.setTimeout(() => {\n roamTimerRef.current = 0\n if (!roamHeldRef.current) return // another owner already took the slot\n roamHeldRef.current = false\n bus.setTrack?.(undefined)\n }, Math.max(150, (Math.abs(travelled) / roam.speed) * 1000))\n }\n // The two decision timers must never share a tick. The roam starts half an\n // interval late, so its ticks interleave with the idle director's instead\n // of landing on the same instant (10 s and 15 s coincide every 30 s).\n let timer = 0\n const lead = window.setTimeout(() => {\n roll()\n timer = window.setInterval(roll, roam.intervalMs)\n }, Math.round(roam.intervalMs / 2))\n return () => {\n window.clearTimeout(lead)\n window.clearInterval(timer)\n yieldRoam()\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps -- one director per pet definition\n }, [definition.id, def])\n\n if (def === undefined || view === undefined) return null\n\n const mode = view.mode\n const stats = def.stats ?? {}\n const shop = def.shop\n\n // Every menu mode beyond work: sleep plus any extra 'modes' the pet declares.\n const menuModes = declaredModes(def)\n\n /** Action-button label for one mode (active = the button that leaves it). */\n const modeLabel = (name: string, active: boolean): string => {\n if (name === 'sleep') return tr(active ? 'pet.gameplay.wake' : 'pet.gameplay.sleep')\n const declared = def.modes?.[name]\n return (active ? declared?.activeLabel ?? declared?.label : declared?.label) ?? tr('pet.gameplay.' + name)\n }\n\n /** Chip label for the mode the pet is in right now. */\n const modeChip = (name: string): string => {\n if (name === 'work') return tr('pet.gameplay.working')\n if (name === 'sleep') return tr('pet.gameplay.sleeping')\n const declared = def.modes?.[name]\n return declared?.activeLabel ?? declared?.label ?? tr('pet.gameplay.' + name)\n }\n\n const buy = (itemId: string): void => {\n void api.buy(itemId).then((result) => {\n applyResult(result)\n if (result.ok !== true) {\n if (result.error === 'insufficient-funds') {\n const item = shop?.items.find(entry => entry.id === itemId)\n pushFloat(tr('pet.gameplay.insufficient', { currency: currencyLabel(item?.currency ?? 'treats') }))\n }\n return\n }\n if (result.prize !== undefined) {\n pushFloat(tr('pet.gameplay.prize', { amount: result.prize.amount, currency: currencyLabel(result.prize.currency) }))\n }\n }, () => undefined)\n }\n\n const setMode = (next: string | null): void => {\n void api.setMode(next).then(applyResult, () => undefined)\n }\n\n // Skin selection is persisted host-side (per pet): re-seed the menu from\n // every fresh state view, so a page reload or client restart keeps the last\n // choice instead of snapping back to the default look.\n useEffect(() => {\n setSkinId(persistedSkin)\n }, [definition.id, persistedSkin])\n\n // Push the resolved base idle track into the renderer whenever the pet or\n // the selection changes. The value is latched on the bus first: the visual\n // may register later, or remount later (hidden/summoned), and reads the\n // latch back on activation so a restored skin never falls back to default.\n useEffect(() => {\n const skin = definition.frames2d?.skins?.find(candidate => candidate.id === skinId)\n bus.idleTrack = skin?.idleTrack\n bus.setIdleTrack?.(skin?.idleTrack)\n // persistedSkin rides the deps so the host's value also re-pushes on\n // arrival (a renderer that mounted early still converges).\n // eslint-disable-next-line react-hooks/exhaustive-deps -- one push per selection\n }, [definition.id, skinId, persistedSkin])\n\n const skins = definition.frames2d?.skins\n /** The base idle track one skin id resolves to (undefined = default look). */\n const skinTrackOf = (id: string | undefined): string | undefined =>\n id === undefined ? undefined : definition.frames2d?.skins?.find(candidate => candidate.id === id)?.idleTrack\n\n const selectSkin = (skin: PetSkinDefinition | undefined): void => {\n setSkinId(skin?.id)\n bus.setIdleTrack?.(skin?.idleTrack)\n // The host owns the choice: a refusal (unknown skin) restores both the\n // menu highlight and the renderer to the value it still serves.\n const restore = (): void => {\n setSkinId(persistedSkin)\n bus.setIdleTrack?.(skinTrackOf(persistedSkin))\n }\n void api.setSkin(skin?.id).then((result) => {\n if (result.ok) return\n restore()\n }, restore)\n }\n\n return (\n <div ref={hudRef} className={styles.gameplayHud} data-dsh-pet-gameplay={definition.id}>\n {floats.map(entry => (\n <div key={entry.id} className={styles.gameplayFloat}>{entry.text}</div>\n ))}\n {mode !== null && (\n <div className={styles.gameplayModeChip}>\n {modeChip(mode)}\n </div>\n )}\n {open && (\n <div ref={cardRef} className={styles.gameplayCard} data-page={page}>\n {page === 'root' && (\n <>\n <div className={styles.gameplayBars}>\n {Object.entries(stats).map(([name, stat]) => {\n const value = view.stats[name] ?? 0\n return (\n <div key={name} className={styles.gameplayBarRow} title={statLabel(name) + ' ' + String(value) + '/' + String(stat.max)}>\n <span className={styles.gameplayBarLabel}>{statLabel(name)}</span>\n <span className={styles.gameplayBarTrack}>\n <span\n className={styles.gameplayBarFill}\n style={{ width: Math.round((value / stat.max) * 100) + '%' }}\n />\n </span>\n </div>\n )\n })}\n </div>\n <div className={styles.gameplayActions}>\n {menuModes.map(name => (\n <button\n key={name}\n type=\"button\"\n className={styles.action}\n onClick={() => setMode(mode === name ? null : name)}\n >\n {modeLabel(name, mode === name)}\n </button>\n ))}\n {shop !== undefined && (\n <button type=\"button\" className={styles.action} onClick={() => setPage('shop')}>\n {tr('pet.gameplay.shop')}\n </button>\n )}\n {skins !== undefined && skins.length > 0 && (\n <button type=\"button\" className={styles.action} onClick={() => setPage('skins')}>\n {tr('pet.gameplay.skin')}\n </button>\n )}\n {def.work !== undefined && (\n <button\n type=\"button\"\n className={styles.action}\n onClick={() => setMode(mode === 'work' ? null : 'work')}\n >\n {tr(mode === 'work' ? 'pet.gameplay.stopWork' : 'pet.gameplay.work')}\n </button>\n )}\n </div>\n </>\n )}\n {page === 'shop' && shop !== undefined && (\n <>\n <div className={styles.gameplayShopItems}>\n {shop.items.map(item => (\n <button\n key={item.id}\n type=\"button\"\n className={styles.gameplayShopItem}\n onClick={() => buy(item.id)}\n title={item.label + ' — ' + String(item.price) + ' ' + currencyLabel(item.currency)}\n >\n {item.image !== undefined && (\n <img className={styles.gameplayShopItemImage} src={item.image} alt=\"\" draggable={false} />\n )}\n <span className={styles.gameplayShopItemLabel}>{item.label}</span>\n <span className={styles.gameplayShopItemPrice}>\n {item.price} {currencyLabel(item.currency)}\n </span>\n </button>\n ))}\n </div>\n <div className={styles.gameplayActions}>\n <button type=\"button\" className={styles.action} onClick={() => setPage('root')}>\n {tr('pet.gameplay.back')}\n </button>\n </div>\n </>\n )}\n {page === 'skins' && skins !== undefined && (\n <>\n <div className={styles.gameplaySkinItems}>\n <button\n type=\"button\"\n className={skinId === undefined ? styles.gameplaySkinItem + ' ' + styles.gameplaySkinItemActive : styles.gameplaySkinItem}\n onClick={() => selectSkin(undefined)}\n >\n {tr('pet.gameplay.skinDefault')}\n </button>\n {skins.map(skin => (\n <button\n key={skin.id}\n type=\"button\"\n className={skinId === skin.id ? styles.gameplaySkinItem + ' ' + styles.gameplaySkinItemActive : styles.gameplaySkinItem}\n onClick={() => selectSkin(skin)}\n >\n {skin.label}\n </button>\n ))}\n </div>\n <div className={styles.gameplayActions}>\n <button type=\"button\" className={styles.action} onClick={() => setPage('root')}>\n {tr('pet.gameplay.back')}\n </button>\n </div>\n </>\n )}\n <button\n type=\"button\"\n className={styles.gameplayClose}\n aria-label={tr('pet.gameplay.back')}\n onClick={() => setOpen(false)}\n >\n ×\n </button>\n </div>\n )}\n </div>\n )\n}\n","/**\n * Global floating pet entry. The pet is host-global (its state, display and\n * interactions live on '/api/pet/*' endpoints with no session dimension), so\n * it must not ride a session-scoped slot — on the new-conversation screen no\n * session exists to scope a slot by, and the pet would vanish (issue #48).\n * The client half therefore mounts this entry straight onto 'document.body'\n * (see index.ts): while visible it renders the floating PetSprite (a portal\n * into the plugin root, so the root owns the whole surface), while hidden it\n * renders a fixed-position summon button. Which sprite renders is decided by\n * the host snapshot's pet id resolved against the registry list — no per-pet\n * component exists.\n * @module @linxin666/dsh-pet/client/PetDockEntry\n */\n\nimport { useEffect, useRef, useSyncExternalStore, type ReactElement } from 'react'\nimport type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { PetDisplayConfig } from '../persist.ts'\nimport type { PetStoreInstance } from './pet-store.ts'\nimport { PetSprite } from './PetSprite.tsx'\nimport { PetRendererSwitch } from './renderers/PetRendererSwitch.tsx'\nimport { createDragStream, type DragStream } from './drag-stream.ts'\nimport { GameplayHud, type GameplayApi, type GameplayBus } from './gameplay-hud.tsx'\nimport { NS } from './locales.ts'\nimport styles from './pet.module.css'\n\n/** Injected actions handed to the dock entry component. */\nexport interface PetInjected {\n /** The app-wide pet store instance (snapshot + registry list + feedback). */\n store: PetStoreInstance\n /** Ensure the first snapshot (and registry list) is fetched (called on mount). */\n ensure: () => void\n /** Pet the sprite (click). */\n pet: () => void\n /** Feed the sprite. */\n feed: () => void\n /** Hide the sprite. */\n hide: () => void\n /** Summon the hidden sprite back. */\n summon: () => void\n /** Persist a drag position. */\n dragEnd: (right: number, bottom: number) => void\n /** Rename the selected pet (persisted by the host). */\n rename: (name: string) => void\n /**\n * Report a click on one plugin-registered panel action (issue #6). The host\n * dispatches it to the plugin that registered the action; the panel itself\n * only renders the button the state snapshot served.\n */\n panelAction: (id: string) => void\n /** Navigate the GUI to the session a bubble reports on. */\n openSession: (sessionId: string) => void\n /** Clear the reaction bubble. */\n feedbackDone: () => void\n /** Gameplay verb API (miku-pet generalization); wired but unused for pets without a gameplay block. */\n gameplay: GameplayApi\n}\n\n/** Composed props of the global pet entry (locale + injected; no slot runtime share). */\nexport type PetDockEntryProps =\n PetInjected\n & PropsLocale<typeof NS>\n & {\n /**\n * DOM node the floating sprite chrome portals into. Defaults to\n * document.body; the plugin apply passes its [data-dsh-plugin=\"pet\"]\n * root so root-keyed suppressors (the portrait mobile layer) and skins\n * own the whole pet surface as one unit.\n */\n portalTarget?: Element\n /**\n * Active UI locale id, forwarded to the sprite so a pet-declared English\n * rank name (`rankEn`) applies when the UI language is English.\n */\n lang?: string\n }\n\nconst DEFAULT_DISPLAY: PetDisplayConfig = { visible: true, size: 160, right: 24, bottom: 20, bubbleScale: 1 }\n\n/**\n * Dock entry: while the pet is visible, mount the floating PetSprite (it\n * portals itself onto document.body); while hidden, render the summon\n * button so the pet can always come back. The store is the plugin-owned\n * single instance — the slot system provides none because the pet is\n * host-global, not session-scoped.\n */\nexport function PetDockEntry(props: PetDockEntryProps): ReactElement {\n const { store, ensure } = props\n const ui = useSyncExternalStore(store.subscribe, store.getSnapshot)\n const snapshot = ui.snapshot\n const feedback = ui.feedback\n const definition = ui.pets.find(entry => entry.id === snapshot?.pet.id) ?? null\n const visible = snapshot?.display.visible ?? true\n\n useEffect(() => {\n ensure()\n }, [ensure])\n\n // Per-pet gameplay wiring: the coordination bus (HUD taps <-> chrome,\n // HUD track overrides <-> frames2d mount) and the shared drag stream.\n const auxRef = useRef<{ id: string; bus: GameplayBus; drag: DragStream } | null>(null)\n if (definition !== null && (auxRef.current === null || auxRef.current.id !== definition.id)) {\n auxRef.current = { id: definition.id, bus: {}, drag: createDragStream() }\n }\n const aux = auxRef.current\n const gameplay = definition?.gameplay\n\n if (visible) {\n return (\n <span data-pet-dock data-testid=\"pet-dock\">\n {snapshot === null || definition === null\n ? null\n : (\n <PetRendererSwitch\n definition={definition}\n phase={snapshot?.phase ?? 'idle'}\n onPet={props.pet}\n {...(aux === null ? {} : { drag: aux.drag, bus: aux.bus })}\n t={props.t}\n >\n <PetSprite\n snapshot={snapshot}\n definition={definition}\n display={snapshot.display}\n feedback={feedback}\n onPet={props.pet}\n onFeed={props.feed}\n onHide={props.hide}\n onDragEnd={props.dragEnd}\n onRename={props.rename}\n onPanelAction={props.panelAction}\n onOpenSession={props.openSession}\n onFeedbackDone={props.feedbackDone}\n portalTarget={props.portalTarget}\n dragDisabled={snapshot.gameplay?.mode === 'work'}\n {...(aux === null ? {} : { bus: aux.bus })}\n lang={props.lang}\n {...(gameplay === undefined || aux === null\n ? {}\n : {\n onGameplayTap: (fx: number, fy: number) => aux.bus.tap?.(fx, fy),\n onGameplayMenu: () => aux.bus.openCard?.(),\n hud: (\n <GameplayHud\n definition={definition}\n store={store}\n api={props.gameplay}\n bus={aux.bus}\n drag={aux.drag}\n t={props.t}\n />\n ),\n })}\n t={props.t}\n />\n </PetRendererSwitch>\n )}\n </span>\n )\n }\n const display = snapshot?.display ?? DEFAULT_DISPLAY\n return (\n <button\n type=\"button\"\n className={styles.summon}\n style={{\n position: 'fixed',\n right: display.right,\n bottom: display.bottom,\n zIndex: 2147483000,\n }}\n onClick={props.summon}\n data-testid=\"pet-summon\"\n data-dsh-part=\"summon-button\"\n >\n {props.t('pet.summon', { name: snapshot?.name ?? '' })}\n </button>\n )\n}\n","/**\n * Renderer contract — the seam between the pet center and its renderers\n * (issue #623, milestone M2 P4). Renderers never see the DSH session, the\n * registry, or the network: they receive exactly three capabilities — an\n * asset base URL, the ActivityPhase stream, and the interaction write-back —\n * inside a center-owned container. Every mount is a fresh activation whose\n * cleanups must be idempotent.\n *\n * This contract only serves real consumers: sprite2d (existing) and live2d\n * (M3). Speculative capabilities join only when a renderer actually needs\n * them.\n * @module @linxin666/dsh-pet/contracts/renderer\n */\n\nimport type { ActivityPhase } from '../state.ts'\n\n/** Contract version renderers declare against (independent of the manifest). */\nexport const PET_RENDERER_API_VERSION = 'x-org.linxin666.pet-center/v1alpha1'\n\n/** What the pet center hands a renderer on mount. */\nexport interface PetRendererContext {\n /** The selected pet's id. */\n readonly petId: string\n /** Same-origin URL prefix of this pet's assets ('/pet/<id>'). */\n readonly assetBase: string\n /** Center-owned mount root; renderers must not attach to document.body. */\n readonly container: HTMLElement\n /** The ActivityPhase stream (pet-center owned; renderers subscribe). */\n readonly phase: {\n get(): ActivityPhase\n subscribe(listener: (phase: ActivityPhase) => void): () => void\n }\n /** The single interaction write-back into the affinity economy. */\n readonly interact: (kind: 'tap') => void\n /** Register an activation-scoped cleanup; run on dispose, idempotently. */\n onCleanup(fn: () => void): void\n}\n\n/** A mounted renderer activation. */\nexport interface PetRendererHandle {\n /** Tear the activation down; may be called 0/1/N times. */\n dispose(): void\n}\n\n/**\n * One renderer implementation. validateConfig is fail-closed over the\n * renderer-specific manifest block (schema v2 'sprite2d'/'live2d' blocks).\n */\nexport interface PetRenderer<Config = unknown> {\n readonly id: string\n readonly apiVersion: string\n validateConfig(config: unknown): Config\n mount(ctx: PetRendererContext, config: Config): PetRendererHandle\n}\n","/**\n * Live2D runtime loading (pet-center M3) — the two scripts a live2d mount\n * needs, fetched lazily through the plugin's own runtime route: the\n * user-supplied Cubism Core (proprietary; the plugin never bundles or\n * downloads it — issue #623 M1 §0) and the plugin-shipped MIT vendor bundle\n * (pixi.js + untitled-pixi-live2d-engine). Each loads at most once per page;\n * concurrent mounts share the in-flight promise, and a failure is cached as\n * 'absent' so a broken install stops retrying the network every mount.\n *\n * The vendor surface below is the structural slice the renderer consumes;\n * the real objects come from 'window.__dshPetLive2d' (lib/live2d-vendor.js),\n * so this module never imports pixi — the client bundle stays lean.\n * @module @linxin666/dsh-pet/client/renderers/live2d/runtime\n */\n\n/** Runtime file URLs the host serves ('/api/pet/runtime/<name>', M3-2). */\nconst CORE_URL = '/api/pet/runtime/live2dcubismcore.min.js'\nconst VENDOR_URL = '/api/pet/runtime/live2d-vendor.js'\n\n/** The pixi Application slice the renderer uses. */\nexport interface Live2dVendorApp {\n canvas: HTMLCanvasElement\n stage: { addChild(child: unknown): unknown }\n renderer: {\n readonly width: number\n readonly height: number\n resize(width: number, height: number): void\n }\n init(options: Record<string, unknown>): Promise<void>\n destroy(rendererOptions?: boolean | { removeView?: boolean; releaseGlobalResources?: boolean }, options?: Record<string, unknown>): void\n}\n\n/** The Live2DModel slice the renderer uses. */\nexport interface Live2dVendorModel {\n automator: { autoUpdate: boolean }\n anchor: { set(x: number, y?: number): void }\n position: { set(x: number, y: number): void }\n scale: { set(x: number, y?: number): void }\n readonly width: number\n readonly height: number\n internalModel: {\n settings: {\n motions?: Record<string, unknown[]>\n hitAreas?: readonly { Name?: string }[]\n }\n }\n motion(group: string, index?: number): Promise<unknown>\n expression(name?: string): unknown\n hitTest(x: number, y: number): string[]\n on(event: string, fn: () => void): unknown\n destroy(options?: { children?: boolean; texture?: boolean; baseTexture?: boolean }): void\n}\n\n/** The vendor bundle global (window.__dshPetLive2d). */\nexport interface Live2dVendor {\n Application: new () => Live2dVendorApp\n extensions: { add(...items: unknown[]): void }\n Live2DPlugin: unknown\n configureCubismSDK(options: Record<string, unknown>): void\n Live2DModel: { from(source: string, options?: Record<string, unknown>): Promise<Live2dVendorModel> }\n}\n\ndeclare global {\n interface Window {\n Live2DCubismCore?: unknown\n __dshPetLive2d?: Live2dVendor\n }\n}\n\n/** Injects one classic script tag; resolves on load, rejects on error. */\ntype ScriptInjector = (src: string) => Promise<void>\n\nconst defaultInjector: ScriptInjector = (src) => new Promise<void>((resolve, reject) => {\n const tag = document.createElement('script')\n tag.src = src\n tag.onload = () => resolve()\n tag.onerror = () => reject(new Error('script failed to load: ' + src))\n document.head.appendChild(tag)\n})\n\n/** Test seam: swap the network for a stub injector. */\nexport interface Live2dRuntimeProbe {\n inject?: ScriptInjector\n}\n\nlet corePromise: Promise<boolean> | undefined\nlet vendorPromise: Promise<Live2dVendor | undefined> | undefined\n\n/**\n * Ensure the Cubism Core global exists, injecting the runtime-route script\n * once when absent. Resolves false when the user has not installed the core\n * (a normal state — the renderer turns it into install guidance).\n */\nexport function ensureCubismCore(probe: Live2dRuntimeProbe = {}): Promise<boolean> {\n if (typeof window !== 'undefined' && window.Live2DCubismCore !== undefined) return Promise.resolve(true)\n if (probe.inject !== undefined) {\n return probe.inject(CORE_URL)\n .then(() => typeof window !== 'undefined' && window.Live2DCubismCore !== undefined)\n .catch(() => false)\n }\n corePromise ??= defaultInjector(CORE_URL)\n .then(() => typeof window !== 'undefined' && window.Live2DCubismCore !== undefined)\n .catch(() => false)\n return corePromise\n}\n\n/** Ensure the plugin vendor bundle global exists (same caching discipline). */\nexport function ensureLive2dVendor(probe: Live2dRuntimeProbe = {}): Promise<Live2dVendor | undefined> {\n if (typeof window !== 'undefined' && window.__dshPetLive2d !== undefined) return Promise.resolve(window.__dshPetLive2d)\n if (probe.inject !== undefined) {\n return probe.inject(VENDOR_URL)\n .then(() => typeof window !== 'undefined' ? window.__dshPetLive2d : undefined)\n .catch(() => undefined)\n }\n vendorPromise ??= defaultInjector(VENDOR_URL)\n .then(() => typeof window !== 'undefined' ? window.__dshPetLive2d : undefined)\n .catch(() => undefined)\n return vendorPromise\n}\n\n/** Reset the cached script promises (tests). */\nexport function resetLive2dRuntime(): void {\n corePromise = undefined\n vendorPromise = undefined\n}\n","/**\n * Live2D renderer (pet-center M3, issue #623) — mounts a Cubism model into\n * the center-owned container through the lazy vendor stack. The mount call\n * itself is synchronous per the renderer contract: the boot (core script →\n * vendor script → pixi → model) continues asynchronously and reports fatal\n * failures through the handle's error sink, so the React bridge can render\n * localized guidance. Disposing mid-boot is race-safe.\n *\n * Interaction model: the center chrome owns the affinity economy (its click\n * handler fires the pet interaction exactly like sprite2d); this renderer's\n * 'tap' affordance only drives the model's hit-area motion feedback. The\n * contract's interact write-back stays available for future standalone\n * mounts and is intentionally not invoked here.\n *\n * Motion mapping: manifests map ActivityPhases to motion GROUP names; every\n * unmapped phase (and any mapped-but-absent group) falls back to the idle\n * group — official sample models only ship Idle/TapBody, so the fallback is\n * mandatory. Groups with multiple motions pick a random entry, and a tap\n * that hits a declared hit area plays the conventional 'TapBody' group,\n * returning to the phase's group when the tap motion finishes.\n * @module @linxin666/dsh-pet/client/renderers/live2d\n */\n\nimport type { ActivityPhase } from '../../state.ts'\nimport {\n PET_RENDERER_API_VERSION,\n type PetRenderer,\n type PetRendererContext,\n type PetRendererHandle,\n} from '../../contracts/renderer.ts'\nimport {\n ensureCubismCore,\n ensureLive2dVendor,\n type Live2dVendor,\n type Live2dVendorApp,\n type Live2dVendorModel,\n} from './live2d/runtime.ts'\n\n/** Renderer config: the client-visible live2d block (fail-closed validated). */\nexport interface PetLive2dConfig {\n modelUrl: string\n scale?: number\n translate?: { x?: number; y?: number }\n motions: Partial<Record<ActivityPhase, string>> & { idle: string }\n expressions?: Partial<Record<ActivityPhase, string>>\n hitAreas?: string[]\n}\n\n/** Fatal mount failure codes the bridge localizes. */\nexport type Live2dErrorCode = 'core-missing' | 'vendor-missing' | 'load-failed'\n\n/** The live2d activation handle: contract dispose plus tap + error sink. */\nexport interface Live2dRendererHandle extends PetRendererHandle {\n /** Forward a chrome tap in container coordinates; plays the hit motion. */\n tap(x: number, y: number): void\n /** Subscribe to fatal mount errors (at most one fires per activation). */\n onError(listener: (code: Live2dErrorCode) => void): void\n}\n\n/** The de-facto tap-motion group of Cubism sample models. */\nconst TAP_GROUP = 'TapBody'\n\n/**\n * Keep one screen-appropriate atlas LOD instead of asking Pixi for the\n * engine's default full mip chain. A user model can legitimately carry an\n * 8192px texture while the pet itself is only a few hundred pixels tall;\n * `single-auto` preserves the source for larger renders and generates one\n * downsampled atlas only when the effective on-screen scale warrants it.\n */\nconst TEXTURE_OPTIONS = { lod: 'single-auto' } as const\n/** Recursively release the activation without invalidating shared texture caches. */\nconst DESTROY_OPTIONS = { children: true } as const\n/** Remove only this activation's canvas; `true` would release Pixi globals. */\nconst RENDERER_DESTROY_OPTIONS = { removeView: true } as const\n\ninterface Live2dModelSize {\n width: number\n height: number\n}\n\n/** Ignore hidden/zero boxes and keep Pixi dimensions stable and integral. */\nfunction normalizeRendererSize(width: number, height: number): Live2dModelSize | undefined {\n if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) return undefined\n return {\n width: Math.max(1, Math.round(width)),\n height: Math.max(1, Math.round(height)),\n }\n}\n\n/** Fit the model from its unscaled dimensions into the current Pixi screen. */\nfunction layoutModel(\n app: Live2dVendorApp,\n model: Live2dVendorModel,\n sourceSize: Live2dModelSize,\n config: PetLive2dConfig,\n): void {\n const fit = Math.min(\n app.renderer.width / sourceSize.width,\n app.renderer.height / sourceSize.height,\n ) * 0.92\n model.scale.set(fit * (config.scale ?? 1))\n model.anchor.set(0.5)\n model.position.set(\n app.renderer.width / 2 + (config.translate?.x ?? 0),\n app.renderer.height / 2 + (config.translate?.y ?? 0),\n )\n}\n\nlet vendorConfigured = false\n\n/** Configure pixi extensions + the Cubism SDK once per page. */\nfunction configureOnce(vendor: Live2dVendor): void {\n if (vendorConfigured) return\n vendorConfigured = true\n vendor.extensions.add(vendor.Live2DPlugin)\n vendor.configureCubismSDK({ memorySizeMB: 32 })\n}\n\n/** Reset module state (tests). */\nexport function resetLive2dRenderer(): void {\n vendorConfigured = false\n}\n\n/** Fail-closed config validation (contract: unknown manifest block in). */\nfunction validateLive2dConfig(config: unknown): PetLive2dConfig {\n if (typeof config !== 'object' || config === null) throw new Error('live2d config is not an object')\n const source = config as Record<string, unknown>\n if (typeof source.modelUrl !== 'string' || source.modelUrl === '') throw new Error('live2d config modelUrl is required')\n const motions = source.motions\n if (typeof motions !== 'object' || motions === null || typeof (motions as Record<string, unknown>).idle !== 'string') {\n throw new Error('live2d config motions.idle is required')\n }\n return config as PetLive2dConfig\n}\n\n/** The live2d renderer implementation. */\nexport const live2dRenderer: PetRenderer<PetLive2dConfig> = {\n id: 'live2d',\n apiVersion: PET_RENDERER_API_VERSION,\n validateConfig: validateLive2dConfig,\n mount(ctx: PetRendererContext, config: PetLive2dConfig): Live2dRendererHandle {\n let disposed = false\n let app: Live2dVendorApp | undefined\n let model: Live2dVendorModel | undefined\n let modelAttached = false\n let modelSourceSize: Live2dModelSize | undefined\n let resizeObserver: ResizeObserver | undefined\n let resizeTracking = false\n let errorListener: ((code: Live2dErrorCode) => void) | undefined\n let unsubscribe: (() => void) | undefined\n /** The motion group the current phase maps to (resume target after taps). */\n let phaseGroup: string = config.motions.idle\n let tapPlaying = false\n\n const stopResizeTracking = (): void => {\n resizeTracking = false\n resizeObserver?.disconnect()\n resizeObserver = undefined\n }\n\n const resizeRenderer = (pixiApp: Live2dVendorApp, width: number, height: number): void => {\n const next = normalizeRendererSize(width, height)\n if (disposed || !resizeTracking || next === undefined) return\n if (pixiApp.renderer.width === next.width && pixiApp.renderer.height === next.height) return\n pixiApp.renderer.resize(next.width, next.height)\n if (model !== undefined && modelSourceSize !== undefined) {\n layoutModel(pixiApp, model, modelSourceSize, config)\n }\n }\n\n const trackContainerSize = (pixiApp: Live2dVendorApp): void => {\n if (typeof ResizeObserver === 'undefined') return\n resizeTracking = true\n resizeObserver = new ResizeObserver((entries) => {\n const entry = entries.find(candidate => candidate.target === ctx.container)\n if (entry === undefined) return\n resizeRenderer(pixiApp, entry.contentRect.width, entry.contentRect.height)\n })\n resizeObserver.observe(ctx.container)\n // Catch a synchronous layout change between init() and observe().\n resizeRenderer(pixiApp, ctx.container.clientWidth, ctx.container.clientHeight)\n }\n\n /** Release every resource currently owned by this activation exactly once. */\n const destroyResources = (): void => {\n stopResizeTracking()\n unsubscribe?.()\n unsubscribe = undefined\n const currentApp = app\n const currentModel = model\n const modelOwnedByApp = currentApp !== undefined && modelAttached\n app = undefined\n model = undefined\n modelSourceSize = undefined\n modelAttached = false\n try {\n if (currentModel !== undefined && !modelOwnedByApp) currentModel.destroy(DESTROY_OPTIONS)\n } finally {\n currentApp?.destroy(RENDERER_DESTROY_OPTIONS, DESTROY_OPTIONS)\n }\n }\n\n const playGroup = (group: string): void => {\n if (model === undefined) return\n const groups = model.internalModel.settings.motions ?? {}\n const count = Array.isArray(groups[group]) ? groups[group]!.length : 0\n if (count === 0) {\n // A mapped-but-absent group falls back to idle (never blank motion).\n if (group !== config.motions.idle) playGroup(config.motions.idle)\n return\n }\n const index = count > 1 ? Math.floor(Math.random() * count) : 0\n void model.motion(group, index)\n }\n\n const applyPhase = (phase: ActivityPhase): void => {\n phaseGroup = config.motions[phase] ?? config.motions.idle\n playGroup(phaseGroup)\n const expression = config.expressions?.[phase]\n if (expression !== undefined && model !== undefined) void model.expression(expression)\n }\n\n const boot = async (): Promise<void> => {\n if (!await ensureCubismCore()) {\n if (!disposed) errorListener?.('core-missing')\n return\n }\n const vendor = await ensureLive2dVendor()\n if (vendor === undefined) {\n if (!disposed) errorListener?.('vendor-missing')\n return\n }\n configureOnce(vendor)\n const pixiApp = new vendor.Application()\n const initialSize = normalizeRendererSize(ctx.container.clientWidth, ctx.container.clientHeight) ?? {\n width: 160,\n height: 174,\n }\n try {\n await pixiApp.init({\n width: initialSize.width,\n height: initialSize.height,\n backgroundAlpha: 0,\n antialias: true,\n autoDensity: true,\n preference: 'webgl',\n })\n } catch (error) {\n // init() can fail after allocating a partial renderer; cleanup is\n // best-effort because Pixi may not consider that partial app ready.\n try { pixiApp.destroy(RENDERER_DESTROY_OPTIONS, DESTROY_OPTIONS) } catch {}\n throw error\n }\n if (disposed) {\n pixiApp.destroy(RENDERER_DESTROY_OPTIONS, DESTROY_OPTIONS)\n return\n }\n app = pixiApp\n pixiApp.canvas.style.display = 'block'\n pixiApp.canvas.style.width = '100%'\n pixiApp.canvas.style.height = '100%'\n ctx.container.appendChild(pixiApp.canvas)\n // Keep a model that rejects during setup off Ticker.shared; from()\n // does not expose that partial instance to callers for disposal.\n trackContainerSize(pixiApp)\n const loaded = await vendor.Live2DModel.from(config.modelUrl, {\n autoUpdate: false,\n autoHitTest: false,\n autoFocus: false,\n textureOptions: TEXTURE_OPTIONS,\n })\n model = loaded\n if (disposed) {\n destroyResources()\n return\n }\n modelSourceSize = {\n width: Math.max(1, loaded.width),\n height: Math.max(1, loaded.height),\n }\n // Auto-fit the model into the container; the manifest scale multiplies\n // the fit and translate offsets from the center anchor.\n layoutModel(pixiApp, loaded, modelSourceSize, config)\n pixiApp.stage.addChild(loaded)\n modelAttached = true\n loaded.automator.autoUpdate = true\n // Resume the phase group once a tap motion finishes playing.\n loaded.on('motionFinish', () => {\n if (tapPlaying) {\n tapPlaying = false\n playGroup(phaseGroup)\n }\n })\n applyPhase(ctx.phase.get())\n unsubscribe = ctx.phase.subscribe(applyPhase)\n }\n\n void boot().catch(() => {\n try {\n destroyResources()\n } finally {\n if (!disposed) errorListener?.('load-failed')\n }\n })\n\n return {\n dispose() {\n if (disposed) return\n disposed = true\n destroyResources()\n },\n tap(x: number, y: number) {\n const current = model\n if (disposed || current === undefined) return\n const hits = current.hitTest(x, y)\n const allowed = config.hitAreas\n const hit = allowed === undefined ? hits.length > 0 : hits.some(name => allowed.includes(name))\n if (!hit) return\n const groups = current.internalModel.settings.motions ?? {}\n const group = groups[TAP_GROUP]\n if (!Array.isArray(group) || group.length === 0) return\n tapPlaying = true\n const index = group.length > 1 ? Math.floor(Math.random() * group.length) : 0\n void current.motion(TAP_GROUP, index)\n },\n onError(listener: (code: Live2dErrorCode) => void) {\n errorListener = listener\n },\n }\n },\n}\n","/**\n * frames2d renderer — plays the free-form named frame-sequence tracks of a\n * frames2d pet (manifest v2 'frames2d' block). The pet center picks the\n * track from the ActivityPhase stream (phase -> track map, idle fallback);\n * the gameplay driver may force a track through the handle's setState\n * override (drag/work/sleep/shop...), and a finished non-loop track settles\n * into its fallback, releasing the override when the fallback matches the\n * phase-mapped track. Rendering never throws: a broken track list degrades\n * to the first decodable frame, and the 1.2 s stall watchdog re-kicks the\n * playback chain after timer throttling.\n *\n * Frame presentation has two modes picked once at mount by capability\n * probing:\n * - Canvas bitmap buffer (default where createImageBitmap/fetch/2D context\n * exist): frames are decoded once into an ImageBitmap on demand, with a\n * bounded look-ahead window over the playing track, and drawn onto one\n * <canvas>. Steady-state playback issues zero DOM mutations and re-decodes\n * only what the retention budget evicted: decoded frames are held under\n * MAX_RETAINED_BYTES, so a long-lived pet that plays every track of every\n * skin cannot pin every bitmap for the life of the page (measured hotspot:\n * swapping <img>.src per frame drove image decode + invalidation every tick).\n * - Classic <img> fallback (jsdom/tests or missing APIs): identical to the\n * historical behavior - cache-warm Image elements plus guarded src swaps,\n * so environments without modern decoding keep working unchanged.\n *\n * @module @linxin666/dsh-pet/client/renderers/frames2d\n */\n\nimport { PET_RENDERER_API_VERSION, type PetRenderer, type PetRendererContext, type PetRendererHandle } from '../../contracts/renderer.ts'\nimport type { ActivityPhase } from '../../state.ts'\n\n/** One track as served inside the pet definition (browser URLs). */\nexport interface Frames2dTrackConfig {\n frames: string[]\n durations: number[]\n loop: boolean\n fallback?: string\n}\n\n/** The frames2d block as served inside the pet definition. */\nexport interface PetFrames2dConfig {\n tracks: Record<string, Frames2dTrackConfig>\n phases: Partial<Record<ActivityPhase, string>> & { idle: string }\n /** Selectable skins; each swaps the base idle target while selected. */\n skins?: Frames2dSkinConfig[]\n}\n\n/** One selectable skins entry as served inside the pet definition. */\nexport interface Frames2dSkinConfig {\n id: string\n label: string\n /** A declared looping track that becomes the base idle while selected. */\n idleTrack: string\n /** Click actions exclusive to this skin (roll by probability; miss → touch zones). */\n clickActions?: Frames2dSkinClickActionConfig[]\n /** Gameplay-state overrides (state -> track) swapped in while selected. */\n gameplayTracks?: Record<string, string>\n}\n\n/** One probability-rolled tap action a skin may declare. */\nexport interface Frames2dSkinClickActionConfig {\n track: string\n probability: number\n phrases?: string[]\n}\n\nexport interface Frames2dRendererHandle extends PetRendererHandle {\n /** Force a track id (gameplay override); undefined returns to phase mapping. */\n setState(track: string | undefined): void\n /**\n * Swap the base idle target (idle phase, unmapped phases and every\n * fallback back to idle) to a declared looping track — a skin. undefined\n * restores the manifest idle track.\n */\n setIdleTrack(track: string | undefined): void\n /** The track currently playing (diagnostics and tests). */\n currentTrack(): string\n}\n\n/** Stall watchdog period: a looping track stuck longer re-kicks its chain. */\nconst WATCHDOG_MS = 1200\n\n/**\n * Retention budget for decoded frame bitmaps, in bytes.\n *\n * The budget is expressed in bytes rather than in frames because a frame's\n * decoded footprint is `width * height * 4` and published pets differ by more\n * than an order of magnitude (a 512x683 frame is 1.33 MB, a 128x128 frame is\n * 64 KB): a frame count would be either useless for small atlases or too tight\n * for large ones. 128 MiB holds this repository's longest shipped track (78\n * frames, 104 MB) in full, so a running loop still re-decodes nothing, while\n * capping a pet that played every track of every skin at roughly a tenth of\n * the ~1.7 GB the unbounded memo reached.\n */\nconst MAX_RETAINED_BYTES = 128 * 1024 * 1024\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** Fail-closed client-side validation of the served frames2d block. */\nfunction validateFrames2dConfig(config: unknown): PetFrames2dConfig {\n if (!isRecord(config) || !isRecord(config.tracks) || !isRecord(config.phases)) {\n throw new Error('frames2d config requires tracks and phases objects')\n }\n const tracks: Record<string, Frames2dTrackConfig> = {}\n for (const [name, raw] of Object.entries(config.tracks)) {\n if (!isRecord(raw) || !Array.isArray(raw.frames) || raw.frames.length === 0\n || raw.frames.some(f => typeof f !== 'string' || f === '')\n || !Array.isArray(raw.durations) || raw.durations.length !== raw.frames.length\n || raw.durations.some(d => typeof d !== 'number' || !(d > 0))) {\n throw new Error('frames2d track ' + JSON.stringify(name) + ' needs same-length frames/durations')\n }\n tracks[name] = {\n frames: raw.frames as string[],\n durations: raw.durations as number[],\n loop: raw.loop !== false,\n ...(typeof raw.fallback === 'string' ? { fallback: raw.fallback } : {}),\n }\n }\n const phases = config.phases as Partial<Record<ActivityPhase, string>>\n if (typeof phases.idle !== 'string' || tracks[phases.idle] === undefined) {\n throw new Error('frames2d phases.idle must name an existing track')\n }\n // Skins: keep entries whose idleTrack survives validation and loops —\n // a non-looping base idle would settle into itself forever. Click actions\n // with an unresolvable track are dropped from that skin.\n let skins: Frames2dSkinConfig[] | undefined\n if (Array.isArray(config.skins)) {\n const resolved: Frames2dSkinConfig[] = []\n for (const skin of config.skins as unknown[]) {\n if (!isRecord(skin) || typeof skin.id !== 'string' || typeof skin.label !== 'string'\n || typeof skin.idleTrack !== 'string' || skin.idleTrack === '') continue\n const target = tracks[skin.idleTrack]\n if (target === undefined || !target.loop) continue\n let clickActions: Frames2dSkinClickActionConfig[] | undefined\n if (Array.isArray(skin.clickActions)) {\n const kept: Frames2dSkinClickActionConfig[] = []\n for (const action of skin.clickActions as unknown[]) {\n if (!isRecord(action) || typeof action.track !== 'string' || action.track === ''\n || typeof action.probability !== 'number' || !(action.probability > 0) || action.probability > 1) continue\n if (tracks[action.track] === undefined) continue\n kept.push({\n track: action.track,\n probability: action.probability,\n ...(Array.isArray(action.phrases) ? { phrases: action.phrases as string[] } : {}),\n })\n }\n if (kept.length > 0) clickActions = kept\n }\n let gameplayTracks: Record<string, string> | undefined\n if (isRecord(skin.gameplayTracks)) {\n const kept: Record<string, string> = {}\n for (const [state, trackName] of Object.entries(skin.gameplayTracks)) {\n if (typeof trackName !== 'string' || trackName === '' || tracks[trackName] === undefined) continue\n kept[state] = trackName\n }\n if (Object.keys(kept).length > 0) gameplayTracks = kept\n }\n resolved.push({\n id: skin.id,\n label: skin.label,\n idleTrack: skin.idleTrack,\n ...(clickActions === undefined ? {} : { clickActions }),\n ...(gameplayTracks === undefined ? {} : { gameplayTracks }),\n })\n }\n if (resolved.length > 0) skins = resolved\n }\n return { tracks, phases: phases as PetFrames2dConfig['phases'], ...(skins === undefined ? {} : { skins }) }\n}\n\ninterface DecodedFrame {\n source: ImageBitmap | HTMLImageElement\n width: number\n height: number\n}\n\n/**\n * One memoized decode job. `frame` and `bytes` appear only once the job\n * resolved with a frame — exactly the set the retention budget may release;\n * pending and failed jobs carry neither. The owning map's insertion order is\n * the LRU order (re-inserting an entry marks it most recently used).\n */\ninterface DecodeEntry {\n job: Promise<DecodedFrame | undefined>\n frame?: DecodedFrame\n bytes?: number\n}\n\n/**\n * Release one decoded frame. `close()` is browser-only and idempotent, so the\n * call is guarded for exotic hosts and for frames that were already released;\n * the `<img>` fallback has no close, where dropping the reference is the\n * release.\n */\nfunction releaseFrame(frame: DecodedFrame | undefined): void {\n if (frame === undefined) return\n try {\n const maybeClose = (frame.source as { close?: () => void }).close\n if (typeof maybeClose === 'function') maybeClose.call(frame.source)\n } catch { /* already released */ }\n}\n\nexport const frames2dRenderer: PetRenderer<PetFrames2dConfig> = {\n id: 'frames2d',\n apiVersion: PET_RENDERER_API_VERSION,\n validateConfig: validateFrames2dConfig,\n\n mount(ctx: PetRendererContext, config: PetFrames2dConfig): Frames2dRendererHandle {\n const reducedMotion = typeof window !== 'undefined'\n && typeof window.matchMedia === 'function'\n && window.matchMedia('(prefers-reduced-motion: reduce)').matches\n\n // Capability probe: the canvas path needs decode-to-bitmap, same-origin\n // fetch, and a real 2D context (jsdom returns null and falls back below).\n let canvas: HTMLCanvasElement | null = null\n let context2d: CanvasRenderingContext2D | null = null\n let img: HTMLImageElement | null = null\n try {\n if (typeof createImageBitmap === 'function' && typeof fetch === 'function') {\n const probe = document.createElement('canvas')\n const c2d = probe.getContext('2d')\n if (c2d !== null) {\n canvas = probe\n context2d = c2d\n }\n }\n } catch {\n canvas = null\n context2d = null\n }\n\n if (canvas !== null && context2d !== null) {\n canvas.dataset.dshPetFrames2d = ctx.petId\n canvas.draggable = false\n canvas.style.width = '100%'\n canvas.style.height = '100%'\n canvas.style.objectFit = 'contain'\n canvas.style.pointerEvents = 'none'\n ctx.container.appendChild(canvas)\n } else {\n img = document.createElement('img')\n img.dataset.dshPetFrames2d = ctx.petId\n img.alt = ''\n img.draggable = false\n img.style.width = '100%'\n img.style.height = '100%'\n img.style.objectFit = 'contain'\n img.style.pointerEvents = 'none'\n ctx.container.appendChild(img)\n }\n\n // Decode cache: one concurrent decode per URL, retained under a decoded\n // byte budget. The historical map memoized every decoded frame forever, so\n // a pet that had played all of its tracks (every skin) kept every bitmap\n // alive for the life of the page: a shipped three-skin pet measures 1276\n // frames at 512x683 RGBA, about 1.7 GB, growing monotonically. Entries now\n // carry their decoded footprint, sit in Map insertion order (delete + set\n // is an LRU touch) and the least recently used ones outside the playing\n // window are closed once MAX_RETAINED_BYTES is crossed. A failed decode\n // still resolves undefined and leaves the memo, so a transient fetch error\n // retries instead of sticking.\n const decoding = new Map<string, DecodeEntry>()\n let retainedBytes = 0\n // All frame fetches funnel through a small pool. Full-library warm passes\n // on large pets fire 1100+ requests at once, which trips the browser's\n // in-flight request limit (net::ERR_INSUFFICIENT_RESOURCES) and fails\n // whole batches of frames while starving the rest of the page. Playback\n // demand jumps ahead of the warm backlog.\n const FRAME_POOL_LIMIT = 8\n const frameQueue: Array<{ url: string; release: () => void }> = []\n let activeFrames = 0\n\n const decodeFrame = async (url: string): Promise<DecodedFrame | undefined> => {\n try {\n const response = await fetch(url)\n if (!response.ok) throw new Error('http ' + response.status)\n const bitmap = await createImageBitmap(await response.blob())\n return { source: bitmap, width: bitmap.width, height: bitmap.height }\n } catch {\n // Fail-open: classic Image decode keeps non-modern runtimes alive.\n return await new Promise<DecodedFrame | undefined>((resolve) => {\n try {\n const pre = new Image()\n pre.onload = (): void => {\n resolve(pre.naturalWidth > 0 ? { source: pre, width: pre.naturalWidth, height: pre.naturalHeight } : undefined)\n }\n pre.onerror = (): void => resolve(undefined)\n pre.src = url\n } catch {\n resolve(undefined)\n }\n })\n }\n }\n\n const pumpFrames = (): void => {\n while (activeFrames < FRAME_POOL_LIMIT && frameQueue.length > 0) {\n const queued = frameQueue.shift()!\n activeFrames += 1\n queued.release()\n }\n }\n\n const loadFrame = (url: string, jump = false): Promise<DecodedFrame | undefined> => {\n // Jump first: warm-enqueued frames already carry their memo, so a\n // playback demand must reorder the unstarted entry before the cache\n // lookup short-circuits.\n if (jump) {\n const index = frameQueue.findIndex((queued) => queued.url === url)\n if (index > 0) frameQueue.unshift(frameQueue.splice(index, 1)[0]!)\n }\n const cached = decoding.get(url)\n if (cached !== undefined) {\n // LRU touch: a hit means playback just asked for this frame, so it must\n // not be the next victim. Re-inserting the same entry only reorders.\n decoding.delete(url)\n decoding.set(url, cached)\n return cached.job\n }\n let release!: () => void\n const gate = new Promise<void>((resolve) => { release = resolve })\n const job: Promise<DecodedFrame | undefined> = gate.then(() => (disposed ? undefined : decodeFrame(url)))\n const entry: DecodeEntry = { job }\n job.then(\n (frame) => {\n if (frame === undefined) {\n decoding.delete(url)\n return\n }\n // A decode that lands after dispose is closed here: nothing can close\n // it later, and the map was already drained.\n if (disposed) {\n releaseFrame(frame)\n decoding.delete(url)\n return\n }\n entry.frame = frame\n entry.bytes = frame.width * frame.height * 4\n retainedBytes += entry.bytes\n // Only a resolved frame is evictable, and its decoded size is known\n // only now, so the budget is enforced here.\n enforceRetentionBudget()\n },\n () => decoding.delete(url),\n )\n void job.finally(() => {\n activeFrames -= 1\n pumpFrames()\n })\n decoding.set(url, entry)\n const queued = { url, release }\n if (jump) frameQueue.unshift(queued)\n else frameQueue.push(queued)\n pumpFrames()\n return job\n }\n\n /**\n * Release decoded bitmaps until the retained footprint is back under\n * MAX_RETAINED_BYTES. Two properties keep this from breaking playback:\n *\n * - The playing track's look-ahead window, plus the frame a draw is waiting\n * on, are never released. Releasing one would hand a closed bitmap to\n * `drawImage`, and re-decoding it would stall the next tick.\n * - Frames of any other track go first. That is what keeps a running loop\n * warm under a budget smaller than two whole tracks: eviction reclaims the\n * track the pet left instead of eating the cycle it is playing.\n *\n * When the protected window alone exceeds the budget nothing is released —\n * a pet whose frames are that large cannot be bounded further without\n * breaking playback, and the overshoot is then exactly one window.\n */\n function enforceRetentionBudget(): void {\n if (retainedBytes <= MAX_RETAINED_BYTES) return\n const def = config.tracks[track]\n const playing = new Set<string>(def === undefined ? [] : def.frames)\n const protectedUrls = new Set<string>()\n if (pinned !== undefined) protectedUrls.add(pinned)\n if (def !== undefined) {\n const end = Math.min(def.frames.length, frameIndex + 1 + PREFETCH_AHEAD)\n for (let index = frameIndex; index < end; index += 1) {\n const url = def.frames[index]\n if (url !== undefined) protectedUrls.add(url)\n }\n }\n // Pass 1 reclaims frames of tracks the pet is not playing; pass 2 is the\n // backstop for a single track larger than the whole budget.\n for (const foreignOnly of [true, false]) {\n for (const [url, entry] of decoding) {\n if (retainedBytes <= MAX_RETAINED_BYTES) return\n if (entry.bytes === undefined || protectedUrls.has(url)) continue\n if (foreignOnly && playing.has(url)) continue\n releaseFrame(entry.frame)\n retainedBytes -= entry.bytes\n decoding.delete(url)\n }\n }\n }\n\n /**\n * Bounded look-ahead window: decode only the frames playback is about to\n * need. The historical warm pass decoded every frame of every track up\n * front - a shipped pet carries ~1.1k 512x683 frames, so that pass pulls\n * tens of megabytes and retains every decoded bitmap for the life of the\n * page. Prefetching the playing track's next frames keeps loops and phase\n * switches warm while unplayed tracks (and every unselected skin's\n * frames) stay on demand, where playback jumps the queue anyway.\n */\n const PREFETCH_AHEAD = 12\n\n const prefetchAhead = (trackId: string, index: number): void => {\n const def = config.tracks[trackId]\n if (def === undefined) return\n const end = Math.min(def.frames.length, index + 1 + PREFETCH_AHEAD)\n for (let ahead = index + 1; ahead < end; ahead += 1) {\n const url = def.frames[ahead]\n if (url !== undefined) void loadFrame(url)\n }\n }\n\n let disposed = false\n let timer: ReturnType<typeof setTimeout> | undefined\n let watchdog: ReturnType<typeof setInterval> | undefined\n let track: string = config.phases.idle\n let frameIndex = 0\n let lastAdvance = Date.now()\n let override: string | undefined\n // Skin base idle: every \"back to idle\" target resolves through this\n // (idle phase, unmapped phases and fallbacks), so a selected skin swaps\n // the pet's resting look without touching gameplay tracks.\n let baseIdle: string = config.phases.idle\n let drawToken = 0\n let lastDrawnUrl: string | undefined\n // The frame a draw is currently awaiting. Eviction must not release it:\n // the callback below holds the bitmap and would draw a closed one.\n let pinned: string | undefined\n\n const trackForPhase = (phase: ActivityPhase): string => {\n const mapped = config.phases[phase]\n if (mapped === undefined) return baseIdle\n const target = mapped === config.phases.idle ? baseIdle : mapped\n return config.tracks[target] !== undefined ? target : baseIdle\n }\n\n /** Canvas path: paints the newest requested frame; stale draws drop out. */\n const paintCanvas = (url: string): void => {\n if (context2d === null || canvas === null) return\n const myToken = ++drawToken\n pinned = url\n void loadFrame(url, true).then((frame) => {\n if (pinned === url) pinned = undefined\n if (disposed || frame === undefined || myToken !== drawToken) return\n if (lastDrawnUrl === url) return\n lastDrawnUrl = url\n // Resizing clears the canvas, so size only when it actually differs.\n if (canvas.width !== frame.width || canvas.height !== frame.height) {\n canvas.width = frame.width\n canvas.height = frame.height\n } else {\n context2d.clearRect(0, 0, canvas.width, canvas.height)\n }\n context2d.drawImage(frame.source as CanvasImageSource, 0, 0)\n }).catch(() => { if (pinned === url) pinned = undefined /* keep last frame */ })\n }\n\n const show = (trackId: string, index: number): void => {\n const def = config.tracks[trackId]\n const url = def?.frames[index]\n if (url === undefined) return\n prefetchAhead(trackId, index)\n if (img !== null) {\n if (img.getAttribute('src') !== url) img.src = url\n return\n }\n paintCanvas(url)\n }\n\n const schedule = (ms: number): void => {\n if (disposed) return\n timer = setTimeout(tick, ms)\n }\n\n function tick(): void {\n if (disposed) return\n const def = config.tracks[track]\n if (def === undefined || def.frames.length === 0) return\n lastAdvance = Date.now()\n const next = frameIndex + 1\n if (next < def.frames.length) {\n frameIndex = next\n show(track, frameIndex)\n schedule(def.durations[frameIndex] ?? 200)\n return\n }\n if (def.loop) {\n frameIndex = 0\n show(track, frameIndex)\n schedule(def.durations[frameIndex] ?? 200)\n return\n }\n // Non-loop completion: settle into the fallback — an explicit fallback to\n // a real track wins, except when it points back at the manifest idle\n // (that resolves through the skin base idle); anything else lands on\n // the skin base idle. When the settle target is what the phase map\n // plays anyway, release the gameplay override.\n const target = def.fallback !== undefined && config.tracks[def.fallback] !== undefined\n ? (def.fallback === config.phases.idle ? baseIdle : def.fallback)\n : baseIdle\n if (target === trackForPhase(ctx.phase.get())) override = undefined\n play(target)\n }\n\n function play(trackId: string): void {\n if (disposed) return\n if (config.tracks[trackId] === undefined) trackId = baseIdle\n if (timer !== undefined) clearTimeout(timer)\n track = trackId\n frameIndex = 0\n lastAdvance = Date.now()\n show(track, frameIndex)\n if (reducedMotion) return\n const def = config.tracks[track]!\n schedule(def.durations[0] ?? 200)\n }\n\n const unsubscribe = ctx.phase.subscribe((phase) => {\n if (override !== undefined) return\n const target = trackForPhase(phase)\n if (target !== track) play(target)\n })\n\n // Watchdog: a throttled-away timer (background tab) leaves the chain\n // dead; re-kick when a looping track has not advanced on schedule.\n if (!reducedMotion) {\n watchdog = setInterval(() => {\n if (disposed) return\n const def = config.tracks[track]\n if (def === undefined || !def.loop) return\n const expected = (def.durations[frameIndex] ?? 200) + WATCHDOG_MS\n if (Date.now() - lastAdvance > expected) tick()\n }, WATCHDOG_MS)\n }\n\n play(track)\n\n let disposedOnce = false\n const dispose = (): void => {\n if (disposedOnce) return\n disposedOnce = true\n disposed = true\n unsubscribe()\n if (timer !== undefined) clearTimeout(timer)\n if (watchdog !== undefined) clearInterval(watchdog)\n // Release every retained bitmap and drain the pool. Queued-but-unstarted\n // frames resolve as no-ops (the gate skips decodeFrame once disposed), and\n // a decode that lands after this loop is closed by the resolution guard\n // above, so teardown leaves nothing pending and nothing retained.\n for (const queued of frameQueue.splice(0)) queued.release()\n for (const entry of decoding.values()) releaseFrame(entry.frame)\n decoding.clear()\n retainedBytes = 0\n canvas?.remove()\n img?.remove()\n }\n ctx.onCleanup(dispose)\n\n return {\n dispose,\n setState(next: string | undefined): void {\n if (disposed) return\n if (next === undefined) {\n override = undefined\n const target = trackForPhase(ctx.phase.get())\n if (target !== track) play(target)\n return\n }\n if (config.tracks[next] === undefined) return\n override = next\n if (next !== track) play(next)\n },\n setIdleTrack(next: string | undefined): void {\n if (disposed) return\n if (next === undefined || (config.tracks[next] !== undefined && config.tracks[next]!.loop)) {\n baseIdle = next ?? config.phases.idle\n }\n // A skin only owns the resting look: re-resolve only when no\n // gameplay override is active (active overrides end into baseIdle).\n if (override === undefined) {\n const target = trackForPhase(ctx.phase.get())\n if (target !== track) play(target)\n }\n },\n currentTrack(): string {\n return track\n },\n }\n },\n}\n","/**\n * Cross-bundle-instance teardown slot for the page-global pet root\n * (issue #785).\n *\n * A client bundle swap (HMR rebuilt frame, plugin update, duplicate\n * injection) runs a new apply body while the previous instance's fiber\n * may still be draining. Module state does not survive the swap, so a\n * closure guard only sees one apply body and the previous instance's\n * container keeps sitting on document.body: the page shows two pets\n * until a full refresh. The slot rides globalThis (which does survive)\n * so a re-apply can find the previous instance and unmount its React\n * root cleanly before mounting its own; the previous fiber's later\n * disposal stays a no-op through the idempotent teardowns.\n */\n\nconst SLOT = Symbol.for('dsh-pet.client-ui-teardown')\n\ninterface TeardownSlot {\n [SLOT]?: (() => void) | undefined\n}\n\n/**\n * Claim the page-global pet UI slot with the current instance's teardown\n * (React root unmount + container removal + poll stop).\n * @param teardown - what a later instance runs to take the slot over.\n * @returns a disposer that clears the slot when the current instance's\n * UI is torn down (settings toggle, takeover, or fiber disposal).\n */\nexport function registerPetUiTeardown(teardown: () => void): () => void {\n const slot = globalThis as TeardownSlot\n slot[SLOT] = teardown\n return () => {\n if (slot[SLOT] === teardown) slot[SLOT] = undefined\n }\n}\n\n/**\n * Run the previous instance's teardown if one is registered, so the\n * re-applying instance becomes the sole owner of the page-global pet\n * root. No-op when the previous fiber already tore down cleanly.\n */\nexport function takeoverPetUiTeardown(): void {\n const slot = globalThis as TeardownSlot\n const teardown = slot[SLOT]\n slot[SLOT] = undefined\n teardown?.()\n}\n","/**\n * Coarse adjustment for a bounded number: resting the pointer on the control\n * (or moving focus into it) raises a small bubble holding a slider across the\n * field's whole range, so a large change is one drag instead of many presses\n * or a retyped value. The control itself stays the precise entry.\n *\n * The bubble belongs to the anchor's subtree, so moving from the control onto\n * the bubble never counts as leaving. It opens after a short rest and closes a\n * moment after the pointer and focus have both gone, so crossing the control\n * on the way elsewhere does not flash it. While a drag is in progress the\n * bubble stays put even if the pointer strays off it.\n *\n * Dragging reports each value through `onInput`, so the field shows it live;\n * releasing the thumb, or a key press on it, reports `onCommit` once. The\n * bubble opens on the side of the control that has room inside the nearest\n * scrolling ancestor, so a row near the top of a settings page does not hang\n * its bubble under the page edge.\n */\n\nimport { useEffect, useRef, useState, type ChangeEvent, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react'\nimport css from './settings-card.module.css'\n\n/** Rest on the control before the bubble opens. */\nconst OPEN_DELAY_MS = 220\n/** Grace after pointer and focus have left before the bubble closes. */\nconst CLOSE_DELAY_MS = 200\n/** Room the bubble needs between the control and the scroller's edge. */\nconst BUBBLE_ROOM_PX = 64\n\n/** Props of {@link RangeBubble}. */\nexport interface RangeBubbleProps {\n /** Lowest value the slider reaches. */\n min: number\n /** Highest value the slider reaches. */\n max: number\n /** Slider granularity. */\n step: number\n /** Current value; a value outside the range parks the thumb at the nearer end. */\n value: number\n /** Accessible name of the slider. */\n label: string\n /** Disables the bubble along with the control. */\n disabled?: boolean\n /** Each value while the thumb moves. */\n onInput: (value: number) => void\n /** The value the thumb was released on, once per drag or key press. */\n onCommit: (value: number) => void\n /** The precise control the bubble hangs off. */\n children: ReactNode\n}\n\n/** The nearest ancestor that scrolls vertically, or the viewport's root. */\nfunction scroller(node: HTMLElement): HTMLElement {\n for (let parent = node.parentElement; parent !== null; parent = parent.parentElement) {\n const overflow = getComputedStyle(parent).overflowY\n if (overflow === 'auto' || overflow === 'scroll') return parent\n }\n return node.ownerDocument.documentElement\n}\n\n/**\n * Render the control with its coarse-adjustment bubble.\n * @param props - the range, the value and the two report callbacks.\n * @returns the anchor holding the control and the bubble.\n */\nexport function RangeBubble(props: RangeBubbleProps): ReactNode {\n const { min, max, step, disabled = false } = props\n const [open, setOpen] = useState(false)\n const [side, setSide] = useState<'above' | 'below'>('above')\n const [live, setLive] = useState<number | null>(null)\n const anchorRef = useRef<HTMLDivElement | null>(null)\n const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)\n const hovered = useRef(false)\n const focused = useRef(false)\n const dragging = useRef(false)\n\n useEffect(() => () => { clearTimeout(timer.current) }, [])\n useEffect(() => {\n if (disabled) {\n clearTimeout(timer.current)\n setOpen(false)\n }\n }, [disabled])\n\n const show = (): void => {\n const anchor = anchorRef.current\n if (anchor !== null) {\n const room = anchor.getBoundingClientRect().top - scroller(anchor).getBoundingClientRect().top\n setSide(room >= BUBBLE_ROOM_PX ? 'above' : 'below')\n }\n setOpen(true)\n }\n const schedule = (): void => {\n clearTimeout(timer.current)\n if (disabled) return\n if (hovered.current || focused.current || dragging.current) {\n if (!open) timer.current = setTimeout(show, focused.current ? 0 : OPEN_DELAY_MS)\n return\n }\n timer.current = setTimeout(() => { setOpen(false) }, CLOSE_DELAY_MS)\n }\n\n const commit = (value: number): void => {\n dragging.current = false\n setLive(null)\n props.onCommit(value)\n schedule()\n }\n const onChange = (event: ChangeEvent<HTMLInputElement>): void => {\n const value = Number(event.target.value)\n setLive(value)\n props.onInput(value)\n }\n const onKeyUp = (event: KeyboardEvent<HTMLInputElement>): void => {\n if (live !== null) commit(live)\n if (event.key === 'Escape') {\n clearTimeout(timer.current)\n setOpen(false)\n }\n }\n const shown = live ?? Math.min(max, Math.max(min, props.value))\n\n return (\n <div\n ref={anchorRef}\n className={css.rangeAnchor}\n onPointerEnter={() => { hovered.current = true; schedule() }}\n onPointerLeave={() => { hovered.current = false; schedule() }}\n onFocus={() => { focused.current = true; schedule() }}\n onBlur={(event) => {\n if (event.currentTarget.contains(event.relatedTarget as Node | null)) return\n focused.current = false\n if (live !== null) commit(live)\n else schedule()\n }}\n >\n {props.children}\n <div className={css.rangeBubble} data-open={open ? '' : undefined} data-side={side}>\n <input\n type=\"range\"\n className={css.rangeSlider}\n min={min}\n max={max}\n step={step}\n value={shown}\n aria-label={props.label}\n tabIndex={open ? 0 : -1}\n disabled={disabled}\n style={{ '--range-fill': `${((shown - min) / (max - min)) * 100}%` } as CSSProperties}\n onPointerDown={() => { dragging.current = true }}\n onPointerUp={(event) => { commit(Number(event.currentTarget.value)) }}\n onPointerCancel={(event) => { commit(Number(event.currentTarget.value)) }}\n onChange={onChange}\n onKeyUp={onKeyUp}\n />\n <span className={css.rangeEnds} aria-hidden=\"true\">\n <span>{min}</span>\n <span>{max}</span>\n </span>\n </div>\n </div>\n )\n}\n","/**\n * The family's segmented control: a quiet track whose options share one\n * highlight that slides to the pressed option, instead of each option fading\n * its own background out and the next one in. The settings fields' small\n * choices and the Web Extensions TAB strip both render through it, so the two\n * read as one control.\n *\n * The caller builds the option buttons and marks the pressed one with\n * `data-active`; the group measures that button after every render and writes\n * its box as four custom properties, and the stylesheet draws the highlight\n * there (`.segmentGroup[data-pill]::before`). Attribute and first placement\n * land in the same task, so the highlight appears in place and only later\n * changes slide. A ResizeObserver re-measures when the group or an option\n * changes size: a longer locale, a font arriving, a container growing, a\n * strip wrapping onto a second line.\n */\n\nimport { Children, useLayoutEffect, useRef, type HTMLAttributes, type ReactNode } from 'react'\nimport css from './settings-card.module.css'\n\n/** The attribute marking a group whose highlight has been placed. */\nconst PILL_ATTR = 'data-pill'\n/** The pressed option, relative to the group. */\nconst ACTIVE_SELECTOR = ':scope > [data-active]'\nconst PILL_PROPERTIES = ['--segment-pill-x', '--segment-pill-y', '--segment-pill-w', '--segment-pill-h'] as const\n\n/** Props of {@link SegmentGroup}: the track's own attributes and the option buttons. */\nexport interface SegmentGroupProps extends HTMLAttributes<HTMLDivElement> {\n /** The option buttons; the pressed one carries `data-active`. */\n children: ReactNode\n}\n\n/**\n * Write the highlight's box from the pressed option's box, or take the\n * highlight off when nothing is pressed or the group has no layout yet.\n * The two boxes are read in viewport pixels and turned back into the group's\n * own CSS pixels, so a dialog that opens through a scale transform still\n * lands the highlight on its option.\n */\nfunction placePill(group: HTMLElement): void {\n const item = group.querySelector<HTMLElement>(ACTIVE_SELECTOR)\n const box = group.getBoundingClientRect()\n if (item === null || group.offsetWidth === 0 || box.width === 0) {\n group.removeAttribute(PILL_ATTR)\n for (const property of PILL_PROPERTIES) group.style.removeProperty(property)\n return\n }\n const scale = box.width / group.offsetWidth\n const itemBox = item.getBoundingClientRect()\n const values = [\n (itemBox.left - box.left) / scale - group.clientLeft,\n (itemBox.top - box.top) / scale - group.clientTop,\n itemBox.width / scale,\n itemBox.height / scale,\n ]\n values.forEach((value, index) => {\n group.style.setProperty(PILL_PROPERTIES[index], `${Math.round(value * 100) / 100}px`)\n })\n if (!group.hasAttribute(PILL_ATTR)) group.setAttribute(PILL_ATTR, '')\n}\n\n/**\n * Render a segmented track around the caller's option buttons.\n * @param props - the track's attributes (role, accessible name, key handler) and its options.\n * @returns the track.\n */\nexport function SegmentGroup(props: SegmentGroupProps): ReactNode {\n const { children, className, ...rest } = props\n const group = useRef<HTMLDivElement | null>(null)\n const count = Children.count(children)\n\n // Placed before the frame is painted, after every render: a press moves the\n // pressed mark and the highlight follows it in the same frame.\n useLayoutEffect(() => {\n if (group.current !== null) placePill(group.current)\n })\n\n useLayoutEffect(() => {\n const element = group.current\n if (element === null || typeof ResizeObserver === 'undefined') return undefined\n const observer = new ResizeObserver(() => { placePill(element) })\n observer.observe(element)\n for (const item of Array.from(element.children)) observer.observe(item)\n return () => { observer.disconnect() }\n }, [count])\n\n return (\n <div {...rest} ref={group} className={className === undefined ? css.segmentGroup : `${css.segmentGroup} ${className}`}>\n {children}\n </div>\n )\n}\n","/**\n * Family-shared chrome for plugin settings cards: a disclosure header naming\n * the plugin and what its settings govern, the controls inside, and the line\n * that reports a refused write. A pick is written the moment it is made and a\n * typed value after a pause, so the card has no save button and nothing waits\n * on the reader. Renders nothing while the namespace is unavailable — a\n * deployment that does not compose the owning plugin should show no trace of\n * it. Inlined into each consumer's client bundle; mirrors the official\n * ui-plugin-config PluginCard in a self-contained slice.\n *\n * Every field inside the body is one settings row: the label and its hint on\n * the left, the control on the right, a hairline between two rows; a narrow\n * card stacks the control under the text (settings-card.module.css).\n */\n\nimport { createContext, useCallback, useContext, useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode } from 'react'\nimport type { CardShell } from './settings-form.ts'\nimport { RangeBubble } from './RangeBubble.tsx'\nimport { SegmentGroup } from './SegmentGroup.tsx'\nimport css from './settings-card.module.css'\n\n/** Copy keys the card chrome itself reads; every consumer locale carries this shared vocabulary. */\nexport const CARD_COPY_KEYS = [\n 'settings.collapse',\n 'settings.expand',\n 'settings.notExposed',\n 'settings.readOnly',\n 'settings.saveFailed',\n] as const\n\n/**\n * What a text field inside a card reaches without its plugin wiring it: write\n * the pending draft now (Enter, leaving the field) or put it back (Escape).\n * Picks need neither; they are written the moment they are made.\n */\nconst CardApply = createContext<{ commit(): void, revert(): void } | null>(null)\n\n/** Copy key the card chrome itself reads. */\nexport type CardCopyKey = (typeof CARD_COPY_KEYS)[number]\n\n/** Key domain for the plugin's own copy (inferred per consumer). */\nexport type SettingsCardKey<TKey extends string = string> = TKey | CardCopyKey\n\n/** Card chrome shared by every plugin settings card. */\nexport interface PluginSettingsCardProps<TKey extends string = string> {\n /** Locale reader for this card's copy. */\n t: (key: SettingsCardKey<TKey>, params?: Record<string, string | number>) => string\n /** Locale key of the plugin's name. */\n titleKey: TKey\n /** Locale key of the line describing what this plugin's settings govern. */\n descriptionKey: TKey\n /** Optional rich header description rendered instead of the plain t(descriptionKey) text (the plain text stays as the tooltip). */\n descriptionNode?: ReactNode\n /**\n * Locale key of the full sentence behind a shortened description: when\n * present, the header's native `title` takes this text while the visible\n * line keeps `descriptionKey`/`descriptionNode`, so a compact card can\n * compress the sentence without keeping a second visible copy of it.\n * Defaults to the description key.\n */\n descriptionTitleKey?: TKey\n /**\n * Optional leading mark identifying the plugin. A card without one keeps the\n * plain official header shape, so the chrome stays a readable sibling of the\n * built-in PluginCard wherever a family plugin lands in the official bundle\n * seat.\n */\n icon?: ReactNode\n /** The card's form state: availability, writability, and how the last write went. */\n state: CardShell\n /** Write every pending draft now: a text field's Enter or blur. */\n onSave: () => void\n /** Drop every pending draft: a text field's Escape. */\n onDiscard: () => void\n /**\n * Id applied to the card's title element, so a header control (an immediate\n * toggle in `headerAction`) can name itself through `aria-labelledby`\n * instead of repeating the title as a string.\n */\n titleId?: string\n /**\n * Render the header only, with no body region. A card whose whole setting is\n * the header control (a switch whose explanation is the description) has no\n * controls to lay out below it, and an empty body would draw a divider line\n * with nothing under it.\n */\n headerOnly?: boolean\n /**\n * Render the controls expanded on arrival (still collapsible). Defaults to\n * true: promoted first-level sections show their settings immediately.\n */\n defaultOpen?: boolean\n /**\n * Render without the collapse affordance: a static header and an always\n * visible body. Used by first-level settings sections whose nav entry\n * already provides the selection.\n */\n alwaysOpen?: boolean\n /**\n * Hide the line under the body that reports a refused write: a card whose\n * body applies its own changes (an embedded external settings section)\n * reports its own failures.\n */\n hideFooter?: boolean\n /**\n * Optional control rendered at the header's trailing edge, before the\n * chevron. A card whose setting is one immediate flip (it\n * applies outside the card's form) puts its ToggleSwitch here, so the control\n * is reachable without opening the card and matches a plugin card's shape.\n */\n headerAction?: ReactNode\n /** Render children even when the settings namespace is not exposed by the host. */\n renderChildrenWhenNotExposed?: boolean\n /** Hide the 'not exposed' warning banner when the settings namespace is not exposed. */\n hideNotExposedNotice?: boolean\n /**\n * Compact chrome for a topic card rendered inside another card's body: a\n * smaller title, a tighter header and body inset, and a one-line description\n * whose full text stays on the header's own title. Defaults to the\n * first-level chrome, which is unchanged.\n */\n density?: 'nested'\n /** The plugin's controls. */\n children: ReactNode\n}\n\n/** Length of the body's disclosure motion; it matches `--settings-card-motion` on the card root. */\nconst BODY_MOTION_MS = 180\n\n/**\n * Lifecycle of one card body. `collapsed` is the mounted-but-closed frame the\n * enter leg starts from, `entering` and `closing` are the two moving legs, and\n * `shown` is the settled open body, which releases its clipping box.\n */\ntype BodyPhase = 'hidden' | 'collapsed' | 'entering' | 'shown' | 'closing'\n\n/**\n * Render one plugin settings card.\n * @param props - the plugin's copy keys, its form state, and its controls.\n * @returns the card, or nothing while the namespace is still loading.\n */\nexport function PluginSettingsCard<TKey extends string = string>(props: PluginSettingsCardProps<TKey>) {\n const [open, setOpen] = useState(props.defaultOpen ?? true)\n const { state, alwaysOpen } = props\n const expanded = alwaysOpen === true || open\n const [bodyPhase, setBodyPhase] = useState<BodyPhase>(expanded ? 'shown' : 'hidden')\n const bodyRef = useRef<HTMLDivElement | null>(null)\n // Enter and leave run the same pair: a body that should open is mounted\n // closed for one frame so its transition has a state to leave, and a closing\n // one stays mounted until its leg has run.\n useLayoutEffect(() => {\n if (expanded) {\n if (bodyPhase === 'hidden') setBodyPhase('collapsed')\n else if (bodyPhase === 'collapsed') {\n const node = bodyRef.current\n if (node !== null) void node.offsetHeight\n setBodyPhase('entering')\n } else if (bodyPhase === 'closing') setBodyPhase('entering')\n return\n }\n if (bodyPhase === 'collapsed') setBodyPhase('hidden')\n else if (bodyPhase === 'entering' || bodyPhase === 'shown') setBodyPhase('closing')\n }, [expanded, bodyPhase])\n useEffect(() => {\n if (bodyPhase !== 'entering' && bodyPhase !== 'closing') return\n const timer = setTimeout(() => {\n setBodyPhase(bodyPhase === 'entering' ? 'shown' : 'hidden')\n }, BODY_MOTION_MS)\n return () => { clearTimeout(timer) }\n }, [bodyPhase])\n if (!state.available) return null\n const title = props.t(props.titleKey)\n const description = props.t(props.descriptionKey)\n const descriptionTitle = props.descriptionTitleKey === undefined ? description : props.t(props.descriptionTitleKey)\n const baseClass = expanded ? `${css.cardOpen} ${css.card}` : css.card\n const cardClass = props.density === 'nested' ? `${baseClass} ${css.cardNested}` : baseClass\n /** The body region both legs share; a hidden phase renders nothing at all. */\n const bodyRegion = (content: ReactNode) => bodyPhase === 'hidden'\n ? null\n : (\n <div className={css.disclosure} data-state={bodyPhase} ref={bodyRef}>\n <div className={css.body}>{content}</div>\n </div>\n )\n // With alwaysOpen the nav entry already provides the selection, so the\n // header is a static title row instead of a disclosure button.\n const header = alwaysOpen === true\n ? (\n <div className={css.headerStatic}>\n {props.icon !== undefined ? <span className={css.mark} aria-hidden=\"true\">{props.icon}</span> : null}\n <span className={css.headText}>\n <span className={css.name} id={props.titleId} title={title}>{title}</span>\n <span className={css.description} title={descriptionTitle}>{props.descriptionNode ?? description}</span>\n </span>\n {props.headerAction !== undefined ? <span className={css.headerAction}>{props.headerAction}</span> : null}\n </div>\n )\n : (\n <button\n type=\"button\"\n className={css.header}\n aria-expanded={open}\n aria-label={`${props.t(open ? 'settings.collapse' : 'settings.expand')}: ${title}`}\n onClick={() => { setOpen(!open) }}\n >\n {props.icon !== undefined ? <span className={css.mark} aria-hidden=\"true\">{props.icon}</span> : null}\n <span className={css.headText}>\n <span className={css.name} id={props.titleId} title={title}>{title}</span>\n <span className={css.description} title={descriptionTitle}>{props.descriptionNode ?? description}</span>\n </span>\n {props.headerAction !== undefined ? <span className={css.headerAction}>{props.headerAction}</span> : null}\n <svg\n width=\"14\"\n height=\"14\"\n viewBox=\"0 0 14 14\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n className={open ? `${css.chevron} ${css.chevronOpen}` : css.chevron}\n >\n <path\n d=\"M11.8486 5.5L11.4238 5.92383L8.69727 8.65137C8.44157 8.90706 8.21562 9.13382 8.01172 9.29785C7.79912 9.46883 7.55595 9.61756 7.25 9.66602C7.08435 9.69222 6.91565 9.69222 6.75 9.66602C6.44405 9.61756 6.20088 9.46883 5.98828 9.29785C5.78438 9.13382 5.55843 8.90706 5.30273 8.65137L2.57617 5.92383L2.15137 5.5L3 4.65137L3.42383 5.07617L6.15137 7.80273C6.42595 8.07732 6.59876 8.24849 6.74023 8.3623C6.87291 8.46904 6.92272 8.47813 6.9375 8.48047C6.97895 8.48703 7.02105 8.48703 7.0625 8.48047C7.07728 8.47813 7.12709 8.46904 7.25977 8.3623C7.40124 8.24849 7.57405 8.07732 7.84863 7.80273L10.5762 5.07617L11 4.65137L11.8486 5.5Z\"\n fill=\"currentColor\"\n />\n </svg>\n </button>\n )\n // The namespace exists but the Host does not serve it to this client (the\n // official settings allowlist omits third-party namespaces): show a card\n // that explains the gap instead of vanishing, so a missing card never\n // reads as a missing plugin.\n if (!state.exposed && props.renderChildrenWhenNotExposed !== true) {\n const showNotice = props.hideNotExposedNotice !== true\n return (\n <li className={cardClass}>\n {header}\n {bodyRegion(showNotice ? <p className={css.notExposed} role=\"status\">{props.t('settings.notExposed')}</p> : null)}\n </li>\n )\n }\n // A header-only card has no body region at all: the divider would otherwise\n // sit above an empty box.\n const bodyVisible = props.headerOnly !== true\n return (\n <li className={cardClass}>\n {header}\n {bodyVisible\n ? bodyRegion(\n <>\n {!state.writable ? <p className={css.readOnly} role=\"status\">{props.t('settings.readOnly')}</p> : null}\n <CardApply.Provider value={{ commit: props.onSave, revert: props.onDiscard }}>\n {props.children}\n </CardApply.Provider>\n {props.hideFooter !== true && state.failed\n ? (\n <p className={css.failed} role=\"status\">\n {props.t('settings.saveFailed')}{state.failedReason ? ' - ' + state.failedReason : ''}\n </p>\n )\n : null}\n </>,\n )\n : null}\n </li>\n )\n}\n\n/** Props every field control needs regardless of its value type. */\nexport interface FieldProps {\n /** Stable id associating the label with its control. */\n id: string\n /** Visible label. */\n label: string\n /** One-line explanation rendered under the control. */\n hint: string\n /**\n * Full sentence behind the visible hint, exposed as the paragraph's native\n * `title` so a card can shorten the line without losing the text. Omitted:\n * the paragraph carries no title attribute at all.\n */\n hintTitle?: string\n /** Draft text this control renders. */\n text: string\n /** True when the field holds a user-layer entry over the inherited value. */\n overridden: boolean\n /** True when the draft is not a value this field accepts. */\n invalid: boolean\n /** Copy for the overridden badge. */\n overriddenLabel: string\n /** Copy for the reset control. */\n resetLabel: string\n /** Copy shown in place of the hint while the draft is invalid. */\n invalidLabel: string\n /** Disables every control (read-only document, or an unavailable namespace). */\n disabled: boolean\n /** Take new draft text; the card writes it as the field's entry rule says. */\n onEdit: (text: string) => void\n /** Clear the field at once so it re-inherits the composition layer. */\n onReset: () => void\n}\n\n/**\n * A typed value field. Its draft is written after a pause in typing, at once on\n * Enter or when focus leaves, and Escape puts the stored value back. `numeric`\n * only hints the keypad: which drafts a field accepts is decided by its spec.\n * A field given a `range` also offers the coarse slider bubble: dragging fills\n * the draft live and releasing writes it.\n */\nexport function ValueField(props: FieldProps & {\n /** Hints a numeric keypad without narrowing what the control accepts. */\n numeric?: boolean\n /** Placeholder shown while the draft is empty. */\n placeholder?: string\n /** Bounds of a numeric field, for the coarse slider; the spec still judges every draft. */\n range?: { min: number, max: number, step: number }\n}) {\n const apply = useContext(CardApply)\n const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {\n if (apply === null || (event.key !== 'Enter' && event.key !== 'Escape')) return\n event.preventDefault()\n if (event.key === 'Enter') apply.commit()\n else apply.revert()\n event.currentTarget.blur()\n }\n const input = (\n <input\n id={props.id}\n className={props.invalid ? css.inputInvalid : css.input}\n type=\"text\"\n {...props.numeric === true ? { inputMode: 'numeric' as const } : {}}\n {...props.invalid ? { 'aria-invalid': true } : {}}\n value={props.text}\n placeholder={props.placeholder ?? ''}\n disabled={props.disabled}\n onChange={(event) => { props.onEdit(event.target.value) }}\n onKeyDown={onKeyDown}\n onBlur={() => { apply?.commit() }}\n />\n )\n const { range } = props\n const typed = Number(props.text)\n return (\n <div className={css.field}>\n <div className={css.head}>\n <label className={css.label} htmlFor={props.id}>{props.label}</label>\n {props.overridden\n ? (\n <span className={css.badges}>\n <span className={css.badge}>{props.overriddenLabel}</span>\n <button\n type=\"button\"\n className={css.reset}\n disabled={props.disabled}\n onClick={props.onReset}\n >\n {props.resetLabel}\n </button>\n </span>\n )\n : null}\n </div>\n {range === undefined\n ? input\n : (\n <RangeBubble\n min={range.min}\n max={range.max}\n step={range.step}\n value={props.text.trim() === '' || Number.isNaN(typed) ? range.min : typed}\n label={`${props.label} ${range.min}–${range.max}`}\n disabled={props.disabled}\n onInput={(value) => { props.onEdit(String(value)) }}\n onCommit={(value) => {\n props.onEdit(String(value))\n apply?.commit()\n }}\n >\n {input}\n </RangeBubble>\n )}\n <p className={props.invalid ? css.invalid : css.hint} title={props.hintTitle}>\n {props.invalid ? props.invalidLabel : props.hint}\n </p>\n </div>\n )\n}\n\nconst NON_SKIN_BODY_MARKERS = new Set(['dshSkinCenter', 'dshSidebarCollapsed'])\n// 检测使用使用皮肤,用了皮肤退回原生select样式,防止样式冲突。默认外观下使用优化后的select样式。\nfunction isSkinActive(): boolean {\n const datasetList = Object.keys(document.body.dataset)\n const isActive = datasetList.some(key => key.startsWith('dsh') && !NON_SKIN_BODY_MARKERS.has(key))\n return isActive\n}\n\ninterface SelectOption {\n value: string\n label: string\n}\n\nconst SELECT_CLOSE_MS = 100\n\n/**\n * The shared dual-mode select control. While an appearance skin is active it\n * renders the legacy native `<select>` untouched, so element-level skin\n * selectors keep working; under the default appearance it renders a\n * self-drawn `role=\"listbox\"` popup whose open/close is transition-animated.\n * Cards reach it through BooleanField/ChoiceField; editors outside a card\n * (the side-card prefs) bind it directly through onEdit.\n * 双模式下拉框:皮肤激活时用原生 select,默认外观用自绘动画弹层。\n */\nexport function SelectField(props: {\n id: string\n options: ReadonlyArray<SelectOption>\n value: string\n disabled: boolean\n invalid: boolean\n onEdit: (text: string) => void\n}) {\n const { id, options, value } = props\n const [open, setOpen] = useState(false)\n const [closing, setClosing] = useState(false)\n const [phase, setPhase] = useState<'initial' | 'open'>('initial')\n const [activeIndex, setActiveIndex] = useState(0)\n const closeTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)\n const wrapRef = useRef<HTMLDivElement | null>(null)\n const popupRef = useRef<HTMLDivElement | null>(null)\n\n const currentIndex = () => {\n const index = options.findIndex(option => option.value === value)\n return index >= 0 ? index : 0\n }\n\n const close = useCallback(() => {\n if (closeTimer.current !== undefined) clearTimeout(closeTimer.current)\n setClosing(true)\n closeTimer.current = setTimeout(() => {\n setClosing(false)\n setOpen(false)\n }, SELECT_CLOSE_MS)\n }, [])\n\n const openPopup = () => {\n if (closeTimer.current !== undefined) clearTimeout(closeTimer.current)\n setActiveIndex(currentIndex())\n setPhase('initial')\n setClosing(false)\n setOpen(true)\n }\n\n const commit = (index: number) => {\n const option = options[index]\n if (option) props.onEdit(option.value)\n close()\n }\n\n const onTriggerClick = () => {\n if (props.disabled) return\n if (open && !closing) close()\n else openPopup()\n }\n\n const onKeyDown = (event: KeyboardEvent<HTMLButtonElement>) => {\n if (props.disabled) return\n const count = options.length\n switch (event.key) {\n case 'ArrowDown':\n case 'ArrowUp':\n case 'Enter':\n case ' ':\n event.preventDefault()\n if (!open) {\n openPopup()\n } else if (!closing) {\n if (event.key === 'ArrowDown') setActiveIndex(index => (index + 1) % count)\n else if (event.key === 'ArrowUp') setActiveIndex(index => (index - 1 + count) % count)\n else commit(activeIndex)\n }\n break\n case 'Escape':\n if (open) {\n event.preventDefault()\n event.stopPropagation()\n close()\n }\n break\n case 'Tab':\n if (open) close()\n break\n }\n }\n\n useEffect(() => () => {\n if (closeTimer.current !== undefined) clearTimeout(closeTimer.current)\n }, [])\n useLayoutEffect(() => {\n if (open && !closing && phase === 'initial') {\n void popupRef.current?.offsetHeight\n setPhase('open')\n }\n }, [open, closing, phase])\n\n useEffect(() => {\n if (!open) return\n const onPointerDown = (event: PointerEvent) => {\n const target = event.target\n if (target instanceof Node && !wrapRef.current?.contains(target)) close()\n }\n document.addEventListener('pointerdown', onPointerDown)\n return () => document.removeEventListener('pointerdown', onPointerDown)\n }, [open, close])\n\n useEffect(() => {\n if (props.disabled && open) close()\n }, [props.disabled, open, close])\n\n // 使用了皮肤则退回原生select样式防止样式冲突。\n if (isSkinActive()) {\n return (\n <select\n id={id}\n className={css.select}\n value={value}\n disabled={props.disabled}\n onChange={(event) => { props.onEdit(event.target.value) }}\n >\n {options.map(option => (\n <option key={option.value} value={option.value}>{option.label}</option>\n ))}\n </select>\n )\n }\n\n const label = options.find(option => option.value === value)?.label ?? ''\n const popupClass = closing\n ? `${css.selectPopup} ${css.selectPopupClose}`\n : phase === 'open'\n ? `${css.selectPopup} ${css.selectPopupOpen}`\n : css.selectPopup\n return (\n <div className={css.selectWrap} ref={wrapRef}>\n <button\n type=\"button\"\n id={id}\n className={`${css.select} ${css.selectButton}`}\n disabled={props.disabled}\n aria-haspopup=\"listbox\"\n aria-expanded={open}\n aria-activedescendant={open ? `${id}-o${activeIndex}` : undefined}\n aria-invalid={props.invalid || undefined}\n onClick={onTriggerClick}\n onKeyDown={onKeyDown}\n >\n <span className={css.selectLabel}>{label}</span>\n <svg\n width=\"14\"\n height=\"14\"\n viewBox=\"0 0 14 14\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n className={open ? `${css.selectChevron} ${css.selectChevronOpen}` : css.selectChevron}\n aria-hidden=\"true\"\n >\n <path\n d=\"M11.8486 5.5L11.4238 5.92383L8.69727 8.65137C8.44157 8.90706 8.21562 9.13382 8.01172 9.29785C7.79912 9.46883 7.55595 9.61756 7.25 9.66602C7.08435 9.69222 6.91565 9.69222 6.75 9.66602C6.44405 9.61756 6.20088 9.46883 5.98828 9.29785C5.78438 9.13382 5.55843 8.90706 5.30273 8.65137L2.57617 5.92383L2.15137 5.5L3 4.65137L3.42383 5.07617L6.15137 7.80273C6.42595 8.07732 6.59876 8.24849 6.74023 8.3623C6.87291 8.46904 6.92272 8.47813 6.9375 8.48047C6.97895 8.48703 7.02105 8.48703 7.0625 8.48047C7.07728 8.47813 7.12709 8.46904 7.25977 8.3623C7.40124 8.24849 7.57405 8.07732 7.84863 7.80273L10.5762 5.07617L11 4.65137L11.8486 5.5Z\"\n fill=\"currentColor\"\n />\n </svg>\n </button>\n {open\n ? (\n <div className={popupClass} role=\"listbox\" ref={popupRef}>\n {options.map((option, index) => (\n <div\n key={option.value}\n id={`${id}-o${index}`}\n role=\"option\"\n aria-selected={option.value === value}\n className={`${css.selectOption}${option.value === value ? ` ${css.selectOptionSelected}` : ''}${index === activeIndex && !closing ? ` ${css.selectOptionActive}` : ''}`}\n onClick={() => { commit(index) }}\n >\n {option.label}\n </div>\n ))}\n </div>\n )\n : null}\n </div>\n )\n}\n\n/**\n * A visible segmented group for a small set of mutually exclusive values.\n * Every option stays on screen, so inherit/on/off and short enum fields take\n * one click without opening a popup. The pressed option carries the group's\n * sliding highlight and `aria-pressed`; the group takes the field label as its\n * accessible name.\n */\nexport function SegmentField(props: {\n id: string\n label: string\n options: ReadonlyArray<SelectOption>\n value: string\n disabled: boolean\n invalid: boolean\n onEdit: (text: string) => void\n}) {\n return (\n <SegmentGroup\n id={props.id}\n role=\"group\"\n aria-label={props.label}\n aria-invalid={props.invalid || undefined}\n >\n {props.options.map((option, index) => {\n const active = option.value === props.value\n return (\n <button\n key={option.value}\n type=\"button\"\n className={css.segment}\n aria-pressed={active}\n disabled={props.disabled}\n data-active={active ? '' : undefined}\n data-segment-index={index}\n onClick={() => {\n if (!active) props.onEdit(option.value)\n }}\n >\n {option.label}\n </button>\n )\n })}\n </SegmentGroup>\n )\n}\n\n/** How a small single-choice field presents its options. */\nexport type FieldPresentation = 'select' | 'segment'\n\n/** A boolean field: 继承 / 开 / 关. */\nexport function BooleanField(props: FieldProps & {\n /** Copy for the inherit option. */\n inheritLabel: string\n /** Copy for the on option. */\n onLabel: string\n /** Copy for the off option. */\n offLabel: string\n /** Defaults to the visible segments: the three answers always fit on one row. */\n presentation?: FieldPresentation\n}) {\n const segmented = props.presentation !== 'select'\n return (\n <div className={css.field}>\n <div className={css.head}>\n {segmented\n ? <span className={css.label}>{props.label}</span>\n : <label className={css.label} htmlFor={props.id}>{props.label}</label>}\n {props.overridden\n ? (\n <span className={css.badges}>\n <span className={css.badge}>{props.overriddenLabel}</span>\n <button\n type=\"button\"\n className={css.reset}\n disabled={props.disabled}\n onClick={props.onReset}\n >\n {props.resetLabel}\n </button>\n </span>\n )\n : null}\n </div>\n {segmented\n ? (\n <SegmentField\n id={props.id}\n label={props.label}\n options={[\n { value: '', label: props.inheritLabel },\n { value: 'true', label: props.onLabel },\n { value: 'false', label: props.offLabel },\n ]}\n value={props.text}\n disabled={props.disabled}\n invalid={props.invalid}\n onEdit={props.onEdit}\n />\n )\n : (\n <SelectField\n id={props.id}\n options={[\n { value: '', label: props.inheritLabel },\n { value: 'true', label: props.onLabel },\n { value: 'false', label: props.offLabel },\n ]}\n value={props.text}\n disabled={props.disabled}\n invalid={props.invalid}\n onEdit={props.onEdit}\n />\n )}\n <p className={css.hint} title={props.hintTitle}>{props.hint}</p>\n </div>\n )\n}\n\n/** An enumerated field, selecting or segmenting its small choice set. */\nexport function ChoiceField(props: FieldProps & {\n /** Copy for the inherit option (draft text is the empty string). */\n inheritLabel: string\n /** Choices rendered in order; `value` is the draft/stored text. */\n choices: ReadonlyArray<{ value: string; label: string }>\n /**\n * Visible segmented options for a short fixed set; defaults to the compact\n * select, which also suits a list whose length follows the deployment.\n */\n presentation?: FieldPresentation\n}) {\n const segmented = props.presentation === 'segment'\n const options = [{ value: '', label: props.inheritLabel }, ...props.choices]\n return (\n <div className={css.field}>\n <div className={css.head}>\n {segmented\n ? <span className={css.label}>{props.label}</span>\n : <label className={css.label} htmlFor={props.id}>{props.label}</label>}\n {props.overridden\n ? (\n <span className={css.badges}>\n <span className={css.badge}>{props.overriddenLabel}</span>\n <button\n type=\"button\"\n className={css.reset}\n disabled={props.disabled}\n onClick={props.onReset}\n >\n {props.resetLabel}\n </button>\n </span>\n )\n : null}\n </div>\n {segmented\n ? (\n <SegmentField\n id={props.id}\n label={props.label}\n options={options}\n value={props.text}\n disabled={props.disabled}\n invalid={props.invalid}\n onEdit={props.onEdit}\n />\n )\n : (\n <SelectField\n id={props.id}\n options={options}\n value={props.text}\n disabled={props.disabled}\n invalid={props.invalid}\n onEdit={props.onEdit}\n />\n )}\n <p className={props.invalid ? css.invalid : css.hint} title={props.hintTitle}>\n {props.invalid ? props.invalidLabel : props.hint}\n </p>\n </div>\n )\n}\n\n/**\n * A boolean toggle drawn as a switch track, for a setting that is only on or\n * off and applies on flip. It is a real button with\n * `role=\"switch\"` and `aria-checked`, so keyboard and assistive activation\n * arrive as a click and the state is announced instead of inferred from a\n * checkbox tick.\n *\n * The thumb bounces across only once the reader has pressed this switch: the\n * press writes the mark that arms the bounce, so a page opening, a TAB\n * switching back or a value arriving from elsewhere draws every thumb at rest.\n */\nexport function ToggleSwitch(props: {\n /** Id of the element naming the switch (the card's title). */\n labelledBy?: string\n /** Accessible name when no element labels it. */\n ariaLabel?: string\n /** Current state. */\n checked: boolean\n /** Disables the switch while a write is in flight or the Host refuses writes. */\n disabled?: boolean\n /** Called with the requested next state. */\n onChange: (next: boolean) => void\n}) {\n const [moved, setMoved] = useState(false)\n return (\n <button\n type=\"button\"\n className={css.toggle}\n role=\"switch\"\n aria-checked={props.checked}\n aria-labelledby={props.labelledBy}\n aria-label={props.labelledBy === undefined ? props.ariaLabel : undefined}\n disabled={props.disabled}\n data-moved={moved ? '' : undefined}\n onClick={() => {\n setMoved(true)\n props.onChange(!props.checked)\n }}\n >\n <span className={css.toggleTrack}><span className={css.toggleThumb} /></span>\n </button>\n )\n}\n","/** Lightweight, static pet thumbnails built from the registry's existing assets. */\n\nimport type { PetDefinition } from '../registry.ts'\nimport sectionCss from './settings-section.module.css'\n\n/** Registry data needed by a thumbnail; older hosts may serve only id/name. */\nexport type PetPreviewDefinition = Pick<PetDefinition, 'id' | 'displayName'>\n & Partial<Pick<PetDefinition, 'renderer' | 'cell' | 'columns' | 'atlasRows' | 'atlasUrl' | 'frames2d'>>\n\nconst PREVIEW_LIMIT = 72\nconst DEFAULT_CELL = { width: 192, height: 208 }\n\n/**\n * Render the atlas's first sprite cell or a frames2d idle frame. Live2d and\n * incomplete legacy responses degrade to a text mark instead of a broken image.\n */\nexport function PetPreview(props: { pet: PetPreviewDefinition }) {\n const { pet } = props\n const renderer = pet.renderer ?? 'sprite2d'\n if (renderer === 'sprite2d' && pet.atlasUrl !== undefined) {\n const cell = pet.cell ?? DEFAULT_CELL\n const scale = Math.min(PREVIEW_LIMIT / cell.width, PREVIEW_LIMIT / cell.height)\n const width = Math.max(1, Math.round(cell.width * scale))\n const height = Math.max(1, Math.round(cell.height * scale))\n const columns = pet.columns ?? 8\n const rows = pet.atlasRows ?? 9\n return (\n <span className={sectionCss.previewFrame} aria-hidden=\"true\">\n <span\n className={sectionCss.previewAtlas}\n style={{\n width,\n height,\n backgroundImage: `url(\"${pet.atlasUrl}\")`,\n backgroundSize: `${columns * width}px ${rows * height}px`,\n }}\n />\n </span>\n )\n }\n const frame = renderer === 'frames2d'\n ? pet.frames2d?.tracks.idle?.frames[0] ?? pet.atlasUrl\n : undefined\n return (\n <span className={sectionCss.previewFrame} aria-hidden=\"true\">\n {frame === undefined\n ? <span className={sectionCss.previewFallback}>{pet.displayName.slice(0, 1)}</span>\n : <img className={sectionCss.previewImage} src={frame} alt=\"\" draggable={false} />}\n </span>\n )\n}\n","/**\n * Form model behind the plugin settings card. Every control applies itself:\n * a pick (a segment, a select option, a reset) writes the moment it is made,\n * and typed text writes once typing pauses or the reader leaves the field.\n * Between the edit and the write the edit is held here as a draft, so what is\n * on screen is exactly what the write will store; a write the Host refuses\n * puts a pick back to the stored value and keeps typed text for correcting.\n * Family-shared slice inlined into each plugin's client bundle.\n */\n\nimport type { ConfigForm, ConfigFormSnapshot } from '@deepseek-ai/dsh-client-ui-settings/client'\nimport type { SnapshotStore } from '@deepseek-ai/dsh-client-store'\nimport { createSnapshotStore } from '@deepseek-ai/dsh-client-store'\n\n/** The write one field's draft text performs when it is applied. */\nexport type FieldWrite =\n | { kind: 'set'; value: unknown }\n | { kind: 'clear' }\n\n/** How one field converts between its stored value and its draft text. */\nexport interface FieldSpec {\n /** Field name inside the namespace section. */\n field: string\n /**\n * How the reader enters a value, which decides when it is written: a `pick`\n * is a whole value at once and applies immediately; `type` is text arriving\n * a keystroke at a time and applies once typing pauses or the field is left.\n */\n entry: 'pick' | 'type'\n /**\n * Whether the Host treats this field as a secret and redacts its value from\n * the read-back (role('secret') in the section schema). Redacted secrets are\n * never compared against the draft on save: the Host strips them from every\n * wire view layer, so the settled snapshot carries nothing to read back. A\n * staged secret set is judged by the mutation settling; the rest of its\n * batch, when one exists, is still judged by read-back, and the atomic\n * mutation lands every write or none.\n */\n secret?: boolean\n /** Render a stored value as draft text; the empty string when the section carries none. */\n format: (value: unknown) => string\n /**\n * The write this draft text performs, or undefined when the text is not a\n * value this field accepts — which holds the draft unwritten rather than\n * discarding it.\n */\n parse: (text: string) => FieldWrite | undefined\n}\n\n/** One field as the card renders it. */\nexport interface FieldState {\n /** Draft text the control renders. */\n text: string\n /** Whether the field leaves (or will leave) a user-layer entry. */\n overridden: boolean\n /** Whether the draft is not a value this field accepts, which holds it unwritten. */\n invalid: boolean\n}\n\n/** Form state every plugin settings card shares. */\nexport interface CardShell {\n /** False while the namespace is still loading; the card renders nothing. */\n available: boolean\n /**\n * Whether the namespace is actually served to this client. False when the\n * Host deployment does not expose it (e.g. the owning plugin's settings\n * domain is not mounted): the card renders an explanation\n * instead of its form, so a missing namespace never looks like a missing\n * plugin.\n */\n exposed: boolean\n /** Whether the Host document accepts writes. */\n writable: boolean\n /** Whether the form holds drafts not yet written (typed text waiting for its pause). */\n dirty: boolean\n /** Whether any draft is invalid, which holds it unwritten. */\n invalid: boolean\n /** Whether a write is crossing the wire. */\n saving: boolean\n /** Whether the last write did not land; cleared by the next edit or write. */\n failed: boolean\n /**\n * The rejection code/message the Host returned for the last failed save,\n * surfaced next to the generic failure text. Undefined while no save has\n * failed (or the failure carried no server reason).\n */\n failedReason?: string\n}\n\n/** The write actions the card's slot entry injects. */\nexport interface CardActions {\n /** Take draft text for one field; a pick writes at once, typed text after a pause. */\n edit: (field: string, text: string) => void\n /** Clear one field at once, so it re-inherits the composition layer. */\n resetField: (field: string) => void\n /** Write every pending draft now (a text field's Enter or blur), then re-seed from what the Host accepted. */\n save: () => void\n /** Drop every pending draft, putting each control back to the stored value (a text field's Escape). */\n discard: () => void\n}\n\n/** How long typed text rests before it is written. */\nexport const TYPE_PAUSE_MS = 600\n\n/** One field's staged edit. */\ninterface StagedEdit {\n /** Draft text the control renders. */\n text: string\n /** True when this edit clears the field whatever text it shows. */\n clear: boolean\n}\n\n/** One staged edit resolved into the write a save performs. */\ninterface PlannedWrite {\n /** Field this entry writes. */\n field: string\n /** The durable write this entry performs, inside the save's one atomic mutation. */\n op: BatchedWrite\n /**\n * Read the settled snapshot back and report whether the Host holds this\n * write's effect. Undefined when the draft is not a value the field\n * accepts: there is nothing to write, and the entry blocks the save.\n */\n judge: (() => boolean) | undefined\n}\n\n/** One durable write inside the save's atomic form mutation. */\nexport interface BatchedWrite {\n /** Field this entry writes. */\n field: string\n /** set stores a value; unset drops the leaf. */\n op: 'set' | 'unset'\n /** Value for op set (absent for unset). */\n value?: unknown\n}\n\n/** Constraints a numeric field's accepted drafts must satisfy, mirroring the host schema. */\nexport interface NumberConstraints {\n /** The accepted value must be a whole number. */\n integer?: boolean\n /** The accepted value must be at least this. */\n min?: number\n}\n\n/** A whole- or decimal-number field. An empty draft clears the field; any other draft that is not a finite number within the constraints stays unwritten. */\nexport function numberField(field: string, constraints: NumberConstraints = {}): FieldSpec {\n const { integer = false, min } = constraints\n return {\n field,\n entry: 'type',\n format: value => typeof value === 'number' ? String(value) : '',\n parse: (text) => {\n const trimmed = text.trim()\n if (trimmed === '') return { kind: 'clear' }\n const parsed = Number(trimmed)\n if (!Number.isFinite(parsed)) return undefined\n if (integer && !Number.isInteger(parsed)) return undefined\n if (min !== undefined && parsed < min) return undefined\n return { kind: 'set', value: parsed }\n },\n }\n}\n\n/**\n * A free-text field. An empty draft clears the field. `entry` is `pick` when\n * the text arrives whole from a picker (a preset or a reasoning level).\n */\nexport function textField(field: string, entry: FieldSpec['entry'] = 'type'): FieldSpec {\n return {\n field,\n entry,\n format: value => typeof value === 'string' ? value : '',\n parse: (text) => {\n const trimmed = text.trim()\n return trimmed === '' ? { kind: 'clear' } : { kind: 'set', value: trimmed }\n },\n }\n}\n\n/**\n * A free-text field the Host treats as a secret and redacts from the read-back\n * (role('secret') in the section schema). The card still edits it like text,\n * but a save never compares the redacted value back: the staged set is judged\n * by the mutation settling (see {@link FieldSpec.secret}).\n */\nexport function secretField(field: string): FieldSpec {\n return { ...textField(field), secret: true }\n}\n\n/** A boolean field, edited through true/false draft text. */\nexport function booleanField(field: string): FieldSpec {\n return {\n field,\n entry: 'pick',\n format: value => typeof value === 'boolean' ? String(value) : '',\n parse: (text) => {\n const trimmed = text.trim()\n if (trimmed === '') return { kind: 'clear' }\n if (trimmed === 'true') return { kind: 'set', value: true }\n if (trimmed === 'false') return { kind: 'set', value: false }\n return undefined\n },\n }\n}\n\n/** An enumerated string field; only the listed choices are accepted. An empty draft clears the field. */\nexport function choiceField(field: string, choices: readonly string[]): FieldSpec {\n return {\n field,\n entry: 'pick',\n format: value => typeof value === 'string' && choices.includes(value) ? value : '',\n parse: (text) => {\n if (text === '') return { kind: 'clear' }\n return choices.includes(text) ? { kind: 'set', value: text } : undefined\n },\n }\n}\n\n/**\n * Applies one card's edits to one settings namespace as the reader makes them.\n *\n * The Host is the only authority on whether a value was accepted — its\n * validators own the constraints no schema can express — so the outcome is\n * read back from the section rather than predicted here. A write that did not\n * land puts each pick back to the stored value, the way a switch that could not\n * flip springs back, and keeps typed text so the reader can correct it instead\n * of retyping.\n */\nexport class CardForm<T> {\n private readonly specs: Map<string, FieldSpec>\n private readonly staged = new Map<string, StagedEdit>()\n private readonly listeners = new Set<() => void>()\n /** The form subscription installed in the constructor; released by dispose(). */\n private readonly disposeForm: () => void\n private disposed = false\n /** The pending write of typed text, waiting for typing to pause. */\n private typePause: ReturnType<typeof setTimeout> | undefined\n private saving = false\n /** A save asked for while one was in flight; it runs once the first settles (#1754). */\n private saveQueued = false\n private failed = false\n private failedReason: string | undefined\n\n /** @param scope - the bound configuration form for this card's namespace. */\n constructor(\n private readonly scope: ConfigForm<T>,\n specs: FieldSpec[],\n ) {\n this.specs = new Map(specs.map(spec => [spec.field, spec]))\n this.disposeForm = scope.subscribe(() => { this.publish() })\n }\n\n /**\n * Release the form subscription and every bound store listener. The card\n * must call this on teardown; later calls are no-ops.\n */\n dispose(): void {\n if (this.disposed) return\n this.disposed = true\n clearTimeout(this.typePause)\n this.disposeForm()\n this.listeners.clear()\n }\n\n /** Publish a projection of this form, rebuilt whenever the form or a draft changes. */\n bind<S>(project: () => S): SnapshotStore<S> {\n const store = createSnapshotStore(project())\n this.listeners.add(() => { store.set(project()) })\n return store\n }\n\n /** Read the card-level state: what the Host serves, and what is still waiting to be written. */\n shell(): CardShell {\n const snapshot = this.scope.getSnapshot()\n const plan = this.plan()\n return {\n available: snapshot.status !== 'loading',\n exposed: snapshot.status === 'ready',\n writable: snapshot.writable,\n dirty: plan.length > 0,\n invalid: plan.some(item => item.judge === undefined),\n saving: this.saving,\n failed: this.failed,\n ...this.failedReason === undefined ? {} : { failedReason: this.failedReason },\n }\n }\n\n /** Read one field's state from the effective section and its staged draft. */\n field(field: string): FieldState {\n const spec = this.specOf(field)\n const staged = this.staged.get(field)\n if (staged === undefined) {\n return { text: spec.format(this.sectionValue(field)), overridden: this.stored(field), invalid: false }\n }\n const write = staged.clear ? { kind: 'clear' as const } : spec.parse(staged.text)\n return {\n text: staged.text,\n overridden: write?.kind === 'set',\n invalid: write === undefined,\n }\n }\n\n /** The actions the card's slot registration injects. */\n actions(): CardActions {\n return {\n edit: (field, text) => { this.stage(field, { text, clear: false }) },\n resetField: (field) => {\n this.stage(field, { text: this.specOf(field).format(this.baseValue(field)), clear: true })\n },\n save: () => { this.applyNow() },\n discard: () => {\n clearTimeout(this.typePause)\n if (this.staged.size === 0 && !this.failed) return\n this.staged.clear()\n this.failed = false\n this.failedReason = undefined\n this.publish()\n },\n }\n }\n\n /**\n * Run one write, and re-run it once if another was asked for while this one\n * was still in flight.\n *\n * A write is a Host round trip that also drives the profile reconcile, and\n * the Host runs it inside one exclusive transaction. Answering an edit that\n * arrives mid-flight by returning immediately dropped it with no explanation\n * (#1754). Serializing instead means an edit made while another write is\n * still settling is written against the settled state.\n * @returns settlement after the mutation and the read-back.\n */\n async requestSave(): Promise<void> {\n if (this.saving) {\n this.saveQueued = true\n return\n }\n await this.save()\n if (!this.saveQueued) return\n this.saveQueued = false\n await this.requestSave()\n }\n\n /**\n * Write every valid draft in one atomic form mutation, then re-seed from\n * what the Host accepted. A draft the field does not accept stays on screen,\n * unwritten, without holding the others back.\n *\n * The batch rides one mutate, so cross-field validate hooks (baseURL+model)\n * judge it as a unit: the Host either applies every write or refuses the\n * batch. The form contract answers a refusal or a skipped write with `false`\n * (it recovers with a fresh Host view instead of throwing), so the outcome is\n * judged twice: the answer itself, and then the settled snapshot read back\n * one planned write at a time. One missed write fails the whole batch. A\n * transport that rejects instead (the dsh-web bridge controller on a dead\n * connection) reports through the same failure path with its rejection\n * message. A batch that did not land puts its picks and clears back to the\n * stored value and keeps its typed text, so the reader can correct it.\n * @returns settlement after the mutation and the read-back.\n */\n async save(): Promise<void> {\n const plan = this.plan()\n const valid = plan.filter((item): item is PlannedWrite & { judge: () => boolean } => item.judge !== undefined)\n if (valid.length === 0 || this.saving) return\n // Snapshot the staged entries this write carries, so an edit staged while\n // it is in flight (which replaces the same key) survives: only settle the\n // key when the entry is still the one this write started from.\n const pending = new Map<string, StagedEdit | undefined>()\n for (const item of valid) pending.set(item.field, this.staged.get(item.field))\n this.saving = true\n this.failed = false\n this.failedReason = undefined\n this.publish()\n // One atomic namespace mutation: the form contract takes ordered path\n // operations, so the whole staged batch is validated, persisted, and\n // recovered together — either every write lands or none does.\n const ops: Array<{ op: 'set'; path: string[]; value: string | number | boolean } | { op: 'unset'; path: string[] }> = valid.map(item => item.op.op === 'set'\n ? { op: 'set', path: [item.field], value: (item.op as { value: string | number | boolean }).value }\n : { op: 'unset', path: [item.field] })\n let failedReason: string | undefined\n let accepted = false\n try {\n accepted = await this.scope.mutate(ops)\n } catch (error) {\n failedReason = error instanceof Error ? error.message : String(error)\n }\n // `false` is the contract's refusal/skip answer, and the form still\n // resolves after a refusal (it recovers with a fresh view), so the answer\n // alone is not enough: judge every planned write against the settled\n // snapshot as well. The mutation is atomic, so one missed write fails the\n // whole save and keeps the drafts.\n const landed = accepted && failedReason === undefined && valid.every(item => item.judge())\n for (const [field, before] of pending) {\n if (this.staged.get(field) !== before) continue\n if (landed || before === undefined || before.clear || this.specOf(field).entry === 'pick') this.staged.delete(field)\n }\n this.saving = false\n this.failed = !landed\n // A refused or unlanded batch carries no server reason: the card surfaces\n // its generic failure copy; a rejecting transport (the bridge) adds its\n // message.\n this.failedReason = failedReason\n this.publish()\n }\n\n /**\n * Every staged edit a write would carry. An entry whose draft is not a value\n * its field accepts carries no write: the form is still dirty, and the draft\n * stays on screen rather than being dropped. A staged edit that matches the\n * effective section is not a write at all.\n * @returns the planned writes, in the order the fields were staged.\n */\n private plan(): PlannedWrite[] {\n const plan: PlannedWrite[] = []\n for (const [field, staged] of this.staged) {\n const spec = this.specOf(field)\n if (staged.clear) {\n if (this.stored(field)) plan.push({ field, op: { field, op: 'unset' }, judge: () => this.landedUnset(field) })\n continue\n }\n if (staged.text === spec.format(this.sectionValue(field))) continue\n const write = spec.parse(staged.text)\n if (write === undefined) plan.push({ field, op: { field, op: 'unset' }, judge: undefined })\n else if (write.kind === 'clear') plan.push({ field, op: { field, op: 'unset' }, judge: () => this.landedUnset(field) })\n else plan.push({ field, op: { field, op: 'set', value: write.value }, judge: () => this.landedSet(field, write.value) })\n }\n return plan\n }\n\n /**\n * Read-back judgment for a planned set: the user layer must hold the\n * intended value once the mutation has settled.\n */\n private landedSet(field: string, value: unknown): boolean {\n // A redacted secret never appears in any wire view layer: the Host strips\n // role('secret') fields and reports them through a sidecar the form\n // snapshot does not expose, so there is nothing to compare the draft\n // against. Settling is the only signal the form has; the rest of the\n // batch, when one exists, still carries the atomic verdict by read-back.\n if (this.specOf(field).secret) return true\n return this.userLayer()?.[field] === value\n }\n\n /**\n * Read-back judgment for a planned unset: the field must be gone from the\n * user layer once the mutation has settled.\n */\n private landedUnset(field: string): boolean {\n return !this.stored(field)\n }\n\n /**\n * Take one edit and schedule its write: a pick or a clear is written now,\n * typed text once typing has rested for TYPE_PAUSE_MS.\n */\n private stage(field: string, edit: StagedEdit): void {\n this.staged.set(field, edit)\n this.failed = false\n this.failedReason = undefined\n this.publish()\n if (edit.clear || this.specOf(field).entry === 'pick') {\n this.applyNow()\n return\n }\n clearTimeout(this.typePause)\n this.typePause = setTimeout(() => { this.applyNow() }, TYPE_PAUSE_MS)\n }\n\n /** Write every pending draft now, taking the place of a waiting pause. */\n private applyNow(): void {\n clearTimeout(this.typePause)\n this.typePause = undefined\n if (this.disposed) return\n void this.requestSave()\n }\n\n private specOf(field: string): FieldSpec {\n const spec = this.specs.get(field)\n // Every call site names a field this card declared; a missing one is a\n // wiring mistake that must not degrade into a silently inert control.\n if (spec === undefined) throw new Error(`settings card has no field ${field}`)\n return spec\n }\n\n private snapshotOf(): ConfigFormSnapshot<T> {\n return this.scope.getSnapshot()\n }\n\n private sectionValue(field: string): unknown {\n return (this.snapshotOf().value as Record<string, unknown> | undefined)?.[field]\n }\n\n private baseValue(field: string): unknown {\n return (this.snapshotOf().base as Record<string, unknown> | undefined)?.[field]\n }\n\n private userLayer(): Record<string, unknown> | undefined {\n return this.snapshotOf().user as Record<string, unknown> | undefined\n }\n\n private stored(field: string): boolean {\n const user = this.userLayer()\n return user !== undefined && Object.hasOwn(user, field)\n }\n\n private publish(): void {\n for (const listener of this.listeners) listener()\n }\n}\n","/**\n * The pet settings card: pet selection plus display layout, staged over the\n * 'pet' profile entry's own configuration (a plugin's settings ARE its Cordis\n * Config since 0.1.7, so the Host serves one form per profile entry).\n * Rendered as an always-open first-level settings page; the section wrapper\n * below mounts it as the content of the top-level 'settings.section' nav\n * entry. The petId choices come from the registry endpoint ('/api/pet/pets') —\n * the same list the sprite renders from — so the card carries no per-pet\n * knowledge.\n */\n\nimport { useEffect, type ReactNode } from 'react'\nimport type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { ConfigForm } from '@deepseek-ai/dsh-client-ui-settings/client'\nimport type { SnapshotStore } from '@deepseek-ai/dsh-client-store'\n// Type-only: pulls the settings-surface SlotMap merge (the 'settings.section' entry).\nimport type {} from '@deepseek-ai/dsh-client-ui-settings/client'\nimport type {} from './web-extension-contract.ts'\nimport { PluginSettingsCard, ValueField, BooleanField, ChoiceField, ToggleSwitch } from './PluginSettingsCard.tsx'\nimport { PetPreview, type PetPreviewDefinition } from './PetPreview.tsx'\nimport { CardForm, booleanField, choiceField, numberField, type CardActions, type CardShell, type FieldState as CardFieldState } from './settings-form.ts'\nimport sectionCss from './settings-section.module.css'\n\n/** The pet's settings fields this card edits (the namespace's full schema). */\nexport interface PetSettings {\n /** Master switch for the plugin. */\n enabled?: boolean\n /** Master switch. */\n visible?: boolean\n /** Scale of the rendered pet in px (sprite cell height). */\n size?: number\n /** Horizontal inset from the viewport right edge, px. */\n right?: number\n /** Vertical inset from the viewport bottom edge, px. */\n bottom?: number\n /** Bubble typography multiplier on the automatic size following (#1549). */\n bubbleScale?: number\n /** Selected pet id (a registry entry). */\n petId?: string\n /** Status-decoration master switch (pet-center M5, #567). */\n decorationEnabled?: boolean\n /** Whether the pet's own session/status bubbles render (issue #6). */\n statusBubbles?: string\n}\n\n/** What the pet settings card renders. */\nexport interface PetSettingsCardState extends CardShell {\n /** The aggregate shell has no Host settings form; pet selection uses its own persisted API. */\n petSelectionFallback: boolean\n /** Plugin master switch. */\n enabled: CardFieldState\n /** Master switch. */\n visible: CardFieldState\n /** Pet scale. */\n size: CardFieldState\n /** Right inset. */\n right: CardFieldState\n /** Bottom inset. */\n bottom: CardFieldState\n /** Bubble typography multiplier. */\n bubbleScale: CardFieldState\n /** Selected pet. */\n petId: CardFieldState\n /** Status-decoration master switch. */\n decorationEnabled: CardFieldState\n /** Whether the pet's own session/status bubbles render. */\n statusBubbles: CardFieldState\n /** Pet choices (registry ids + display names), loaded from the host. */\n petChoices: readonly { value: string; label: string }[]\n /** The same registry entries with the visual data their thumbnails need. */\n petPreviews: readonly PetPreviewDefinition[]\n}\n\n/** The registration-side face the card's slot entry injects. */\nexport interface PetSettingsCardFace extends CardActions {\n hooks: {\n /** Card snapshot bound by the renderer as usePetSettingsCard. */\n petSettingsCard: SnapshotStore<PetSettingsCardState>\n }\n /**\n * Ask the card for the pet registry again. The pet API only exists while the\n * plugin is enabled, so opening the master switch has to be able to re-ask\n * instead of leaving the picker empty until the page reloads.\n */\n refreshPets(): void\n}\n\n/**\n * The bubble modes this card can write, in render order. Mirrors the host\n * schema's union (see PetStatusBubbleMode); the browser half never imports the\n * host module for a value, so the accepted set is spelled here as literals.\n */\nconst STATUS_BUBBLE_CHOICES = ['auto', 'off'] as const\n\n/**\n * The spans the coarse sliders cover, spelled as literals for the same reason.\n * Size and bubble scale are the schema's own bounds (src/persist.ts); the\n * insets reach the schema's far end only by typing, so their slider covers the\n * distances a window can show.\n */\nexport const SIZE_RANGE = { min: 32, max: 1024, step: 1 }\nexport const INSET_RANGE = { min: 0, max: 1000, step: 1 }\nexport const BUBBLE_SCALE_RANGE = { min: 0.5, max: 2, step: 0.05 }\n\n/** One registry choice as served by '/api/pet/pets'. */\ntype PetChoice = PetPreviewDefinition\n\n/** Fetch the registry list (the same data the sprite renders from). */\nasync function fetchPetChoices(): Promise<PetChoice[]> {\n // Never from cache: the list is exactly what changes when the plugin is\n // switched on (the API only exists then) or a pet is installed.\n const response = await fetch('/api/pet/pets', { cache: 'no-store' })\n if (!response.ok) throw new Error('pet pets failed: ' + response.status)\n return (await response.json()) as PetChoice[]\n}\n\n/** The persisted state the fallback mirrors: the selection and its visibility. */\ninterface PetState {\n /** Selected registry id. */\n petId: string\n /** Whether the pet is currently rendered. */\n visible: boolean\n}\n\n/** Read the selection and visibility from the same persisted state the pet renders. */\nasync function fetchPetState(): Promise<PetState> {\n const response = await fetch('/api/pet/state')\n if (!response.ok) throw new Error('pet state failed: ' + response.status)\n const body = (await response.json()) as { pet?: { id?: unknown }; display?: { visible?: unknown } }\n if (typeof body.pet?.id !== 'string') throw new Error('pet state has no selected pet')\n // A Host without the display block predates the visibility switch; the pet shows.\n return { petId: body.pet.id, visible: body.display?.visible !== false }\n}\n\n/** Bridges the 'pet' scope onto the card's staged form. */\nexport class PetSettingsCardController {\n private readonly form: CardForm<PetSettings>\n private readonly store: SnapshotStore<PetSettingsCardState>\n // The choice list rides a mutable array shared with the choiceField spec,\n // so loading the registry re-validates and re-formats the petId field\n // without rebuilding the form.\n private readonly petChoices: string[] = []\n private readonly petLabels = new Map<string, string>()\n private petPreviews: PetPreviewDefinition[] = []\n private selectedPetId: string | undefined\n private selectedVisible: boolean | undefined\n private stagedPetId: string | undefined\n private stagedVisible: boolean | undefined\n private savingPet = false\n /** A fallback pick made while a write was in flight. */\n private fallbackQueued = false\n private petSaveFailed = false\n private loaded = false\n /** A registry request is in flight. */\n private loading = false\n private attempts = 0\n private disposed = false\n /** Pending deferred-load or retry timer; cancelled by dispose(). */\n private pendingTimer: number | undefined\n\n /** @param scope - the bound configuration form for the 'pet' entry. */\n constructor(scope: ConfigForm<PetSettings>) {\n this.form = new CardForm(scope, [\n booleanField('enabled'),\n booleanField('decorationEnabled'),\n // The bubble switch is a two-value mode, not a boolean: 'off' is the\n // opt-out, and a future mode (say, one that keeps only the current\n // session's bubble) has to be able to join the same field without\n // breaking every settings document already written.\n choiceField('statusBubbles', STATUS_BUBBLE_CHOICES),\n booleanField('visible'),\n numberField('size'),\n numberField('right'),\n numberField('bottom'),\n numberField('bubbleScale'),\n choiceField('petId', this.petChoices),\n ])\n this.store = this.form.bind(() => this.projection())\n // Client plugins are applied synchronously during shell startup. Defer\n // the first registry request until that pass completes so transport\n // plugins (notably remote-web-ui on a paired non-loopback origin) can\n // install their fetch channel before /api/pet/pets is issued.\n this.pendingTimer = window.setTimeout(() => {\n this.pendingTimer = undefined\n if (this.disposed) return\n void this.loadPets()\n void this.loadPetState()\n }, 0)\n }\n\n /** Resolve the registry choices once (retried a few times on failure). */\n private async loadPets(): Promise<void> {\n if (this.loaded || this.disposed || this.loading) return\n this.loading = true\n try {\n const list = await fetchPetChoices()\n if (this.disposed) return\n this.petChoices.splice(0, this.petChoices.length, ...list.map(choice => choice.id))\n this.petPreviews = list\n for (const choice of list) this.petLabels.set(choice.id, choice.displayName)\n this.loaded = true\n this.store.set(this.projection())\n } catch {\n if (this.disposed) return\n this.attempts += 1\n if (this.attempts < 3) {\n this.pendingTimer = window.setTimeout(() => {\n this.pendingTimer = undefined\n if (this.disposed) return\n void this.loadPets()\n }, 3000)\n }\n } finally {\n this.loading = false\n }\n }\n\n /**\n * Re-read the registry on demand. The pet API is registered only while the\n * plugin is enabled, so the first read can fail while the master switch is\n * off; this lets the card try again the moment the switch opens instead of\n * waiting for a page reload.\n */\n refreshPets(): void {\n if (this.disposed || this.loading) return\n this.loaded = false\n this.attempts = 0\n void this.loadPets()\n }\n\n private async loadPetState(): Promise<void> {\n try {\n const state = await fetchPetState()\n if (this.disposed) return\n this.selectedPetId = state.petId\n this.selectedVisible = state.visible\n this.store.set(this.projection())\n } catch {\n // The Host form remains the authority when it is available. An absent\n // pet API leaves the fallback unavailable rather than inventing state.\n }\n }\n\n private fallback(): boolean {\n const shell = this.form.shell()\n return shell.available && !shell.exposed && this.selectedPetId !== undefined\n }\n\n /**\n * The visibility the fallback switch renders: the staged draft when the user\n * moved it, the persisted value otherwise. There is no user layer to override\n * here, so the field is never marked overridden.\n */\n private fallbackVisible(): CardFieldState {\n const value = this.stagedVisible ?? this.selectedVisible\n return { text: value === undefined ? '' : String(value), overridden: false, invalid: false }\n }\n\n /**\n * Persist the staged selection and visibility through the pet API — the only\n * writer available when the aggregate shell serves this card, since there is\n * no Host settings form to mutate — then confirm the read-back before the\n * drafts are cleared. A refused write puts both picks back to what the pet\n * persisted. A pick made while a write is in flight runs once it settles.\n */\n private async saveFallback(): Promise<void> {\n const petId = this.stagedPetId\n const visible = this.stagedVisible\n if (this.savingPet) {\n this.fallbackQueued = true\n return\n }\n if (petId === undefined && visible === undefined) return\n if (petId !== undefined && !this.petChoices.includes(petId)) return\n this.savingPet = true\n this.petSaveFailed = false\n this.store.set(this.projection())\n try {\n if (petId !== undefined) {\n const response = await fetch('/api/pet/set-pet', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ petId }),\n })\n const result = (await response.json()) as { ok?: boolean; petId?: string }\n if (!response.ok || result.ok !== true || result.petId !== petId) {\n throw new Error('pet selection was not persisted')\n }\n }\n if (visible !== undefined) {\n const response = await fetch('/api/pet/set-visible', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ visible }),\n })\n if (!response.ok) throw new Error('pet visibility was not persisted')\n }\n const persisted = await fetchPetState()\n if (petId !== undefined && persisted.petId !== petId) throw new Error('pet selection was not persisted')\n if (visible !== undefined && persisted.visible !== visible) throw new Error('pet visibility was not persisted')\n this.selectedPetId = persisted.petId\n this.selectedVisible = persisted.visible\n if (this.stagedPetId === petId) this.stagedPetId = undefined\n if (this.stagedVisible === visible) this.stagedVisible = undefined\n } catch {\n this.petSaveFailed = true\n if (this.stagedPetId === petId) this.stagedPetId = undefined\n if (this.stagedVisible === visible) this.stagedVisible = undefined\n } finally {\n this.savingPet = false\n if (!this.disposed) this.store.set(this.projection())\n }\n if (this.fallbackQueued && !this.disposed) {\n this.fallbackQueued = false\n await this.saveFallback()\n }\n }\n\n private projection(): PetSettingsCardState {\n const fallback = this.fallback()\n const shell = this.form.shell()\n const configuredPet = this.form.field('petId')\n return {\n ...shell,\n ...(fallback ? {\n exposed: true,\n writable: true,\n dirty: this.stagedPetId !== undefined && this.stagedPetId !== this.selectedPetId\n || this.stagedVisible !== undefined && this.stagedVisible !== this.selectedVisible,\n invalid: this.stagedPetId !== undefined && !this.petChoices.includes(this.stagedPetId),\n saving: this.savingPet,\n failed: this.petSaveFailed,\n failedReason: undefined,\n } : {}),\n petSelectionFallback: fallback,\n enabled: this.form.field('enabled'),\n decorationEnabled: this.form.field('decorationEnabled'),\n statusBubbles: this.form.field('statusBubbles'),\n visible: fallback ? this.fallbackVisible() : this.form.field('visible'),\n size: this.form.field('size'),\n right: this.form.field('right'),\n bottom: this.form.field('bottom'),\n bubbleScale: this.form.field('bubbleScale'),\n petId: fallback\n ? { text: this.stagedPetId ?? this.selectedPetId ?? '', overridden: false, invalid: this.stagedPetId !== undefined && !this.petChoices.includes(this.stagedPetId) }\n : configuredPet.text === '' && this.selectedPetId !== undefined\n ? { ...configuredPet, text: this.selectedPetId }\n : configuredPet,\n petChoices: this.petChoices.map(id => ({ value: id, label: this.petLabels.get(id) ?? id })),\n petPreviews: this.petPreviews,\n }\n }\n\n /**\n * Build the face the card's slot registration injects.\n * @returns the card's snapshot and its form actions.\n */\n inject(): PetSettingsCardFace {\n const actions = this.form.actions()\n return {\n hooks: { petSettingsCard: this.store },\n // The fallback's two fields are both picks, so each is written through\n // the pet API the moment it is made, as the form writes its own picks.\n edit: (field, value) => {\n if (!this.fallback()) return actions.edit(field, value)\n if (field === 'petId') this.stagedPetId = value === '' ? undefined : value\n else if (field === 'visible') this.stagedVisible = value === '' ? undefined : value === 'true'\n else return\n this.petSaveFailed = false\n this.store.set(this.projection())\n void this.saveFallback()\n },\n resetField: (field) => {\n if (!this.fallback()) return actions.resetField(field)\n if (field === 'petId') this.stagedPetId = undefined\n else if (field === 'visible') this.stagedVisible = undefined\n else return\n this.petSaveFailed = false\n this.store.set(this.projection())\n },\n save: () => { if (this.fallback()) void this.saveFallback(); else actions.save() },\n discard: () => {\n if (!this.fallback()) return actions.discard()\n this.stagedPetId = undefined\n this.stagedVisible = undefined\n this.petSaveFailed = false\n this.store.set(this.projection())\n },\n refreshPets: () => { this.refreshPets() },\n }\n }\n\n /**\n * Release the card's scope subscription, bound stores and pending load\n * timers; the slot disposer calls this on teardown.\n */\n dispose(): void {\n if (this.disposed) return\n this.disposed = true\n if (this.pendingTimer !== undefined) {\n window.clearTimeout(this.pendingTimer)\n this.pendingTimer = undefined\n }\n this.form.dispose()\n }\n}\n\n/** Props the renderer binds for the pet settings card. */\nexport type PetSettingsCardProps =\n PropsLocale<'pet'>\n & InjectFace<PetSettingsCardFace>\n\n/**\n * Render the pet settings card.\n * @param props - locale copy, the card snapshot, and its form actions.\n * @returns the card.\n */\nexport function PetSettingsCard(props: PetSettingsCardProps) {\n const { t } = props\n const state = props.usePetSettingsCard(snapshot => snapshot)\n const disabled = !state.writable\n // The registry is read once, when the plugin starts; the pet API that serves\n // it exists only while the master switch is on. A card that opened empty\n // therefore asks again as soon as the switch is on, instead of leaving the\n // picker blank until the page reloads (the deferred reads had already spent\n // their retries while the API was absent).\n const enabled = state.enabled.text !== 'false'\n const hasChoices = state.petPreviews.length > 0\n const { refreshPets } = props\n useEffect(() => {\n if (enabled && !hasChoices) refreshPets()\n }, [enabled, hasChoices, refreshPets])\n const fieldProps = {\n overriddenLabel: t('settings.overridden'),\n resetLabel: t('settings.reset'),\n invalidLabel: t('settings.invalidNumber'),\n disabled,\n presentation: 'segment' as const,\n }\n // The master switch sits in the header, as the Workshop and Usage pages\n // carry theirs; the fallback has no Host form to write it through.\n const enabledSwitch = state.petSelectionFallback\n ? undefined\n : (\n <ToggleSwitch\n labelledBy=\"settings-pet-title\"\n checked={state.enabled.text !== 'false'}\n disabled={disabled}\n onChange={(next) => { props.edit('enabled', String(next)) }}\n />\n )\n return (\n <PluginSettingsCard\n t={t}\n titleKey=\"settings.title\"\n titleId=\"settings-pet-title\"\n descriptionKey=\"settings.description\"\n descriptionNode={state.petSelectionFallback ? t('settings.petHint') : undefined}\n headerAction={enabledSwitch}\n state={state}\n onSave={props.save}\n onDiscard={props.discard}\n alwaysOpen\n >\n <div className={sectionCss.settingsLayout}>\n <section className={sectionCss.selectionGroup}>\n <div className={sectionCss.groupHeader}>\n <h3 className={sectionCss.groupTitle} id=\"settings-pet-selection-title\">{t('settings.pet')}</h3>\n {state.petId.overridden\n ? (\n <button\n type=\"button\"\n className={sectionCss.textAction}\n disabled={disabled}\n onClick={() => { props.resetField('petId') }}\n >\n {t('settings.reset')}\n </button>\n )\n : null}\n </div>\n <div\n id=\"settings-pet-pet\"\n className={sectionCss.petGrid}\n role=\"group\"\n aria-labelledby=\"settings-pet-selection-title\"\n >\n {state.petPreviews.map(pet => {\n const selected = state.petId.text === pet.id\n return (\n <button\n key={pet.id}\n type=\"button\"\n className={selected ? `${sectionCss.petChoice} ${sectionCss.petChoiceSelected}` : sectionCss.petChoice}\n aria-pressed={selected}\n title={pet.displayName}\n disabled={disabled}\n onClick={() => { props.edit('petId', pet.id) }}\n >\n <PetPreview pet={pet} />\n <span className={sectionCss.petChoiceLabel}>{pet.displayName}</span>\n </button>\n )\n })}\n </div>\n <p className={state.petId.invalid ? sectionCss.invalid : sectionCss.groupHint}>\n {state.petId.invalid ? t('settings.invalidNumber') : t('settings.petHint')}\n </p>\n </section>\n\n <div className={sectionCss.settingsColumn}>\n <section className={sectionCss.settingsGroup}>\n <div className={sectionCss.groupHeader}>\n <h3 className={sectionCss.groupTitle} id=\"settings-pet-display-title\">{t('settings.displayGroup')}</h3>\n </div>\n <div className={sectionCss.fields}>\n <BooleanField\n id=\"settings-pet-visible\"\n label={t('settings.visible')}\n hint={t('settings.visibleHint')}\n inheritLabel={t('settings.inherit')}\n onLabel={t('settings.on')}\n offLabel={t('settings.off')}\n {...fieldProps}\n {...state.visible}\n onEdit={(text) => { props.edit('visible', text) }}\n onReset={() => { props.resetField('visible') }}\n />\n {state.petSelectionFallback ? null : <ValueField\n id=\"settings-pet-size\"\n label={t('settings.size')}\n hint={t('settings.sizeHint')}\n numeric\n range={SIZE_RANGE}\n {...fieldProps}\n {...state.size}\n onEdit={(text) => { props.edit('size', text) }}\n onReset={() => { props.resetField('size') }}\n />}\n {state.petSelectionFallback ? null : <ValueField\n id=\"settings-pet-right\"\n label={t('settings.right')}\n hint={t('settings.rightHint')}\n numeric\n range={INSET_RANGE}\n {...fieldProps}\n {...state.right}\n onEdit={(text) => { props.edit('right', text) }}\n onReset={() => { props.resetField('right') }}\n />}\n {state.petSelectionFallback ? null : <ValueField\n id=\"settings-pet-bottom\"\n label={t('settings.bottom')}\n hint={t('settings.bottomHint')}\n numeric\n range={INSET_RANGE}\n {...fieldProps}\n {...state.bottom}\n onEdit={(text) => { props.edit('bottom', text) }}\n onReset={() => { props.resetField('bottom') }}\n />}\n </div>\n </section>\n\n {state.petSelectionFallback ? null : (\n <section className={sectionCss.settingsGroup}>\n <div className={sectionCss.groupHeader}>\n <h3 className={sectionCss.groupTitle} id=\"settings-pet-behavior-title\">{t('settings.bubbleGroup')}</h3>\n </div>\n <div className={sectionCss.fields}>\n <BooleanField\n id=\"settings-pet-decoration\"\n label={t('settings.decoration')}\n hint={t('settings.decorationHint')}\n inheritLabel={t('settings.inherit')}\n onLabel={t('settings.on')}\n offLabel={t('settings.off')}\n {...fieldProps}\n {...state.decorationEnabled}\n onEdit={(text) => { props.edit('decorationEnabled', text) }}\n onReset={() => { props.resetField('decorationEnabled') }}\n />\n <ChoiceField\n id=\"settings-pet-status-bubbles\"\n label={t('settings.statusBubbles')}\n hint={t('settings.statusBubblesHint')}\n inheritLabel={t('settings.inherit')}\n {...fieldProps}\n {...state.statusBubbles}\n choices={[\n { value: STATUS_BUBBLE_CHOICES[0], label: t('settings.on') },\n { value: STATUS_BUBBLE_CHOICES[1], label: t('settings.off') },\n ]}\n onEdit={(text) => { props.edit('statusBubbles', text) }}\n onReset={() => { props.resetField('statusBubbles') }}\n />\n <ValueField\n id=\"settings-pet-bubble-scale\"\n label={t('settings.bubbleScale')}\n hint={t('settings.bubbleScaleHint')}\n numeric\n range={BUBBLE_SCALE_RANGE}\n {...fieldProps}\n {...state.bubbleScale}\n onEdit={(text) => { props.edit('bubbleScale', text) }}\n onReset={() => { props.resetField('bubbleScale') }}\n />\n </div>\n </section>\n )}\n </div>\n </div>\n </PluginSettingsCard>\n )\n}\n\n/** Props the settings section binds for the pet card page. */\nexport type PetSettingsSectionProps =\n (PropsRuntime<'settings.section'> | PropsRuntime<'web-ui.extension'>)\n & PropsLocale<'pet'>\n & InjectFace<PetSettingsCardFace>\n\n/** Render the pet settings card as a first-level settings page. */\nexport function PetSettingsSection(props: PetSettingsSectionProps): ReactNode {\n const { t, usePetSettingsCard, save, discard, edit, resetField, refreshPets } = props\n return (\n <ul className={sectionCss.sectionList} data-dsh-plugin=\"pet\" data-dsh-part=\"panel\">\n <PetSettingsCard\n t={t}\n usePetSettingsCard={usePetSettingsCard}\n save={save}\n discard={discard}\n edit={edit}\n resetField={resetField}\n refreshPets={refreshPets}\n />\n </ul>\n )\n}\n","/**\n * dsh-pet locale dictionaries (zh/en).\n * @module @linxin666/dsh-pet/client/locales\n */\n\n/** Dictionary namespace this package registers. */\nexport const NS = 'pet'\n\n/** Chinese copy. */\nexport const zh = {\n 'pet.feed': '喂食',\n 'pet.hide': '隐藏',\n 'pet.rename': '改名',\n 'pet.confirm': '确定',\n 'pet.namePlaceholder': '输入新名字',\n 'pet.summon': '召唤{name}',\n 'pet.rank': '亲密度 {rank}',\n 'pet.rank.name.幼鲸': '幼鲸',\n 'pet.rank.name.伙伴': '伙伴',\n 'pet.rank.name.挚友': '挚友',\n 'pet.rank.name.深海羁绊': '深海羁绊',\n 'pet.rank.name.心有灵犀': '心有灵犀',\n 'pet.rank.name.传说羁绊': '传说羁绊',\n 'pet.rank.name.神话羁绊': '神话羁绊',\n 'pet.rank.name.永恒之契': '永恒之契',\n 'pet.rank.name.鲸生共渡': '鲸生共渡',\n 'pet.points': '{points} 点',\n 'pet.treats': '小鱼干 ×{n}',\n 'pet.state.loading': '宠物正在赶来…',\n 'pet.state.error': '宠物迷路了(连接失败)',\n 'pet.renderer.unavailable': '这只宠物需要的渲染器({renderer})在当前版本不可用。',\n 'pet.live2d.core-missing': 'Live2D 核心未安装:请把官方 live2dcubismcore.min.js 放入 $DSH_HOME/pets/.runtime/ 后刷新(步骤见宠物插件 README)。',\n 'pet.live2d.vendor-missing': 'Live2D 组件缺失,请升级宠物插件。',\n 'pet.live2d.load-failed': 'Live2D 模型加载失败,请检查该宠物目录的完整性。',\n 'pet.openSessionHint': '点击跳转到对应会话',\n // 玩法 HUD(miku-pet 泛化:属性条 / 打工 / 睡觉 / 商店;统一小鱼干经济)。\n 'pet.gameplay.menu': '玩法',\n 'pet.gameplay.work': '打工',\n 'pet.gameplay.stopWork': '收工',\n 'pet.gameplay.sleep': '休息',\n 'pet.gameplay.wake': '起床',\n 'pet.gameplay.shop': '商店',\n 'pet.gameplay.skin': '皮肤',\n 'pet.gameplay.skinDefault': '默认',\n 'pet.gameplay.back': '返回',\n 'pet.gameplay.buy': '购买',\n 'pet.gameplay.insufficient': '{currency}不足',\n 'pet.gameplay.prize': '中奖 +{amount} {currency}',\n 'pet.gameplay.working': '打工中',\n 'pet.gameplay.sleeping': '睡觉中',\n 'pet.gameplay.stat.hunger': '饱食',\n 'pet.gameplay.stat.mood': '心情',\n 'pet.gameplay.stat.energy': '精力',\n 'pet.gameplay.stat.affection': '好感',\n 'pet.gameplay.currency.treats': '小鱼干',\n 'pet.moreSessions': '展开其余 {n} 个会话的气泡',\n 'pet.collapseSessions': '收起会话气泡',\n // 一级设置页(settings.section 席位)。\n 'settings.title': '宠物',\n 'settings.description': '选一只宠物,摆在页面的角落里。',\n 'settings.pet': '宠物',\n 'settings.petHint': '名字跟着宠物走,在宠物面板里改。',\n 'settings.displayGroup': '显示',\n 'settings.bubbleGroup': '气泡',\n 'settings.decoration': '状态装饰',\n 'settings.decorationHint': '气泡里带上喷水鲸鱼这类装饰。',\n 'settings.statusBubbles': '状态气泡',\n 'settings.statusBubblesHint': '宠物报告正在思考、正在用哪个工具。',\n 'settings.visible': '显示宠物',\n 'settings.visibleHint': '藏起来后可在输入区召唤回来。',\n 'settings.size': '大小(px)',\n 'settings.sizeHint': '宠物的高度。',\n 'settings.bubbleScale': '气泡字号',\n 'settings.bubbleScaleHint': '字号随宠物缩放,再乘上这个倍数。',\n 'settings.right': '距右侧(px)',\n 'settings.rightHint': '离窗口右边的距离。',\n 'settings.bottom': '距底部(px)',\n 'settings.bottomHint': '离窗口底边的距离。',\n 'settings.inherit': '默认',\n 'settings.on': '开',\n 'settings.off': '关',\n 'settings.overridden': '已修改',\n 'settings.reset': '恢复默认',\n 'settings.notExposed': '这个版本的 DSH 没有开放宠物的设置,可直接编辑 $DSH_HOME/settings.yaml。',\n 'settings.readOnly': '设置只读。',\n 'settings.expand': '展开设置',\n 'settings.collapse': '收起设置',\n 'settings.saveFailed': '没有保存成功,输入的值还留着。',\n 'settings.invalidNumber': '填一个数字,留空用默认值。',\n} as const\n\n/** English copy. */\nexport const en = {\n 'pet.feed': 'Feed',\n 'pet.hide': 'Hide',\n 'pet.rename': 'Rename',\n 'pet.confirm': 'OK',\n 'pet.namePlaceholder': 'Enter a new name',\n 'pet.summon': 'Summon {name}',\n 'pet.rank': 'Affinity {rank}',\n 'pet.rank.name.幼鲸': 'Baby Whale',\n 'pet.rank.name.伙伴': 'Companion',\n 'pet.rank.name.挚友': 'Close Friend',\n 'pet.rank.name.深海羁绊': 'Deep Sea Bond',\n 'pet.rank.name.心有灵犀': 'Kindred Spirit',\n 'pet.rank.name.传说羁绊': 'Legendary Bond',\n 'pet.rank.name.神话羁绊': 'Mythic Bond',\n 'pet.rank.name.永恒之契': 'Eternal Covenant',\n 'pet.rank.name.鲸生共渡': 'Lifelong Companion',\n 'pet.points': '{points} pts',\n 'pet.treats': 'Treats ×{n}',\n 'pet.state.loading': 'The pet is on its way…',\n 'pet.state.error': 'The pet is lost (connection failed)',\n 'pet.renderer.unavailable': 'This pet needs a renderer ({renderer}) that is not available in this build.',\n 'pet.live2d.core-missing': 'Live2D Cubism Core is not installed: place the official live2dcubismcore.min.js under $DSH_HOME/pets/.runtime/ and refresh (see the pet plugin README).',\n 'pet.live2d.vendor-missing': 'The Live2D component is missing; please update the pet plugin.',\n 'pet.live2d.load-failed': 'The Live2D model failed to load; check the pet directory is complete.',\n 'pet.openSessionHint': 'Click to jump to this session',\n // Gameplay HUD (miku-pet generalization: stat bars / work / sleep / shop; unified treats economy).\n 'pet.gameplay.menu': 'Play',\n 'pet.gameplay.work': 'Work',\n 'pet.gameplay.stopWork': 'Stop work',\n 'pet.gameplay.sleep': 'Sleep',\n 'pet.gameplay.wake': 'Wake up',\n 'pet.gameplay.shop': 'Shop',\n 'pet.gameplay.skin': 'Skin',\n 'pet.gameplay.skinDefault': 'Default',\n 'pet.gameplay.back': 'Back',\n 'pet.gameplay.buy': 'Buy',\n 'pet.gameplay.insufficient': 'Not enough {currency}',\n 'pet.gameplay.prize': 'Prize +{amount} {currency}',\n 'pet.gameplay.working': 'Working',\n 'pet.gameplay.sleeping': 'Sleeping',\n 'pet.gameplay.stat.hunger': 'Hunger',\n 'pet.gameplay.stat.mood': 'Mood',\n 'pet.gameplay.stat.energy': 'Energy',\n 'pet.gameplay.stat.affection': 'Affection',\n 'pet.gameplay.currency.treats': 'Treats',\n 'pet.moreSessions': 'Expand {n} more session bubbles',\n 'pet.collapseSessions': 'Collapse session bubbles',\n // First-level settings section (the `settings.section` seat).\n 'settings.title': 'Pet',\n 'settings.description': 'Pick a pet to sit in a corner of the page.',\n 'settings.pet': 'Pet',\n 'settings.petHint': 'Each pet keeps its own name; rename it from the pet panel.',\n 'settings.displayGroup': 'Display',\n 'settings.bubbleGroup': 'Bubbles',\n 'settings.decoration': 'Status decoration',\n 'settings.decorationHint': 'Bubbles carry ornaments like the spouting whale.',\n 'settings.statusBubbles': 'Status bubbles',\n 'settings.statusBubblesHint': 'The pet reports when it is thinking and which tool it is using.',\n 'settings.visible': 'Show the pet',\n 'settings.visibleHint': 'A hidden pet comes back from the input row.',\n 'settings.size': 'Size (px)',\n 'settings.sizeHint': 'How tall the pet stands.',\n 'settings.bubbleScale': 'Bubble text',\n 'settings.bubbleScaleHint': 'Text follows the pet size, times this factor.',\n 'settings.right': 'Right inset (px)',\n 'settings.rightHint': 'Distance from the right edge of the window.',\n 'settings.bottom': 'Bottom inset (px)',\n 'settings.bottomHint': 'Distance from the bottom edge of the window.',\n 'settings.inherit': 'Default',\n 'settings.on': 'On',\n 'settings.off': 'Off',\n 'settings.overridden': 'Changed',\n 'settings.reset': 'Reset to default',\n 'settings.notExposed': 'This DSH version does not open the pet settings here; edit $DSH_HOME/settings.yaml instead.',\n 'settings.readOnly': 'Settings are read-only.',\n 'settings.expand': 'Show settings',\n 'settings.collapse': 'Hide settings',\n 'settings.saveFailed': 'Not saved; what you typed is still there.',\n 'settings.invalidNumber': 'Enter a number, or leave it empty for the default.',\n} as const\n\n/** Key union for this namespace. */\nexport type PetKey = keyof typeof zh\n\n/** The settings-card slice of the pet dictionary. */\nexport type SettingsCardKey = PetKey\n\n/**\n * Active dictionary, picked by the document language at call time. The pet\n * mounts as a global floating surface (not a session-scoped slot), so it has\n * no framework locale seat and resolves its copy the same tiny way the\n * task-board's DOM-injected surface does.\n */\nexport function dictionary(): Record<PetKey, string> {\n const lang = typeof document !== 'undefined' ? document.documentElement.lang : 'zh'\n return lang.toLowerCase().startsWith('en') ? en : zh\n}\n\n/**\n * Translate a key with optional `{name}` template params. Mirrors the slot\n * `Translate` contract `(key, params?) => string` so it can be handed to the\n * same components that used to receive the framework-injected `t` seat. The\n * key is typed loosely (`string`) so the function is assignable to the slot's\n * `TranslateNS<'pet'>` (whose key domain also spans the shared common\n * vocabulary); a missing key degrades to the key itself rather than throwing.\n */\nexport function t(key: string, params?: Record<string, unknown>): string {\n let text: string = (dictionary() as Record<string, string>)[key] ?? key\n if (params !== undefined) {\n for (const [name, value] of Object.entries(params)) {\n text = text.replaceAll(`{${name}}`, String(value))\n }\n }\n return text\n}\n\ndeclare module '@deepseek-ai/dsh-client-ui-slots' {\n interface LocaleNamespaceMap {\n /** dsh-pet UI copy. */\n pet: PetKey\n }\n}\n","/**\n * One settings page's seat in either the Web Extensions parent or the legacy\n * first-level settings navigation.\n *\n * The parent supplies the page contract; a child does not know which slot the\n * parent uses internally. While `webUiExtensions` is live the page is handed\n * to its service, which owns keyed mounting and disposal. Without the parent,\n * the same component registers as its original first-level settings section,\n * so a standalone install keeps a working entry.\n */\n\n/** The parent service face this helper consumes. */\nexport interface WebExtensionPageService {\n readonly sectionId: string\n registerPage(page: WebExtensionPageSeat): () => void\n}\n\n/** Seat-independent page contribution. */\nexport interface WebExtensionPageSeat {\n key: string\n order: number\n locale: string\n label(): string\n inject(): object\n component: unknown\n children?: Record<string, { kind: 'keyed' | 'list'; scope: 'root' }>\n}\n\n/** The slot-registry slice used for the standalone fallback. */\nexport interface WebExtensionPageSlots {\n register(options: never, component: never): unknown\n spec?(key: string): unknown\n entries?(key: string): readonly { component?: unknown; options: Record<string, unknown> }[]\n}\n\n/** The context slice needed by the migration. */\nexport interface WebExtensionPageContext {\n slots: WebExtensionPageSlots\n get?(name: string): unknown\n on?(event: string, listener: () => void): unknown\n}\n\nconst SETTINGS_SECTION = 'settings.section'\nconst WEB_EXTENSION_SLOT = 'web-ui.extension'\n\nfunction serviceOf(ctx: WebExtensionPageContext): WebExtensionPageService | undefined {\n if (typeof ctx.get !== 'function') return undefined\n try {\n const candidate = ctx.get('webUiExtensions') as Partial<WebExtensionPageService> | undefined\n return candidate !== null\n && typeof candidate === 'object'\n && typeof candidate.sectionId === 'string'\n && typeof candidate.registerPage === 'function'\n ? candidate as WebExtensionPageService\n : undefined\n } catch {\n return undefined\n }\n}\n\nfunction warn(seat: string, error: unknown): void {\n try {\n console.warn(`[dsh-web-settings] page \"${seat}\" could not be mounted`, error)\n } catch {\n // A restricted console must not drop the remaining entry.\n }\n}\n\n/**\n * Keep exactly one reachable page contribution while the parent loads or\n * unloads. The parent service owns integrated mounting; only the fallback uses\n * this plugin's own slot registry. Slot disposal is synchronous, so the latch\n * prevents a move from recursively registering a duplicate.\n */\nexport function installWebExtensionPage(\n ctx: WebExtensionPageContext,\n page: WebExtensionPageSeat,\n): () => void {\n let dispose: (() => void) | undefined\n let current: 'integrated' | 'legacy' | undefined\n let reconciling = false\n let disposed = false\n\n const present = (seat: 'integrated' | 'legacy'): boolean => {\n if (typeof ctx.slots.entries !== 'function') return current === seat\n const slot = seat === 'integrated' ? WEB_EXTENSION_SLOT : SETTINGS_SECTION\n return ctx.slots.entries(slot).some(entry =>\n entry.component === page.component\n && (seat === 'integrated' ? entry.options.key : entry.options.id) === page.key)\n }\n\n const registerSeat = (seat: 'integrated' | 'legacy'): (() => void) => {\n if (seat === 'integrated') {\n const service = serviceOf(ctx)\n if (service === undefined) throw new Error('webUiExtensions service is unavailable')\n return service.registerPage(page)\n }\n return ctx.slots.register({\n name: SETTINGS_SECTION,\n id: page.key,\n order: page.order,\n label: page.label,\n locale: page.locale,\n inject: page.inject as never,\n ...(page.children === undefined ? {} : { children: page.children }),\n } as never, page.component as never) as () => void\n }\n\n const reconcile = (): void => {\n if (disposed || reconciling) return\n const target: 'integrated' | 'legacy' = serviceOf(ctx) === undefined ? 'legacy' : 'integrated'\n if (current === target && present(target)) return\n const slot = target === 'integrated' ? WEB_EXTENSION_SLOT : SETTINGS_SECTION\n if (typeof ctx.slots.spec === 'function' && ctx.slots.spec(slot) === undefined) return\n reconciling = true\n const previous = current\n const disposePrevious = dispose\n current = undefined\n dispose = undefined\n disposePrevious?.()\n try {\n dispose = registerSeat(target)\n current = target\n } catch (error) {\n warn(target, error)\n if (previous !== undefined && previous !== target) {\n try {\n dispose = registerSeat(previous)\n current = previous\n } catch (restoreError) {\n warn(previous, restoreError)\n }\n }\n } finally {\n reconciling = false\n }\n }\n\n if (typeof ctx.on === 'function') {\n try { ctx.on('slots/changed', reconcile) } catch { /* the initial entry remains usable */ }\n }\n reconcile()\n return () => {\n if (disposed) return\n disposed = true\n dispose?.()\n dispose = undefined\n current = undefined\n }\n}\n","/**\n * The pet settings page's contribution: the Web Extensions parent mounts it\n * through its page service, while a standalone install keeps the original\n * first-level settings section.\n */\n\nimport type { Context as ClientContext } from '@deepseek-ai/cordis'\n// Type-only: the renderer owns ctx.slots and the locale plugin owns ctx.locale.\nimport type {} from '@deepseek-ai/dsh-client-ui-renderer/client'\nimport type {} from '@deepseek-ai/dsh-client-locale/client'\nimport type {} from './web-extension-contract.ts'\nimport { PetSettingsSection, type PetSettingsCardController } from './PetSettingsCard.tsx'\nimport { NS } from './locales.ts'\nimport { installWebExtensionPage } from './web-extension-page.ts'\n\n/**\n * Register exactly one reachable pet entry and follow the parent across late\n * loading or teardown. The controller belongs to apply(), not a registration,\n * so moving seats never resets staged edits or subscriptions.\n * @returns the page contribution's disposer.\n */\nexport function installPetSettingsRegistration(\n ctx: ClientContext,\n controller: PetSettingsCardController,\n): () => void {\n return installWebExtensionPage(ctx, {\n key: 'pet',\n order: 130,\n locale: NS,\n label: () => ctx.locale.bind(NS)('settings.title'),\n inject: () => controller.inject(),\n component: PetSettingsSection,\n })\n}\n","// Generated by scripts/sync-shared.mjs from shared/client/main-session.ts. Do not edit this copy; edit the shared source and run \"node scripts/sync-shared.mjs\".\n/**\n * Main-view Session derivation for the multi-instance Client Session model.\n *\n * The Client Session Controller carries no global \"current\" selection: view\n * selection belongs to the workspace UI, which owns the main-area reference and\n * publishes it through the catalog's per-source ownership counts\n * (`SessionSummary.retainedBy.mainView`). A plugin that needs the Session the\n * main view shows derives it from that marker instead of the removed\n * `SessionListState.current` field.\n *\n * The marker describes view ownership, not authority. It is the right input for\n * presentation and for deciding which view a navigation targets; it is not a\n * business fallback, because source counts never imply visibility or success.\n * @module dsh-web/shared/main-session\n */\n\n/** The catalog row subset this helper reads (a `SessionSummary` projection). */\nexport interface MainViewOwnedRow<Id extends string = string> {\n /** Catalog row identity. */\n readonly id: Id\n /** Per-source local ownership counts; absent rows are never owned. */\n readonly retainedBy?: Readonly<Partial<Record<string, number>>> | undefined\n}\n\n/**\n * Resolve the Session the main view currently shows.\n *\n * Reads the catalog's rows rather than a per-id retain-info source: ownership\n * counts ride the list snapshot, so this neither allocates observers nor opens\n * history, and a subscription to the list still fires when the selection moves.\n * @param byId - the session catalog's rows (`SessionListState.byId`), when available.\n * @returns the main-view session id, or undefined when the main view shows none.\n */\nexport function mainViewSessionId<Id extends string>(\n byId: Readonly<Record<Id, MainViewOwnedRow<Id> | undefined>> | undefined | null,\n): Id | undefined {\n if (byId === undefined || byId === null) return undefined\n for (const row of Object.values<MainViewOwnedRow<Id> | undefined>(byId)) {\n if (row !== undefined && (row.retainedBy?.mainView ?? 0) > 0) return row.id\n }\n return undefined\n}\n","// Generated by scripts/sync-shared.mjs from shared/client/telemetry.ts. Do not edit this copy; edit the shared source and run \"node scripts/sync-shared.mjs\".\n/**\n * Anonymous install telemetry shared by the DSH Web UI family plugins.\n *\n * Once per UTC day per browser, each wired plugin sends one heartbeat to\n * the dsh-market edge API listing its package name (and version when known).\n * The payload carries no conversation data and no identifiers beyond a random\n * UUID generated in localStorage; the server hashes it with a deployment salt\n * before storage and never persists IP addresses. Sends are fire-and-forget:\n * failures stay silent and simply retry on a later mount or day. The system\n * is documented in docs/telemetry.md.\n */\n\nexport type TelemetryChannel = 'market' | 'npm' | 'unknown'\n\nexport interface TelemetryItem {\n /** npm package name or asset id, e.g. \"@linxin666/dsh-pet\" or \"skin:harbor\". */\n name: string\n /** Installed version when known; omitted otherwise. */\n version?: string\n /** Install channel when determinable (market = Workshop install). */\n channel?: TelemetryChannel\n}\n\nconst VISITOR_KEY = 'dsh-web-ui-telemetry-visitor'\nconst DAY_KEY_PREFIX = 'dsh-web-ui-telemetry-day:'\nconst ENDPOINT = 'https://dsh-market.com/api/telemetry/event'\n\n// Baked into each client bundle by shared/tsdown.client.ts (the package's own\n// package.json version at build time). Undefined in dev/test builds.\ndeclare const __DSH_PKG_VERSION__: string | undefined\n\n/** The building package's version, when the bundle carries it. */\nfunction bakedVersion(): string | undefined {\n try {\n return typeof __DSH_PKG_VERSION__ === 'string' && __DSH_PKG_VERSION__ !== ''\n ? __DSH_PKG_VERSION__\n : undefined\n } catch {\n return undefined\n }\n}\n\n/** Read or lazily create the anonymous visitor id; null when storage is unavailable. */\nfunction visitorId(): string | null {\n try {\n const existing = localStorage.getItem(VISITOR_KEY)\n if (existing && /^[A-Za-z0-9_-]{16,64}$/.test(existing)) return existing\n const fresh = crypto.randomUUID().replaceAll('-', '')\n localStorage.setItem(VISITOR_KEY, fresh)\n return fresh\n } catch {\n // Storage unavailable (privacy mode, sandboxed frame): report nothing.\n return null\n }\n}\n\n/** Drop stale per-day dedup keys so localStorage does not grow forever. */\nfunction pruneDayKeys(today: string): void {\n try {\n for (let index = localStorage.length - 1; index >= 0; index -= 1) {\n const key = localStorage.key(index)\n if (key !== null && key.startsWith(DAY_KEY_PREFIX) && key !== DAY_KEY_PREFIX + today) {\n localStorage.removeItem(key)\n }\n }\n } catch { /* best effort */ }\n}\n\n/**\n * Fire the daily heartbeat for the given items at most once per UTC day per\n * browser. Never throws and never blocks the caller. Items without an explicit\n * version inherit the bundle's baked build version.\n */\nexport function reportDailyHeartbeat(items: readonly TelemetryItem[]): void {\n try {\n if (items.length === 0) return\n const today = new Date().toISOString().slice(0, 10)\n // Automation contexts (CDP-driven QA browsers, fresh isolated profiles)\n // mint a new visitor id per run and would inflate instance counts.\n if (navigator.webdriver) return\n if (localStorage.getItem(DAY_KEY_PREFIX + today) !== null) return\n const visitor = visitorId()\n if (visitor === null) return\n pruneDayKeys(today)\n const payloadItems = items.map((item) => {\n const out: Record<string, string> = { name: item.name }\n const version = item.version ?? bakedVersion()\n if (version !== undefined) out.version = version\n if (item.channel !== undefined) out.channel = item.channel\n return out\n })\n const body = JSON.stringify({ kind: 'heartbeat', visitor, items: payloadItems })\n void fetch(ENDPOINT, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body,\n keepalive: true,\n }).then((response) => {\n // Mark the day only after an accepted send, so offline browsers retry\n // on a later mount instead of going dark until tomorrow.\n if (response.ok) localStorage.setItem(DAY_KEY_PREFIX + today, '1')\n }).catch(() => { /* unreachable endpoint: stay silent */ })\n } catch { /* never break the host UI over telemetry */ }\n}\n","/**\n * dsh-pet browser half — mounts the selected pet as a global floating\n * surface and drives it from the host's same-origin '/api/pet/*' JSON\n * endpoints: fetch the registry list once, poll the host snapshot (~2 s),\n * forward interactions, persist drag positions. The pet is host-global (no\n * session dimension), so it mounts directly onto 'document.body' via a\n * single React root — the [data-dsh-plugin=\"pet\"] container — rather than a\n * session-scoped slot: on the new-conversation screen no session exists, and\n * a dock-mounted pet would vanish there (issue #48). The sprite chrome\n * portals into that same root, so the root owns the whole surface and a\n * root-keyed suppressor can hide it as one unit. When the pet is hidden the\n * entry becomes a fixed-position summon button.\n * @module @linxin666/dsh-pet/client\n */\n\nimport type { Context as ClientContext } from '@deepseek-ai/cordis'\nimport type { ISessions } from '@deepseek-ai/dsh-api-session-controller/client'\nimport type { SessionId } from '@deepseek-ai/dsh-api-remotes/client'\nimport type { ConfigForm, ConfigFormSnapshot } from '@deepseek-ai/dsh-client-ui-settings/client'\n// Type-only: pulls the locale plugin's Context merge (ctx.locale).\nimport type {} from '@deepseek-ai/dsh-client-locale/client'\n// Type-only: pulls the shared configuration forms Context merge (ctx.configForms).\nimport type {} from '@deepseek-ai/dsh-client-ui-settings/client'\nimport type {} from '@deepseek-ai/dsh-client-ui-slots'\n// Type-only: pulls the ctx.slots merge (the renderer owns the slot registry since 0.1.2).\nimport type {} from '@deepseek-ai/dsh-client-ui-renderer/client'\nimport type {} from '@deepseek-ai/dsh-client-ui-conversation/client'\n// Type-only: pulls the workspace plugin's Context merge (ctx.uiWorkspace), the\n// multi-instance navigation face that replaced ISessions.open().\nimport type {} from '@deepseek-ai/dsh-client-ui-workspace/client'\nimport type { PetDisplayConfig } from '../persist.ts'\nimport type { PetGameplayVerbResult, PetInteractResult, PetStateView } from '../service.ts'\nimport type { PetInteraction } from '../affinity.ts'\nimport type { PetDefinition } from '../registry.ts'\nimport { createElement } from 'react'\nimport { createRoot } from 'react-dom/client'\nimport { createPetStore, type PetStoreInstance } from './pet-store.ts'\nimport { createWorkTickGate } from './work-tick-gate.ts'\nimport { PetDockEntry, type PetInjected } from './PetDockEntry.tsx'\nimport { defaultPetRendererRegistry } from './renderers/registry.ts'\nimport { live2dRenderer } from './renderers/live2d.ts'\nimport { frames2dRenderer } from './renderers/frames2d.ts'\nimport { registerPetUiTeardown, takeoverPetUiTeardown } from './ui-teardown.ts'\nimport { PetSettingsCardController, type PetSettings } from './PetSettingsCard.tsx'\nimport { installPetSettingsRegistration } from './settings-registration.ts'\nimport { NS, en, zh } from './locales.ts'\nimport { mainViewSessionId } from './main-session.ts'\nimport { reportDailyHeartbeat } from './telemetry.ts'\n\n/** The host pet API as the browser sees it (same-origin JSON endpoints). */\ninterface PetHttpApi {\n /** Poll the host snapshot; the GUI's current session id rides the query. */\n state(currentSessionId?: string): Promise<PetStateView>\n pets(): Promise<PetDefinition[]>\n interact(kind: PetInteraction): Promise<PetInteractResult>\n setVisible(visible: boolean): Promise<{ ok: true; display: PetDisplayConfig }>\n setConfig(patch: Partial<PetDisplayConfig>): Promise<{ ok: true; display: PetDisplayConfig }>\n setName(name: string): Promise<{ ok: true; name: string } | { ok: false; error: string }>\n setPet(petId: string): Promise<{ ok: true; petId: string } | { ok: false; error: string }>\n panelAction(id: string): Promise<{ ok: boolean; error?: string }>\n setSkin(skin?: string): Promise<{ ok: boolean; error?: string; skin?: string }>\n gameplayTouch(zone?: string): Promise<PetGameplayVerbResult>\n gameplaySetMode(mode: string | null): Promise<PetGameplayVerbResult>\n gameplayWorkTick(): Promise<PetGameplayVerbResult>\n gameplayBuy(item: string): Promise<PetGameplayVerbResult>\n}\n\n/** Same-origin JSON fetch helper (GET without body, POST with JSON body). */\nasync function petFetch<T>(path: string, body?: unknown): Promise<T> {\n const response = await fetch(path, body === undefined\n ? {}\n : {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n })\n if (!response.ok) {\n throw new Error('pet ' + path + ' failed: ' + response.status)\n }\n return (await response.json()) as T\n}\n\n/** The live host API instance (always defined; failures surface per call). */\nconst petApi: PetHttpApi = {\n state: (currentSessionId) => petFetch('/api/pet/state'\n + (currentSessionId === undefined ? '' : '?current=' + encodeURIComponent(currentSessionId))),\n pets: () => petFetch('/api/pet/pets'),\n interact: (kind) => petFetch('/api/pet/interact', { kind }),\n setVisible: (visible) => petFetch('/api/pet/set-visible', { visible }),\n setConfig: (patch) => petFetch('/api/pet/set-config', patch),\n setName: (name) => petFetch('/api/pet/set-name', { name }),\n setPet: (petId) => petFetch('/api/pet/set-pet', { petId }),\n panelAction: (id) => petFetch('/api/pet/panel-action', { id }),\n setSkin: (skin) => petFetch('/api/pet/set-skin', skin === undefined ? {} : { skin }),\n gameplayTouch: (zone) => petFetch('/api/pet/gameplay/touch', zone === undefined ? {} : { zone }),\n gameplaySetMode: (mode) => petFetch('/api/pet/gameplay/mode', { mode }),\n gameplayWorkTick: () => petFetch('/api/pet/gameplay/work-tick', {}),\n gameplayBuy: (item) => petFetch('/api/pet/gameplay/buy', { item }),\n}\n\n/** Poll interval for the host snapshot. */\nconst POLL_MS = 2000\n\n/** Settings namespace of the pet's settings page. It is the profile entry id the Host serves a form for. */\nconst PET_SETTINGS_NS = 'pet'\n\n/** Required services (sessions powers bubble-to-session navigation). */\nexport const inject = ['slots', 'locale', 'connection', 'configForms', 'remote', 'sessions', 'uiWorkspace']\n\n/** Re-exported for consumers that type against the injected face. */\nexport type { PetInjected, PetDockEntryProps } from './PetDockEntry.tsx'\nexport type { PetSpriteProps } from './PetSprite.tsx'\nexport type { PetUiState, PetFeedback } from './pet-store.ts'\nexport type { PetSettingsCardFace, PetSettingsCardState } from './PetSettingsCard.tsx'\nexport type { PetSettingsSectionProps } from './PetSettingsCard.tsx'\nexport type { PetDefinition } from '../registry.ts'\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n /**\n * Optional family binder provided by dsh-web-settings; absent when that\n * group plugin is not installed, so callers fall back to the shared\n * per-entry form.\n */\n webUiSettings?: {\n bind<S>(spec: { namespace: string; decode?: (section: unknown) => S | undefined }): ConfigForm<S>\n }\n }\n}\n\n/**\n * The profile entry ids a pet install is served under, most specific first. The\n * family bundle renames child rows, so a standalone install and an aggregate\n * one answer to different ids for the same 'pet' namespace.\n */\nconst AGGREGATE_ENTRY_ID = 'web-ui-pet'\nconst PET_ENTRY_IDS: readonly string[] = [AGGREGATE_ENTRY_ID, 'ui-pet', PET_SETTINGS_NS]\n\n/** How long the deferred form keeps retrying before it settles on the fallback. */\nexport const BINDER_RETRY_MS = 250\nconst BINDER_ATTEMPTS = 24\n\n/** The snapshot an unresolved (or resolvable-but-unbound) form publishes. */\nfunction pendingSnapshot<T>(status: 'loading' | 'unavailable'): ConfigFormSnapshot<T> {\n return { status, value: undefined, base: undefined, user: undefined, revision: undefined, writable: false }\n}\n\n/**\n * A ConfigForm that late-binds to the family settings binder.\n *\n * The binder service (dsh-web-settings) is not guaranteed to be published by the\n * time this plugin's apply() runs: the aggregate bundle mounts its inlined\n * children — including the binder — inside an async mount that awaits the\n * active-rows fetch, while standalone loader entries like this one apply\n * synchronously in that window. A single early probe then permanently falls\n * back to `configForms.get('pet')`, which is never a served row id under the\n * aggregate (the row is `web-ui-pet`), so the settings card renders \"not\n * exposed\" forever even though the Host serves the namespace.\n *\n * This form resolves through the binder as soon as the service appears and\n * delegates the whole ConfigForm surface to it, re-publishing to its own\n * subscribers on every swap. Until a form is resolved it publishes a loading\n * (then unavailable) snapshot so the card shows a transient state, never a\n * false \"not exposed\". If the binder never appears it retries for a bounded\n * window, then permanently binds the non-bridge fallback by SERVED entry id.\n */\nclass DeferredSettingsForm implements ConfigForm<PetSettings> {\n private ctx: ClientContext\n private current: ConfigForm<PetSettings> | undefined\n private readonly listeners = new Set<() => void>()\n private unsubscribeCurrent: (() => void) | undefined\n private retryTimer: number | undefined\n private attempts = 0\n private disposed = false\n private readonly fallback: ConfigForm<PetSettings>\n private fallbackUnsubscribe: (() => void) | undefined\n\n constructor(ctx: ClientContext) {\n this.ctx = ctx\n this.fallback = ctx.configForms.get<PetSettings>(this.resolveFallbackEntryId())\n // No binder yet: the aggregate publishes it after an async mount, so keep\n // probing. A shared form that can already answer for itself is adopted at\n // once; one still loading has simply not been filled in yet.\n if (!this.resolve() && !this.fallbackSettled()) this.scheduleRetry()\n else if (this.current === undefined) this.adoptFallback()\n }\n\n /**\n * True only once the shared mirror answers for the pet namespace itself.\n *\n * 'ready' is the only state that answers (#1813). A host-persisted row starts\n * out as 'loading' — the mirror has published no view yet — and that is not\n * an answer: adopting it on sight drops the retry window, and under the\n * aggregate, which serves only the renamed 'web-ui-pet' row, the form then\n * settles into 'unavailable' and the page stays \"not exposed\" for good. So\n * 'loading' and 'unavailable' both keep the window open and let the binder be\n * adopted the moment the aggregate publishes it.\n */\n private fallbackSettled(): boolean {\n try {\n return this.fallback.getSnapshot().status === 'ready'\n } catch {\n return false\n }\n }\n\n /**\n * Bind the fallback to a SERVED row id when the mirror can name one; a mirror\n * that cannot is left to report its own unavailable state.\n */\n private resolveFallbackEntryId(): string {\n try {\n const served = this.ctx.configForms.describe().getSnapshot().view?.namespaces.map(view => view.ns)\n if (served && served.length > 0) {\n const hit = PET_ENTRY_IDS.find(id => served.includes(id))\n if (hit !== undefined) return hit\n }\n } catch {\n // fall through to the family namespace; the form reports unavailable.\n }\n return PET_SETTINGS_NS\n }\n\n /**\n * Adopt the family binder the moment it is published.\n * @returns true when a binder was bound, false when none is available yet.\n */\n private resolve(): boolean {\n if (this.disposed) return false\n let binder: { bind?: unknown } | undefined\n try {\n binder = this.ctx.get('webUiSettings') as { bind?: unknown } | undefined\n } catch {\n binder = undefined\n }\n if (binder === undefined || typeof binder.bind !== 'function') return false\n let bound: ConfigForm<PetSettings>\n try {\n bound = (binder as { bind: <T>(spec: { namespace: string }) => ConfigForm<T> })\n .bind<PetSettings>({ namespace: PET_SETTINGS_NS })\n } catch {\n return false\n }\n this.current = bound\n // Mirror the bound form's changes to our own subscribers; a later re-resolve\n // swaps this subscription to the new form.\n this.unsubscribeCurrent?.()\n this.unsubscribeCurrent = bound.subscribe(() => this.publish())\n this.publish()\n return true\n }\n\n /**\n * Adopt the shared per-entry form. It is used immediately unless it cannot\n * answer yet (still loading, or reporting the namespace unavailable), in which\n * case the binder may still be on its way and the retry window takes over\n * (see scheduleRetry).\n */\n private adoptFallback(): void {\n this.current = this.fallback\n this.fallbackUnsubscribe ??= this.fallback.subscribe(() => this.publish())\n this.unsubscribeCurrent = this.fallbackUnsubscribe\n this.publish()\n }\n\n /** Retry the binder lookup a few times across the aggregate's async mount. */\n private scheduleRetry(): void {\n if (this.disposed) return\n if (this.attempts >= BINDER_ATTEMPTS) {\n this.adoptFallback()\n return\n }\n this.attempts += 1\n this.retryTimer = window.setTimeout(() => {\n this.retryTimer = undefined\n if (this.disposed) return\n if (this.resolve()) return\n // The binder still absent: keep waiting only while the shared form cannot\n // answer for itself, otherwise a standalone install stalls for the window.\n if (this.fallbackSettled()) {\n this.attempts = BINDER_ATTEMPTS\n this.adoptFallback()\n return\n }\n this.scheduleRetry()\n }, BINDER_RETRY_MS)\n }\n\n private publish(): void {\n for (const listener of this.listeners) listener()\n }\n\n /** The resolved form, or a placeholder snapshot when still pending. */\n private snapshot(): ConfigFormSnapshot<PetSettings> {\n return this.current?.getSnapshot() ?? pendingSnapshot<PetSettings>(this.attempts >= BINDER_ATTEMPTS ? 'unavailable' : 'loading')\n }\n\n getSnapshot(): ConfigFormSnapshot<PetSettings> {\n return this.snapshot()\n }\n\n subscribe(listener: () => void): () => void {\n this.listeners.add(listener)\n return () => { this.listeners.delete(listener) }\n }\n\n mutate(ops: Parameters<ConfigForm<PetSettings>['mutate']>[0], expectedRevision?: number): Promise<boolean> {\n return this.current?.mutate(ops, expectedRevision) ?? Promise.resolve(false)\n }\n\n set(field: string, value: unknown): Promise<boolean> {\n return this.current?.set(field, value) ?? Promise.resolve(false)\n }\n\n unset(field: string): Promise<boolean> {\n return this.current?.unset(field) ?? Promise.resolve(false)\n }\n\n /** Release the retry timer and mirror subscription; not part of ConfigForm. */\n dispose(): void {\n if (this.disposed) return\n this.disposed = true\n if (this.retryTimer !== undefined) {\n window.clearTimeout(this.retryTimer)\n this.retryTimer = undefined\n }\n this.unsubscribeCurrent?.()\n this.unsubscribeCurrent = undefined\n this.current = undefined\n this.listeners.clear()\n // The shared per-entry form carries no disposer of its own (ConfigForm is a\n // pure read/write surface); only this form's own subscriptions are released.\n this.fallbackUnsubscribe?.()\n this.fallbackUnsubscribe = undefined\n }\n}\n\n/**\n * Client plugin body: register dictionaries, mount the global pet entry and\n * poll loop while the plugin is enabled, and seat the settings card as a\n * first-level settings section.\n * @param ctx - client root context.\n */\n\n/** The page-wide work-tick gate; its window follows the active pet's cadence. */\nconst workTickGate = createWorkTickGate()\n\n/**\n * The work cadence the active pet declares, when its registry entry is known.\n * @param store - the pet store holding the host snapshot and the registry list.\n * @returns the configured `gameplay.work.tickMs`, or undefined when unknown.\n */\nfunction activeWorkTickMs(store: PetStoreInstance): number | undefined {\n const state = store.getSnapshot()\n const definition = state.pets.find((entry) => entry.id === state.snapshot?.pet.id)\n return definition?.gameplay?.work?.tickMs\n}\n\nexport function apply(ctx: ClientContext): void {\n // Anonymous install heartbeat (docs/telemetry.md): one beat per browser per\n // UTC day, package name only, silent failure.\n reportDailyHeartbeat([{ name: '@linxin666/dsh-pet' }])\n\n ctx.effect(() => {\n try {\n return ctx.locale.register(NS, { zh, en })\n } catch {\n return () => {}\n }\n }, 'pet: dictionaries')\n\n // Built-in renderers dispatch through the plugin-wide registry (pet-center\n // M3). Registration is idempotent (id wins), so re-applies stay clean.\n defaultPetRendererRegistry.register(live2dRenderer)\n defaultPetRendererRegistry.register(frames2dRenderer)\n\n const settingsForm = new DeferredSettingsForm(ctx)\n const enabled = (): boolean => {\n const snapshot = settingsForm.getSnapshot()\n return snapshot.status === 'ready'\n ? snapshot.value?.enabled ?? true\n : snapshot.status === 'unavailable'\n }\n\n // One staged form follows the pet page between Web Extensions and the\n // standalone first-level section. Seat migration does not reset drafts.\n const petSettings = new PetSettingsCardController(settingsForm)\n const disposeSettingsRegistration = installPetSettingsRegistration(ctx, petSettings)\n ctx.effect(() => () => {\n disposeSettingsRegistration()\n petSettings.dispose()\n }, 'pet: settings page')\n\n // The global pet entry, its store, and the poll loop live while the plugin\n // is enabled; toggling the setting off hides the pet and stops polling.\n // 'uiDead' marks a terminal teardown (takeover by a later bundle instance\n // or fiber disposal): a taken-over or disposed instance must never remount\n // from a late settings callback (issue #785).\n let disposeUi: (() => void) | undefined\n let clearUiTeardown: (() => void) | undefined\n let uiDead = false\n const killUi = (): void => {\n if (uiDead) return\n uiDead = true\n clearUiTeardown?.()\n clearUiTeardown = undefined\n disposeUi?.()\n disposeUi = undefined\n }\n const syncUi = (): void => {\n if (!uiDead && enabled() && disposeUi === undefined) {\n // ONE store instance for the whole app, owned by this apply body. The\n // pet is host-global (state/display/interactions are /api/pet/*\n // endpoints with no session dimension), so the slot system's per-session\n // store scoping would only reset the pet on session switches and leave\n // it stateless on the new-conversation screen (no session to scope by).\n const petStore: PetStoreInstance = createPetStore().create()\n const setSnapshot = petStore.actions.setSnapshot\n const setPets = petStore.actions.setPets\n const setState = petStore.actions.setState\n const setFeedback = petStore.actions.setFeedback\n\n // Clicking a session bubble jumps the GUI to that session; the\n // catalog's main-view ownership marker tells which session the main view\n // holds (the multi-instance replacement for the removed list.current), so\n // the host can lead the bubble stack with it. A bubble can outlive its\n // disposed session by one poll tick, and navigation rejects unknown ids,\n // so consult the live list first. The pet's type program also loads the\n // host-side dsh-session package through the service types, whose Context\n // merge declares a different 'sessions' face; pin the browser runtime's\n // outward face here.\n const sessions = ctx.sessions as unknown as ISessions\n const currentSessionId = (): string | undefined => mainViewSessionId(sessions.list.getSnapshot().byId)\n\n // The registry list is fetched lazily with retries baked into the poll\n // cycle: until it lands, the dock entry renders nothing and every 2s\n // tick tries again. After it lands, one list feeds both the sprite and\n // the settings card's choices.\n let petsLoaded = false\n // Latest-wins guard: the 2s tick, visibility recovery, and\n // interaction-triggered refreshes can overlap; only the newest\n // response may publish, so a slow older one can never roll the\n // snapshot back.\n let stateSeq = 0\n const pollNow = (): void => {\n if (!petsLoaded) {\n petApi.pets().then((list) => {\n petsLoaded = true\n setPets(list)\n }, () => {\n // Retry on the next poll tick.\n })\n }\n const seq = stateSeq + 1\n stateSeq = seq\n petApi.state(currentSessionId()).then((snapshot) => {\n if (seq !== stateSeq) return\n setSnapshot(snapshot)\n }, () => {\n if (seq !== stateSeq) return\n setState('error', 'pet.state transport error')\n })\n }\n\n const disposePoll = ctx.effect(() => {\n // Poll only while the tab is visible: the host snapshot does not\n // change while the page is hidden, so a background interval would\n // only burn RPCs (browser throttling is an unreliable backstop).\n // Coming back to the tab refreshes the pet immediately instead of\n // waiting out the next 2 s cycle.\n let timer: number | undefined\n const stop = (): void => {\n if (timer !== undefined) {\n window.clearInterval(timer)\n timer = undefined\n }\n }\n const start = (): void => {\n if (timer === undefined && document.visibilityState === 'visible') {\n timer = window.setInterval(pollNow, POLL_MS)\n }\n }\n const onVisibility = (): void => {\n if (document.visibilityState === 'visible') {\n pollNow()\n start()\n } else {\n stop()\n }\n }\n start()\n document.addEventListener('visibilitychange', onVisibility)\n return () => {\n stop()\n document.removeEventListener('visibilitychange', onVisibility)\n }\n }, 'pet: poll')\n\n // A current-session switch should re-order the bubble stack right away,\n // not on the next 2s tick. Poll only while the tab is visible, as the\n // poll loop itself does.\n const disposeSessionWatch = ctx.effect(() => {\n const unsubscribe = sessions.list.subscribe(() => {\n if (document.visibilityState === 'visible') pollNow()\n })\n return unsubscribe\n }, 'pet: current-session watch')\n\n const openSession = (sessionId: string): void => {\n const list = sessions.list.getSnapshot()\n if ((list.byId as any)[sessionId] === undefined) return\n // Navigation belongs to the workspace UI since the multi-instance Client\n // Session model; the Session Controller no longer opens one.\n ctx.uiWorkspace.openSession(sessionId as never)\n }\n\n const injected = (): PetInjected => ({\n store: petStore,\n ensure: pollNow,\n openSession,\n pet: () => {\n petApi.interact('pet').then((result) => {\n setFeedback({\n text: result.reaction,\n kind: 'pet',\n at: Date.now(),\n })\n }, () => {\n // Ignore transport errors on interactions; the next poll resyncs.\n })\n },\n feed: () => {\n petApi.interact('feed').then((result) => {\n setFeedback({\n text: result.reaction,\n kind: 'feed',\n at: Date.now(),\n })\n }, () => {\n // Ignore transport errors on interactions; the next poll resyncs.\n })\n },\n hide: () => {\n petApi.setVisible(false).then(() => {\n pollNow()\n }, () => {\n // Ignore; next poll resyncs.\n })\n },\n summon: () => {\n petApi.setVisible(true).then(() => {\n pollNow()\n }, () => {\n // Ignore; next poll resyncs.\n })\n },\n dragEnd: (right, bottom) => {\n petApi.setConfig({ right, bottom }).then(() => {\n pollNow()\n }, () => {\n // Ignore; next poll resyncs.\n })\n },\n rename: (name) => {\n petApi.setName(name).then((result) => {\n if (result.ok) pollNow()\n }, () => {\n // Ignore; next poll resyncs.\n })\n },\n // A panel action click (issue #6) travels back to the host, which\n // dispatches it to the plugin that registered the action. The plugin's\n // own callback does the work; the browser half only reports the id, and\n // the next poll brings back whatever that callback changed. A click on\n // an action the plugin already disposed answers { ok: false } — the\n // button was one poll tick stale, which is not a pet failure.\n panelAction: (id) => {\n petApi.panelAction(id).then((result) => {\n if (result.ok) pollNow()\n }, () => {\n // Ignore; next poll resyncs.\n })\n },\n feedbackDone: () => {\n setFeedback(null)\n },\n gameplay: {\n touch: (zone) => petApi.gameplayTouch(zone),\n setSkin: (skin) => petApi.setSkin(skin).then((result) => {\n if (result.ok) pollNow()\n return result\n }, () => ({ ok: false, error: 'transport' })),\n \n setMode: async (mode) => {\n if (mode === 'work') workTickGate.reset()\n return petApi.gameplaySetMode(mode)\n },\n workTick: async () => {\n // One adjudication per tick window, page-wide: suppress stale\n // duplicate intervals (HMR) re-playing the result track. The window\n // is the pet's own cadence, so a shorter tickMs is not downgraded.\n if (!workTickGate.allow(activeWorkTickMs(petStore))) {\n return { ok: true } as PetGameplayVerbResult\n }\n return petApi.gameplayWorkTick()\n },\n buy: (item) => petApi.gameplayBuy(item),\n },\n })\n\n // The pet is host-global (its state/display/interactions have no session\n // dimension), and the official rc.6 shell declares no root-scoped slot\n // for a global floating surface — the dock is session-scoped, so a pet\n // mounted there would vanish on the new-conversation screen (issue #48).\n // The entry therefore mounts straight onto document.body via a single\n // React root for the page lifetime: PetSprite portals itself to body\n // when visible, and the hidden-state summon button is fixed-positioned.\n //\n // Cross-instance single-mount guard (issue #785): take over the\n // page-global slot first — the previous bundle instance's fiber may\n // still be draining during a client reload, so unmount its React root\n // and remove its container — then sweep containers left behind by\n // instances that predate the teardown registry, so this mount is the\n // page's only [data-dsh-pet-root].\n takeoverPetUiTeardown()\n for (const stale of Array.from(document.querySelectorAll('div[data-dsh-pet-root]'))) {\n stale.remove()\n }\n const container = document.createElement('div')\n container.dataset.dshPetRoot = ''\n container.dataset.dshPlugin = 'pet'\n document.body.appendChild(container)\n const petRoot = createRoot(container)\n // The sprite chrome portals into THIS root (not document.body): the\n // root then owns the whole surface, so a root-keyed suppressor (the\n // portrait mobile layer, which hides [data-dsh-plugin=\"pet\"]) really\n // hides the sprite instead of missing the portaled float.\n //\n // The floating surface has no session-scoped locale seat, so it must be\n // handed the framework one explicitly. Resolving its copy from the\n // plugin's own zh/en dictionary keyed on <html lang> sent every\n // registered language except English to Chinese: a ru/ja/de page showed a\n // Chinese panel while the settings card beside it was translated. Binding\n // the 'pet' namespace instead follows the active language, the English\n // fallback, and every language pack that registers a dictionary for it\n // (the settings section label already resolves through the same seat).\n const renderPet = (): void => {\n petRoot.render(createElement(PetDockEntry, {\n ...injected(),\n t: ctx.locale.bind(NS),\n // The active locale rides the same mount as the translate seat so a\n // pet-declared English rank name follows the UI language.\n lang: ctx.locale.getLocale().active,\n portalTarget: container,\n }))\n }\n renderPet()\n // Re-render on a language switch instead of waiting for the next poll\n // tick: the declared rank ladder's nameEn applies immediately.\n const unsubscribeLocale = ctx.locale.subscribe(renderPet)\n\n let uiGone = false\n disposeUi = () => {\n if (uiGone) return\n uiGone = true\n clearUiTeardown?.()\n clearUiTeardown = undefined\n unsubscribeLocale()\n petRoot.unmount()\n container.remove()\n disposePoll()\n disposeSessionWatch()\n disposeUi = undefined\n }\n // The slot teardown is the takeover hook a later apply body runs; it\n // marks this instance terminal so a late settings callback from the\n // still-draining instance cannot remount a second pet.\n clearUiTeardown = registerPetUiTeardown(() => {\n uiDead = true\n disposeUi?.()\n })\n } else if (!uiDead && !enabled() && disposeUi !== undefined) {\n disposeUi()\n disposeUi = undefined\n }\n }\n // The settings subscription and the pet UI lifetime follow the fiber\n // (issue #785): disposal drops the subscription and tears the UI down\n // (terminal), so a hot-reloaded or re-injected bundle never leaves the\n // previous React root, container, or poll loop behind on document.body.\n const unsubscribeSettings = settingsForm.subscribe(syncUi)\n ctx.effect(\n () => () => {\n unsubscribeSettings()\n // Release the deferred form's retry timer and its mirror subscription so a\n // disposed fiber can never bind or publish after teardown.\n settingsForm.dispose()\n killUi()\n },\n 'pet: client lifecycle',\n )\n syncUi()\n}\n"],"ignoreList":[2],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAyDA,SAAgB,iBAA8D;GAC5E,OAAO,YAAY;IACjB,aAAyB;KACvB,UAAU;KACV,MAAM,CAAC;KACP,O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AAU,SAAS;KAExD,IAAI,SAAS;KACb,kBAAkB;MAChB,IAAI,QAAQ;MACZ,SAAS;MACT,kBAAkB;MAClB,kBAAkB,KAAA;MAClB,kBAAkB;MAClB,QAAQ,QAAQ;MAChB,UAAU,OAAO;MACjB,YAAY;MACZ,oBAAoB;MACpB,YAAY,KAAA;KACd;KAIA,kBAAkB,4BAA4B;MAC5C,SAAS;MACT,YAAY;KACd,CAAC;IACH,OAAO,IAAI,CAAC,UAAU,CAAC,QAAQ,KAAK,cAAc,KAAA,GAAW;KAC3D,UAAU;KACV,YAAY,KAAA;IACd;GACF;GAKA,MAAM,sBAAsB,aAAa,UAAU,MAAM;GACzD,IAAI,mBACU;IACV,oBAAoB;IAGpB,aAAa,QAAQ;IACrB,OAAO;GACT,GACA,uBACF;GACA,OAAO;EACT"}
1
+ {"version":3,"file":"client.js","names":["useRef","styles","useState","createPortal","useRef","useState","useRef","useState","useRef","isValidElement","cloneElement","useSyncExternalStore","useState","useRef","styles","useSyncExternalStore","useRef","styles","useState","useRef","css","useRef","Children","css","createContext","useState","useRef","css","useContext","useCallback","sectionCss","sectionCss","createRoot","createElement"],"sources":["../src/client/pet-store.ts","../src/client/work-tick-gate.ts","../node_modules/.pnpm/clsx@2.1.1/node_modules/clsx/dist/clsx.mjs","../src/persist.ts","../src/announce.ts","../src/state.ts","../src/client/spritesheet.ts","../src/client/sequences.ts","../src/client/PetSprite.tsx","../src/client/drag-stream.ts","../src/client/renderers/registry.ts","../src/client/phase-stream.ts","../src/client/renderers/live2d/Live2dVisualMount.tsx","../src/client/renderers/Frames2dVisualMount.tsx","../src/client/renderers/PetRendererSwitch.tsx","../src/gameplay.ts","../src/client/gameplay-hud.tsx","../src/client/PetDockEntry.tsx","../src/contracts/renderer.ts","../src/client/renderers/live2d/runtime.ts","../src/client/renderers/live2d.ts","../src/client/renderers/frames2d.ts","../src/client/ui-teardown.ts","../src/client/RangeBubble.tsx","../src/client/SegmentGroup.tsx","../src/client/PluginSettingsCard.tsx","../src/client/PetPreview.tsx","../src/client/settings-form.ts","../src/client/PetSettingsCard.tsx","../src/client/locales.ts","../src/client/web-extension-page.ts","../src/client/settings-registration.ts","../src/client/main-session.ts","../src/client/telemetry.ts","../src/client/index.ts"],"sourcesContent":["/**\n * Browser-side pet store: the pet state snapshot plus transient UI feedback\n * (reaction bubbles), written only through the store's audit actions. The\n * RPC polling and interactions live in the plugin apply body; components\n * only ever read snapshots.\n * @module @linxin666/dsh-pet/client/pet-store\n */\n\nimport { defineStore } from '@deepseek-ai/dsh-client-store'\nimport type { EngineStoreHandle, EngineStoreInstance } from '@deepseek-ai/dsh-client-store'\nimport type { PetGameplayStateView, PetStateView } from '../service.ts'\nimport type { PetInteraction } from '../affinity.ts'\nimport type { PetDefinition } from '../registry.ts'\n\n/** One transient reaction bubble on the pet. */\nexport interface PetFeedback {\n /** Bubble copy. */\n text: string\n /** Interaction kind driving the reaction animation. */\n kind: PetInteraction | 'none'\n /** Epoch ms when the bubble appeared (for expiry). */\n at: number\n}\n\n/** Pet UI state as consumers see it. */\nexport interface PetUiState {\n /** Latest host snapshot; null before the first successful fetch. */\n snapshot: PetStateView | null\n /** The registry list the host serves (atlas URLs + geometry + tracks). */\n pets: PetDefinition[]\n /** Fetch lifecycle. */\n state: 'loading' | 'ready' | 'error'\n /** Transport error message (for the debug surface), when any. */\n error: string | null\n /** Active reaction bubble, if any. */\n feedback: PetFeedback | null\n}\n\n/** Store write set. */\nexport type PetUiActions = {\n /** Replace the host snapshot (poll result). */\n setSnapshot: (draft: PetUiState, snapshot: PetStateView) => void\n /** Replace the registry list. */\n setPets: (draft: PetUiState, pets: PetDefinition[]) => void\n /** Mark the fetch lifecycle. */\n setState: (draft: PetUiState, state: PetUiState['state'], error: string | null) => void\n /** Show a reaction bubble. */\n setFeedback: (draft: PetUiState, feedback: PetFeedback | null) => void\n /**\n * Patch the gameplay slice of the snapshot (verb write-back), so the HUD\n * reflects a touch/mode/buy result immediately instead of waiting one\n * poll tick (2 s).\n */\n setGameplayView: (draft: PetUiState, view: PetGameplayStateView) => void\n}\n\n/** Create the pet store handle (apply world only; never module-level). */\nexport function createPetStore(): EngineStoreHandle<PetUiState, PetUiActions> {\n return defineStore({\n init: (): PetUiState => ({\n snapshot: null,\n pets: [],\n state: 'loading',\n error: null,\n feedback: null,\n }),\n actions: {\n setSnapshot: (draft, snapshot) => {\n // The 2 s poll republishes the full snapshot even while the pet is\n // idle. Skipping an unchanged payload keeps immer's produce at zero\n // modifications, so zustand never notifies and the whole sprite tree\n // skips the re-render. Equality is JSON-based and skip-only: both\n // sides come from the same host serializer, and any mismatch falls\n // through to the normal publish — the failure mode is one extra\n // render, never a stale pet.\n if (draft.state === 'ready' && draft.error === null && sameSnapshot(draft.snapshot, snapshot)) return\n draft.snapshot = snapshot\n draft.state = 'ready'\n draft.error = null\n },\n setPets: (draft, pets) => {\n draft.pets = pets\n },\n setState: (draft, state, error) => {\n draft.state = state\n draft.error = error\n },\n setFeedback: (draft, feedback) => {\n draft.feedback = feedback\n },\n setGameplayView: (draft, view) => {\n if (draft.snapshot !== null) draft.snapshot = { ...draft.snapshot, gameplay: view }\n },\n },\n })\n}\n\nexport type { PetInteraction }\n\n/**\n * Content equality for consecutive poll snapshots. JSON compare, not field\n * enumeration: an exact string match is the only way to skip the publish, so\n * a missed field can never freeze the UI — it can only cost the render the\n * optimization exists to save.\n */\nfunction sameSnapshot(previous: PetStateView | null, next: PetStateView): boolean {\n return previous !== null && JSON.stringify(previous) === JSON.stringify(next)\n}\n\n/**\n * A live pet store instance (one per host, owned by the plugin apply body —\n * the pet itself is host-global, so its UI state must not ride the slot\n * system's per-session store scoping).\n */\nexport type PetStoreInstance = EngineStoreInstance<PetUiState, PetUiActions>\n\n","/**\n * Page-wide work-tick gate for the pet's work mode. Hot reloads can leave\n * several GameplayHud instances alive, each running its own work interval;\n * without a shared gate every interval would call workTick and each stale call\n * re-rolls, re-grants treats and re-plays the success/fail track, so the\n * outcome appears to play several times per window. The gate accepts the first\n * adjudication of a window and silently suppresses the duplicates that follow.\n *\n * The window is the active pet's own `gameplay.work.tickMs`, not a constant: a\n * pet configured with a shorter cadence must actually adjudicate that often,\n * while a fixed window would downgrade it without saying so (#1494).\n * @module @linxin666/dsh-pet/client/work-tick-gate\n */\n\n/** Window used when the active pet declares no work cadence. */\nexport const DEFAULT_WORK_TICK_MS = 10_000\n\n/** Manifest bounds for `gameplay.work.tickMs` (src/gameplay.ts). */\nconst MIN_WORK_TICK_MS = 1_000\nconst MAX_WORK_TICK_MS = 60_000\n\n/**\n * The gate window for one pet: its configured cadence, clamped to the manifest's\n * own bounds so a malformed registry entry cannot disable or flood the gate.\n * @param tickMs - the active definition's `gameplay.work.tickMs`, when it has one.\n * @returns the window in milliseconds.\n */\nexport function workTickWindowMs(tickMs: number | undefined): number {\n if (typeof tickMs !== 'number' || !Number.isFinite(tickMs)) return DEFAULT_WORK_TICK_MS\n return Math.min(MAX_WORK_TICK_MS, Math.max(MIN_WORK_TICK_MS, tickMs))\n}\n\n/** The shared work-tick gate. */\nexport interface WorkTickGate {\n /**\n * Admit one adjudication for the current window.\n * @param tickMs - the active pet's configured work cadence.\n * @returns true when this call may adjudicate, false for a duplicate.\n */\n allow: (tickMs: number | undefined) => boolean\n /** Forget the last adjudication (used when work mode is entered). */\n reset: () => void\n}\n\n/**\n * Create a gate.\n * @param now - the clock, injectable so tests control the window.\n * @returns the gate over that clock.\n */\nexport function createWorkTickGate(now: () => number = Date.now): WorkTickGate {\n let lastAdjudicatedAt = 0\n return {\n allow: (tickMs) => {\n const at = now()\n if (at - lastAdjudicatedAt < workTickWindowMs(tickMs)) return false\n lastAdjudicatedAt = at\n return true\n },\n reset: () => {\n lastAdjudicatedAt = 0\n },\n }\n}\n","function r(e){var t,f,n=\"\";if(\"string\"==typeof e||\"number\"==typeof e)n+=e;else if(\"object\"==typeof e)if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(f=r(e[t]))&&(n&&(n+=\" \"),n+=f)}else for(f in e)e[f]&&(n&&(n+=\" \"),n+=f);return n}export function clsx(){for(var e,t,f=0,n=\"\",o=arguments.length;f<o;f++)(e=arguments[f])&&(t=r(e))&&(n&&(n+=\" \"),n+=t);return n}export default clsx;","/**\n * Pet persistence — tiny JSON store for affinity + display config, written\n * under $DSH_HOME (defaults to ~/.dsh) as `pet.json`. Deliberately minimal:\n * one file, atomic rename write, tolerant read (corrupt file → defaults).\n * @module @linxin666/dsh-pet/persist\n */\n\nimport { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { dshHome } from './dsh-home.ts'\nimport { AFFINITY_MAX, emptyAffinity, type AffinityState } from './affinity.ts'\nimport { defaultTreatConfig, emptyTreatLedger, type TreatLedger } from './treats.ts'\nimport { DEFAULT_PET_ID, DEFAULT_PET_NAME } from './defaults.ts'\nimport type { PetGameplayState } from './gameplay.ts'\n\nexport { DEFAULT_PET_ID, DEFAULT_PET_NAME } from './defaults.ts'\n\n/** Display configuration the user can tweak. */\nexport interface PetDisplayConfig {\n /** Master switch. */\n visible: boolean\n /** Scale of the rendered pet in px (sprite cell height). */\n size: number\n /** Horizontal inset from the viewport right edge, px. */\n right: number\n /** Vertical inset from the viewport bottom edge, px. */\n bottom: number\n /**\n * Multiplier on the bubble typography's automatic size following (#1549).\n * The rendered bubble scale is `size / 160 * bubbleScale`, bounded by\n * {@link BUBBLE_FONT_MIN_PX}..{@link BUBBLE_FONT_MAX_PX}, so 1 keeps the\n * 12px baseline the stylesheet was drawn for at the default 160px pet.\n */\n bubbleScale: number\n}\n\nexport const defaultDisplayConfig: PetDisplayConfig = {\n visible: true,\n size: 160,\n right: 24,\n bottom: 120,\n bubbleScale: 1,\n}\n\n/** Display value bounds (shared by load-time validation and setConfig). */\nexport const DISPLAY_SIZE_MIN = 32\nexport const DISPLAY_SIZE_MAX = 1024\nexport const DISPLAY_INSET_MAX = 10_000\n\n/** Bubble typography bounds (issue #1549). */\nexport const BUBBLE_SCALE_MIN = 0.5\nexport const BUBBLE_SCALE_MAX = 2\n/** Pixel size the bubble stylesheet was drawn for, at the default pet size. */\nexport const BUBBLE_BASE_FONT_PX = 12\n/** Pet size that baseline matches; other sizes scale the bubble with them. */\nexport const BUBBLE_BASE_SIZE_PX = 160\n/** Readability floor and layout ceiling of the scaled bubble text. */\nexport const BUBBLE_FONT_MIN_PX = 10\nexport const BUBBLE_FONT_MAX_PX = 24\n\n/**\n * Bubble typography scale for one display config (issue #1549): the bubble\n * follows the pet's own size so a shrunk pet does not carry a full-size\n * bubble, and the user's multiplier rides on top. The result is a CSS ratio\n * against {@link BUBBLE_BASE_FONT_PX}, bounded so the text never drops below\n * the readability floor or outgrows the pet. `bubbleScale` is optional at\n * runtime: a host that predates the field (a rolling update, or any snapshot\n * that omits it) falls back to the baseline, because a NaN ratio written into\n * `--pet-bubble-scale` collapses every bubble's text to zero.\n * @param display - display config; `bubbleScale` may be absent on older hosts.\n * @returns the ratio written to `--pet-bubble-scale` (always finite).\n */\nexport function bubbleScaleFor(display: Pick<PetDisplayConfig, 'size'> & { bubbleScale?: number }): number {\n // Guard the arithmetic, not just the clamp: Math.min/max propagate NaN, so a\n // missing or non-finite field would otherwise reach the stylesheet.\n const size = Number.isFinite(display.size) ? display.size : BUBBLE_BASE_SIZE_PX\n const multiplier = typeof display.bubbleScale === 'number' && Number.isFinite(display.bubbleScale)\n ? display.bubbleScale\n : 1\n const scaled = (size / BUBBLE_BASE_SIZE_PX) * multiplier\n const min = BUBBLE_FONT_MIN_PX / BUBBLE_BASE_FONT_PX\n const max = BUBBLE_FONT_MAX_PX / BUBBLE_BASE_FONT_PX\n return Math.round(Math.min(max, Math.max(min, scaled)) * 100) / 100\n}\n\n/** Everything persisted for the pet. */\nexport interface PetPersist {\n /** Selected pet id (a registry entry; clamped at service startup). */\n petId: string\n /**\n * Per-pet display names keyed by pet id. A pet without an entry falls back\n * to its manifest displayName, so only user renames are stored here.\n */\n names: Record<string, string>\n /**\n * Per-pet selected frames2d skin id (keyed by pet id). Skin ids are manifest\n * data, so a stale entry (skin renamed or removed, pet swapped) is ignored\n * when the state view is built instead of pinning an unresolvable track.\n */\n skins: Record<string, string>\n affinity: AffinityState\n /** Treat (小鱼干) stock ledger. */\n treats: TreatLedger\n display: PetDisplayConfig\n /** Per-pet gameplay state (stats/currencies/mode), keyed by pet id. */\n gameplay: Record<string, PetGameplayState>\n}\n\n/** Name constraints. */\nexport const PET_NAME_MAX_LENGTH = 20\n\nexport function emptyPersist(): PetPersist {\n return {\n petId: DEFAULT_PET_ID,\n names: {},\n skins: {},\n affinity: emptyAffinity(),\n treats: emptyTreatLedger(),\n display: { ...defaultDisplayConfig },\n gameplay: {},\n }\n}\n\n/**\n * Resolve the persistence directory ($DSH_HOME or ~/.dsh). Delegates to the\n * shared {@link dshHome} resolution so the plugin family keeps one DSH_HOME\n * definition (env override, ~ expansion, cwd-joined relative values).\n */\nexport function petHomeDir(): string {\n return dshHome()\n}\n\n/** Numeric field guard: finite numbers only, else the fallback. */\nfunction finiteNum(value: unknown, fallback: number): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : fallback\n}\n\n/** A persisted document from any schema era (legacy carried a flat `name`). */\ntype PetPersistDocument = Partial<PetPersist> & { name?: unknown }\n\n/** Sanitize the per-pet names map (string keys, non-empty trimmed values). */\nfunction loadPetNames(parsed: PetPersistDocument): Record<string, string> {\n const names: Record<string, string> = {}\n if (typeof parsed.names !== 'object' || parsed.names === null) return names\n for (const [id, value] of Object.entries(parsed.names as Record<string, unknown>)) {\n if (id === '' || typeof value !== 'string') continue\n const name = value.trim()\n if (name === '') continue\n names[id] = name.slice(0, PET_NAME_MAX_LENGTH)\n }\n return names\n}\n\n/** Sanitize the per-pet skin selection map (string keys, non-empty trimmed values). */\nfunction loadPetSkins(parsed: PetPersistDocument): Record<string, string> {\n const skins: Record<string, string> = {}\n if (typeof parsed.skins !== 'object' || parsed.skins === null) return skins\n for (const [id, value] of Object.entries(parsed.skins as Record<string, unknown>)) {\n if (id === '' || typeof value !== 'string') continue\n const skin = value.trim()\n if (skin === '') continue\n skins[id] = skin\n }\n return skins\n}\n\n/** Clamp one count/score into [0, max]. */\nfunction clamp(value: number, max: number): number {\n return Math.min(max, Math.max(0, value))\n}\n\n/** Absolute numeric ceilings applied at load (manifest clamps refine these). */\nconst GAMEPLAY_LOAD_STAT_CAP = 1_000_000\nconst GAMEPLAY_LOAD_CURRENCY_CAP = 9_999_999\n\n/** Sanitize the persisted per-pet gameplay map. */\nfunction loadGameplay(parsed: PetPersistDocument): Record<string, PetGameplayState> {\n const result: Record<string, PetGameplayState> = {}\n if (typeof parsed.gameplay !== 'object' || parsed.gameplay === null) return result\n for (const [petId, raw] of Object.entries(parsed.gameplay as Record<string, unknown>)) {\n if (petId === '' || typeof raw !== 'object' || raw === null) continue\n const record = raw as Partial<PetGameplayState>\n const stats: Record<string, number> = {}\n if (typeof record.stats === 'object' && record.stats !== null) {\n for (const [key, value] of Object.entries(record.stats)) {\n if (key === '' || typeof value !== 'number' || !Number.isFinite(value)) continue\n stats[key] = Math.min(GAMEPLAY_LOAD_STAT_CAP, Math.max(0, value))\n }\n }\n const currencies: Record<string, number> = {}\n if (typeof record.currencies === 'object' && record.currencies !== null) {\n for (const [key, value] of Object.entries(record.currencies)) {\n if (key === '' || typeof value !== 'number' || !Number.isFinite(value)) continue\n currencies[key] = Math.min(GAMEPLAY_LOAD_CURRENCY_CAP, Math.max(0, Math.floor(value)))\n }\n }\n const item: PetGameplayState = {\n stats,\n currencies,\n // Any non-empty id survives the round trip; whether it is still declared\n // is settled against the manifest when the mode is read back.\n mode: typeof record.mode === 'string' && record.mode.length > 0 && record.mode.length <= 24 ? record.mode : null,\n settledAt: clamp(finiteNum(record.settledAt, 0), Number.MAX_SAFE_INTEGER),\n }\n if (typeof record.incomeCarryMs === 'number' && Number.isFinite(record.incomeCarryMs)) {\n item.incomeCarryMs = Math.max(0, record.incomeCarryMs)\n }\n if (typeof record.restoreCarryMs === 'number' && Number.isFinite(record.restoreCarryMs)) {\n item.restoreCarryMs = Math.max(0, record.restoreCarryMs)\n }\n result[petId] = item\n }\n return result\n}\n\n/** Load persisted state; missing or corrupt files fall back to defaults. */\nexport function loadPetPersist(dir: string = petHomeDir()): PetPersist {\n try {\n const raw = readFileSync(join(dir, 'pet.json'), 'utf8')\n const parsed = JSON.parse(raw) as PetPersistDocument\n const base = emptyPersist()\n const rawAffinity = (parsed.affinity ?? {}) as Partial<AffinityState>\n const affinity: AffinityState = {\n points: clamp(finiteNum(rawAffinity.points, 0), AFFINITY_MAX),\n lastPetAt: clamp(finiteNum(rawAffinity.lastPetAt, 0), Number.MAX_SAFE_INTEGER),\n lastFeedAt: clamp(finiteNum(rawAffinity.lastFeedAt, 0), Number.MAX_SAFE_INTEGER),\n pets: clamp(finiteNum(rawAffinity.pets, 0), Number.MAX_SAFE_INTEGER),\n feeds: clamp(finiteNum(rawAffinity.feeds, 0), Number.MAX_SAFE_INTEGER),\n petRejects: clamp(finiteNum(rawAffinity.petRejects, 0), Number.MAX_SAFE_INTEGER),\n feedRejects: clamp(finiteNum(rawAffinity.feedRejects, 0), Number.MAX_SAFE_INTEGER),\n turns: clamp(finiteNum(rawAffinity.turns, 0), Number.MAX_SAFE_INTEGER),\n }\n const rawTreats = (parsed.treats ?? {}) as Partial<TreatLedger>\n const treats: TreatLedger = {\n treats: clamp(finiteNum(rawTreats.treats, 0), defaultTreatConfig.maxTreats),\n lastTreatGrantAt: clamp(finiteNum(rawTreats.lastTreatGrantAt, 0), Number.MAX_SAFE_INTEGER),\n turnsAtLastTreatGrant: clamp(finiteNum(rawTreats.turnsAtLastTreatGrant, 0), Number.MAX_SAFE_INTEGER),\n }\n const rawDisplay = (parsed.display ?? {}) as Partial<PetDisplayConfig>\n const display: PetDisplayConfig = {\n visible: typeof rawDisplay.visible === 'boolean' ? rawDisplay.visible : base.display.visible,\n // The settings schema requires whole pixels; drag positions are\n // clamped but not integral, so round at the persistence boundary.\n size: Math.round(Math.min(DISPLAY_SIZE_MAX, Math.max(DISPLAY_SIZE_MIN, finiteNum(rawDisplay.size, base.display.size)))),\n right: Math.round(clamp(finiteNum(rawDisplay.right, base.display.right), DISPLAY_INSET_MAX)),\n bottom: Math.round(clamp(finiteNum(rawDisplay.bottom, base.display.bottom), DISPLAY_INSET_MAX)),\n // Fractional on purpose: the multiplier is a ratio, not a pixel count.\n bubbleScale: Math.min(BUBBLE_SCALE_MAX, Math.max(BUBBLE_SCALE_MIN, finiteNum(rawDisplay.bubbleScale, base.display.bubbleScale))),\n }\n const petId = typeof parsed.petId === 'string' && parsed.petId.trim() !== ''\n ? parsed.petId.trim()\n : base.petId\n const names = loadPetNames(parsed)\n // Legacy migration: pre-registry installs persisted one flat `name`\n // field. Move it onto the selected pet (the legacy whale-girl unless the\n // file already names another pet) so renames survive the upgrade.\n if (typeof parsed.name === 'string' && parsed.name.trim() !== '' && names[petId] === undefined) {\n names[petId] = parsed.name.trim().slice(0, PET_NAME_MAX_LENGTH)\n }\n return {\n petId,\n names,\n skins: loadPetSkins(parsed),\n affinity,\n treats,\n display,\n gameplay: loadGameplay(parsed),\n }\n } catch {\n return emptyPersist()\n }\n}\n\n/** Atomically persist state (write temp + rename). */\nexport function savePetPersist(data: PetPersist, dir: string = petHomeDir()): void {\n mkdirSync(dir, { recursive: true })\n const target = join(dir, 'pet.json')\n const tmp = `${target}.tmp`\n writeFileSync(tmp, JSON.stringify(data, null, 2), 'utf8')\n renameSync(tmp, target)\n}\n","/**\n * The pet announcement-bubble contract: a sibling plugin\n * pushes one structured announcement through `pet.announce(...)`, the host\n * validates it into a bounded payload, and the browser half renders it as a\n * dedicated, specially styled bubble above the session bubble stack.\n *\n * One slot per publisher (issue #1812): `source` is the slot key, so two\n * announcing plugins coexist instead of displacing each other, and each keeps\n * its own TTL. The single-slot contract this replaced is kept on the wire as\n * the freshest entry, so an older browser half keeps working unchanged.\n *\n * The validation lives in this pure module so the wire contract has exactly\n * one home and stays testable without the cordis service.\n * @module @linxin666/dsh-pet/announce\n */\n\n/** One plugin-authored announcement bubble. */\nexport interface PetAnnouncement {\n /** Authoring plugin's source tag (its own package short name). */\n source: string\n /** Bubble content kind: a spend estimate, an account balance, or a plan-quota status. */\n kind: 'balance' | 'cost' | 'plan'\n /** Lead text (usually the provider display name). */\n title: string\n /** Balance or today-spend amount, formatted for display (kinds `balance` and `cost`). */\n amount?: string\n /** Plan usage percent 0-100 (kind `plan`). */\n percent?: number\n /** ISO 8601 reset instant (kind `plan`). */\n resetAt?: string\n /** Short trailing note (plan tier name, peak-period status, currency code, ...). */\n note?: string\n /** Visual tone; drives the bubble's accent color. */\n tone: 'ok' | 'warn' | 'low'\n /** Freshness window in ms; an expired announcement stops rendering. */\n ttlMs: number\n /** Epoch ms the announcement arrived. */\n at: number\n}\n\n/** Default freshness window. */\nexport const ANNOUNCE_DEFAULT_TTL_MS = 10_000\n\n/**\n * How many publishers can hold an announcement bubble at once (issue #1812).\n *\n * The contract has exactly one slot per `source` — that is the whole upgrade\n * from the single-slot design — but the pet's bubble stack is a finite column,\n * so the table is bounded rather than open. The bound is deliberately above the\n * realistic publisher count (a quota bubble, a balance bubble, a notification):\n * it exists so a misbehaving publisher that rotates `source` per bubble cannot\n * grow the pet's stack without limit.\n */\nexport const MAX_ANNOUNCEMENTS = 4\n\n/**\n * Hard TTL ceiling. A repeating announcer declares its poll cadence as\n * the TTL, so an always-on bubble stays continuous across polls; the\n * ceiling means a source that dies unmounts its bubble within at most one\n * missed refresh cycle rather than lingering forever.\n */\nexport const ANNOUNCE_MAX_TTL_MS = 7_200_000\n\n/** Hard bounds: lengths and the TTL range (1 s .. 60 s). */\nconst TITLE_MAX = 80\nconst TEXT_MAX = 120\nconst SOURCE_MAX = 64\n\nfunction boundedString(value: unknown, max: number): string | undefined {\n if (typeof value !== 'string') return undefined\n const trimmed = value.trim()\n if (trimmed === '') return undefined\n return trimmed.length <= max ? trimmed : trimmed.slice(0, max)\n}\n\n/**\n * Validate one announce payload. Unknown fields are dropped, oversized text\n * is truncated, and anything structurally wrong resolves to undefined — a\n * malformed announcement never reaches the pet's bubble surface.\n * @param input - the payload a sibling plugin passed to `pet.announce`.\n * @param now - epoch ms the announcement arrived.\n */\nexport function parseAnnouncement(input: unknown, now: number): PetAnnouncement | undefined {\n if (typeof input !== 'object' || input === null) return undefined\n const data = input as Record<string, unknown>\n const source = boundedString(data.source, SOURCE_MAX)\n const title = boundedString(data.title, TITLE_MAX)\n if (source === undefined || title === undefined) return undefined\n const kind = data.kind === 'balance' || data.kind === 'cost' || data.kind === 'plan' ? data.kind : undefined\n if (kind === undefined) return undefined\n const amount = boundedString(data.amount, TEXT_MAX)\n const resetAt = boundedString(data.resetAt, TEXT_MAX)\n const note = boundedString(data.note, TITLE_MAX)\n const percent = typeof data.percent === 'number' && Number.isFinite(data.percent)\n ? Math.max(0, Math.min(100, data.percent))\n : undefined\n if ((kind === 'balance' || kind === 'cost') && amount === undefined) return undefined\n if (kind === 'plan' && percent === undefined) return undefined\n const tone = data.tone === 'warn' || data.tone === 'low' ? data.tone : 'ok'\n const ttlMs = typeof data.ttlMs === 'number' && Number.isFinite(data.ttlMs)\n ? Math.max(1000, Math.min(ANNOUNCE_MAX_TTL_MS, data.ttlMs))\n : ANNOUNCE_DEFAULT_TTL_MS\n return {\n source,\n kind,\n title,\n ...(amount !== undefined ? { amount } : {}),\n ...(percent !== undefined ? { percent } : {}),\n ...(resetAt !== undefined ? { resetAt } : {}),\n ...(note !== undefined ? { note } : {}),\n tone,\n ttlMs,\n at: now,\n }\n}\n\n/** Whether an announcement is still fresh at `now`. */\nexport function announcementFresh(announcement: PetAnnouncement, now: number): boolean {\n return now - announcement.at < announcement.ttlMs\n}\n","/**\n * Pet state machine — pure, clock-injected. Maps official DSH session activity\n * and the legacy `activity/status` vocabulary onto the 9-state Codex pet\n * animation contract, plus turn-end celebration and no-session idle.\n *\n * The machine is deliberately dumb: it holds the last input phase, the\n * animation decision, and a one-shot \"celebration\" window after `done` so the\n * pet visibly jumps before settling back to idle. Everything here is a pure\n * function of (input, nowMs); persistence and RPC live in the service.\n * @module @linxin666/dsh-pet/state\n */\n\n/** Activity phases understood by the pet host. */\nexport type ActivityPhase = 'idle' | 'waiting' | 'thinking' | 'tool' | 'review' | 'done' | 'failed'\n\n/** The Codex-compatible 9-state animation contract (spritesheet rows). */\nexport type PetAnimation =\n | 'idle'\n | 'running-right'\n | 'running-left'\n | 'waving'\n | 'jumping'\n | 'failed'\n | 'waiting'\n | 'running'\n | 'review'\n\n/** One input snapshot consumed by the machine. */\nexport interface PetStateInput {\n /** Current activity phase of the active session. */\n phase: ActivityPhase\n /** Human-readable status line (plain text). */\n line?: string\n /** Playful phrase from the activity tracker, when any. */\n phrase?: string\n}\n\n/** Animation decision plus the copy the pet should show. */\nexport interface PetStateSnapshot {\n /** Which animation track to play. */\n animation: PetAnimation\n /** Optional status bubble copy (line or phrase), shown while active. */\n bubble?: string\n /** Wall-clock ms this animation started (client can sync loops). */\n animationStartedAt: number\n /** Raw phase, for debugging and client-side rendering decisions. */\n phase: ActivityPhase\n /** True when there is an active session (pet mounted). */\n sessionActive: boolean\n}\n\n/** Machine configuration. */\nexport interface PetStateConfig {\n /** Celebration window after `done` before settling to idle, ms (default 2400). */\n celebrateMs: number\n /** Failure display window before settling to idle, ms (default 2400). */\n failureMs: number\n}\n\nexport const defaultPetStateConfig: PetStateConfig = { celebrateMs: 2400, failureMs: 2400 }\n\n/**\n * Map one activity phase onto the animation contract.\n * - thinking → `running` and tool → `running-right` (focused work).\n * - review → `review` while answer text is streaming.\n * - waiting → `waiting` (expectant pose, needs user input).\n * - done → `jumping` (celebration), then back to `idle` after the window.\n * - failed → `failed` briefly, then back to `idle`.\n * - idle → `idle` (calm breathing loop).\n */\nexport function animationForPhase(phase: ActivityPhase): PetAnimation {\n switch (phase) {\n case 'thinking': return 'running'\n case 'tool': return 'running-right'\n case 'review': return 'review'\n case 'waiting': return 'waiting'\n case 'done': return 'jumping'\n case 'failed': return 'failed'\n case 'idle': return 'idle'\n }\n}\n\n/** The spritesheet row index for one animation track. */\nexport function rowOf(animation: PetAnimation): number {\n const rows: Record<PetAnimation, number> = {\n 'idle': 0,\n 'running-right': 1,\n 'running-left': 2,\n 'waving': 3,\n 'jumping': 4,\n 'failed': 5,\n 'waiting': 6,\n 'running': 7,\n 'review': 8,\n }\n return rows[animation]\n}\n\n/**\n * PetStateMachine — one instance per host process. Holds only the latest\n * input snapshot and terminal-state timing; no storage, no side effects.\n */\nexport class PetStateMachine {\n private phase: ActivityPhase = 'idle'\n private line: string | undefined\n private phrase: string | undefined\n private sessionActive = false\n private doneAt: number | undefined\n private failedAt: number | undefined\n private readonly config: PetStateConfig\n\n constructor(\n config: Partial<PetStateConfig> = defaultPetStateConfig,\n private readonly now: () => number = Date.now,\n ) {\n this.config = { ...defaultPetStateConfig, ...config }\n }\n\n /** Consume one projected activity update. */\n onActivityStatus(input: PetStateInput): void {\n this.phase = input.phase\n this.line = input.line\n this.phrase = input.phrase\n this.doneAt = input.phase === 'done' ? this.now() : undefined\n this.failedAt = input.phase === 'failed' ? this.now() : undefined\n }\n\n /** A session became the active one (or a fresh session started). */\n onSessionActive(): void {\n this.sessionActive = true\n }\n\n /** The active session was disposed (or none left). */\n onSessionDisposed(): void {\n this.sessionActive = false\n this.phase = 'idle'\n this.line = undefined\n this.phrase = undefined\n this.doneAt = undefined\n this.failedAt = undefined\n }\n\n /** Render the current animation decision. */\n render(): PetStateSnapshot {\n const nowMs = this.now()\n let animation = animationForPhase(this.phase)\n const doneSettled = this.phase === 'done'\n && this.doneAt !== undefined\n && nowMs - this.doneAt >= this.config.celebrateMs\n const failedSettled = this.phase === 'failed'\n && this.failedAt !== undefined\n && nowMs - this.failedAt >= this.config.failureMs\n if (doneSettled || failedSettled) animation = 'idle'\n // Settled sessions never bubble: idle (e.g. an aborted/stopped turn),\n // completed celebration expiry, and failed display expiry all fall silent.\n const settled = this.phase === 'idle' || doneSettled || failedSettled\n const bubble = settled ? undefined : this.phrase ?? this.line\n return {\n animation,\n ...(bubble === undefined ? {} : { bubble }),\n animationStartedAt: nowMs,\n phase: this.phase,\n sessionActive: this.sessionActive,\n }\n }\n}\n","/**\n * Spritesheet geometry helpers — parameterized by the pet definition the\n * host serves over '/api/pet/pets', so the browser half renders any registry\n * entry without per-pet code. The per-track tables (frames, durations, loop,\n * fallback) also come from the registry; these helpers only place frames,\n * guard track lengths, and map the fixed 9-row animation contract.\n * @module @linxin666/dsh-pet/client/spritesheet\n */\n\nimport { rowOf, type PetAnimation } from '../state.ts'\nimport type { PetCell, PetTrackDef } from '../registry.ts'\n\n/** Animation track shape the frame loop consumes. */\nexport type TrackDef = PetTrackDef\n\n/** Row index of one animation track (the fixed 9-row contract). */\nexport function rowOfTrack(animation: PetAnimation): number {\n // The table itself lives in state.ts (rowOf) — the single source of truth.\n return rowOf(animation)\n}\n\n/**\n * Integer size of one cell after `scale`, in device-independent px.\n *\n * Rounding happens here, once, so the rendered atlas grid is integral end to\n * end (issue #17): `background-size` is this size times the column/row count\n * and every frame offset is an exact multiple of it. A fractional cell size\n * leaves each frame on a sub-pixel boundary — 192px cells at `display.size`\n * 160 scale to 147.69px — and the compositor then has to resample the whole\n * scaled atlas on every frame change instead of translating an already-scaled\n * bitmap by whole pixels. The pet advances a frame every 300-700 ms, so that\n * resample was running continuously for a background surface the size of the\n * sprite. A floor of 1px keeps a legally tiny display.size from collapsing the\n * cell to zero and rendering nothing.\n */\nexport function scaledCellSize(cell: PetCell, scale: number): { width: number; height: number } {\n return {\n width: Math.max(1, Math.round(cell.width * scale)),\n height: Math.max(1, Math.round(cell.height * scale)),\n }\n}\n\n/**\n * Background-position (px) of one frame cell within the scaled atlas.\n * The background image is scaled by `scale` (element size ÷ cell size), and\n * background-position offsets are applied in SCALED coordinates — using raw\n * atlas coordinates here would drift each frame by the scale factor and\n * render torn/overlapping frames. The scaled cell is quantized by\n * {@link scaledCellSize}, so the offset of frame N is exactly N whole cells:\n * the atlas is snapped to the pixel grid and a frame change is a plain\n * translate of the scaled bitmap.\n */\nexport function framePosition(cell: PetCell, row: number, col: number, scale = 1): { x: number; y: number } {\n const scaled = scaledCellSize(cell, scale)\n return { x: -col * scaled.width, y: -row * scaled.height }\n}\n\n/**\n * Trim a track to the actual frame count of its row (the manifest's per-row\n * counts are authoritative; this is a last-line guard against a definition\n * whose row count disagrees with its track table). A row with 0 detected\n * frames degrades to the first frame so the pet never renders blank.\n */\nexport function trimTrack(track: TrackDef, frameCount: number): TrackDef {\n const n = Math.max(1, Math.min(frameCount, track.frames.length, track.durations.length))\n return {\n frames: track.frames.slice(0, n),\n durations: track.durations.slice(0, n),\n loop: track.loop,\n ...(track.fallback === undefined ? {} : { fallback: track.fallback }),\n }\n}\n","/** Pure timing helpers for manifest-defined scene animation sequences. */\n\nimport type { PetTrackDef } from '../registry.ts'\nimport type { PetAnimation } from '../state.ts'\n\nexport interface SequenceFrame {\n animation: PetAnimation\n frameIndex: number\n}\n\n/**\n * Precomputed timeline for one looping sequence: the per-item duration table\n * is built once instead of per query. The sprite frame loop asks once per\n * frame change, where the per-call map/reduce is pure waste.\n */\nexport interface SequenceTimeline {\n frameAt(elapsedMs: number): SequenceFrame\n /**\n * Milliseconds from `elapsedMs` until the frame it lands on ends. The sprite\n * loop sleeps for exactly this long instead of polling at the screen refresh\n * rate (issue #17); the floor of 1 ms keeps a zero-length frame from turning\n * into a busy timer.\n */\n remainingAt(elapsedMs: number): number\n}\n\n/** One sequence position, with the residual offset inside its own frame. */\ninterface SequencePoint {\n animation: PetAnimation\n track: PetTrackDef\n frameIndex: number\n offsetInFrame: number\n}\n\n/** Build a {@link SequenceTimeline} over one manifest sequence. */\nexport function createSequenceTimeline(\n sequence: readonly PetAnimation[],\n tracks: Record<PetAnimation, PetTrackDef>,\n): SequenceTimeline {\n const itemDurations = sequence.map(animation => tracks[animation].durations.reduce((sum, value) => sum + value, 0))\n const sequenceDuration = itemDurations.reduce((sum, value) => sum + value, 0)\n // One traversal serves both queries: frameAt needs the index it lands on and\n // remainingAt needs how far into that frame it is, so resolving them\n // separately would walk the same tables twice for one loop tick.\n const locate = (elapsedMs: number): SequencePoint => {\n let offset = sequenceDuration > 0 ? Math.max(0, elapsedMs) % sequenceDuration : 0\n let itemIndex = 0\n while (itemIndex < sequence.length - 1 && offset >= itemDurations[itemIndex]!) {\n offset -= itemDurations[itemIndex]!\n itemIndex += 1\n }\n const animation = sequence[itemIndex]!\n const track = tracks[animation]\n let frameIndex = 0\n while (frameIndex < track.frames.length - 1 && offset >= track.durations[frameIndex]!) {\n offset -= track.durations[frameIndex]!\n frameIndex += 1\n }\n return { animation, track, frameIndex, offsetInFrame: offset }\n }\n return {\n frameAt(elapsedMs: number): SequenceFrame {\n const point = locate(elapsedMs)\n return { animation: point.animation, frameIndex: point.frameIndex }\n },\n remainingAt(elapsedMs: number): number {\n const point = locate(elapsedMs)\n return Math.max(1, (point.track.durations[point.frameIndex] ?? 0) - point.offsetInFrame)\n },\n }\n}\n\n/** Resolve the active track and frame after elapsed milliseconds of a looping sequence. */\nexport function sequenceFrameAt(\n sequence: readonly PetAnimation[],\n tracks: Record<PetAnimation, PetTrackDef>,\n elapsedMs: number,\n): SequenceFrame {\n return createSequenceTimeline(sequence, tracks).frameAt(elapsedMs)\n}\n","/**\n * Pet sprite companion component — the browser half's centerpiece. Renders a\n * fixed-position floating sprite (React portal onto document.body), plays\n * the track matching the host animation snapshot, and exposes the\n * interaction surface: click to pet, hover panel with feed/rename/hide, drag\n * to reposition (persisted via setConfig). Everything visual comes from the\n * pet definition the host serves ('/api/pet/pets' + the state snapshot's\n * pet id), so one component renders every registry entry.\n * @module @linxin666/dsh-pet/client/PetSprite\n */\n\nimport { useEffect, useLayoutEffect, useRef, useState } from 'react'\nimport type { CSSProperties, PointerEvent as ReactPointerEvent, ReactElement, ReactNode, ReactPortal } from 'react'\nimport { createPortal } from 'react-dom'\nimport clsx from 'clsx'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport { bubbleScaleFor, type PetDisplayConfig } from '../persist.ts'\nimport type { PetStateView } from '../service.ts'\nimport { announcementFresh, type PetAnnouncement } from '../announce.ts'\nimport type { PetDefinition } from '../registry.ts'\nimport type { GameplayBus } from './gameplay-hud.ts'\nimport type { PetRoamDirection } from '../gameplay.ts'\nimport type { DecorationView } from '../contracts/status-decoration.ts'\nimport type { PetFeedback } from './pet-store.ts'\nimport { framePosition, rowOfTrack, scaledCellSize, trimTrack } from './spritesheet.ts'\nimport { createSequenceTimeline } from './sequences.ts'\nimport { animationForPhase, type ActivityPhase, type PetAnimation } from '../state.ts'\nimport { NS } from './locales.ts'\nimport styles from './pet.module.css'\n\n/** Props injected by the plugin apply body (store actions + locale). */\nexport interface PetSpriteProps {\n /** Latest host snapshot; null while loading. */\n snapshot: PetStateView | null\n /** The selected pet's registry definition (atlas URL + geometry + tracks). */\n definition: PetDefinition\n /** Display configuration (persisted by the host). */\n display: PetDisplayConfig\n /** Active reaction bubble, if any. */\n feedback: PetFeedback | null\n /** Pet the sprite (click). */\n onPet: () => void\n /** Feed the sprite (panel button). */\n onFeed: () => void\n /** Hide the sprite (panel button). */\n onHide: () => void\n /** Persist a drag position. */\n onDragEnd: (right: number, bottom: number) => void\n /** Drag gesture notifications for renderers with a drag track (frames2d). */\n onDraggingChange?: (dragging: boolean) => void\n /** Rename the selected pet (persisted by the host). */\n onRename: (name: string) => void\n /**\n * Report a click on one plugin-registered action (issue #6). The buttons\n * themselves come from the state snapshot's `panelActions` slice, so the\n * panel renders exactly the registrations the host serves and adds nothing\n * of its own.\n */\n onPanelAction: (id: string) => void\n /** Navigate to the session one status bubble reports on. */\n onOpenSession: (sessionId: string) => void\n /** Clear the reaction bubble (after its CSS animation). */\n onFeedbackDone: () => void\n /**\n * Custom visual replacing the sprite2d atlas animation (pet-center M3).\n * The chrome (drag, bubbles, panel, tap economy) is untouched: the visual\n * renders inside the sprite box, and the atlas load + frame loop skip.\n */\n visual?: ReactNode\n /**\n * Gameplay overlay (miku-pet generalization): rendered inside the float\n * container so hover containment and stacking work unchanged. Absent for\n * pets without a gameplay block.\n */\n hud?: ReactNode\n /**\n * Gameplay tap sink: receives the tap point as sprite-box fractions\n * (0..1). When present the chrome reports the tap IN ADDITION to the\n * affinity pet; the HUD decides zones/no-ops.\n */\n onGameplayTap?: (fractionX: number, fractionY: number) => void\n /**\n * Gameplay entry (miku-pet generalization): when present the hover panel\n * renders a 玩法 action that opens/closes the gameplay card. The chrome\n * wires it to the HUD through the per-pet bus (openCard), mirroring the\n * onGameplayTap sink. Absent for pets without a gameplay block.\n */\n onGameplayMenu?: () => void\n /** Disable the drag gesture (gameplay work mode blocks dragging). */\n dragDisabled?: boolean\n /**\n * Per-pet coordination bus. The chrome registers `walk` here so the gameplay\n * HUD can roam the pet (the same two-way shape the HUD's `tap` uses).\n */\n bus?: GameplayBus\n /**\n * DOM node the floating chrome portals into. Defaults to document.body\n * (the legacy behavior); the plugin apply passes its owning root (the\n * [data-dsh-plugin=\"pet\"] container) so the root owns the whole surface\n * and a root-keyed suppressor (the portrait mobile layer) hides the pet\n * as one unit instead of missing the portaled sprite.\n */\n portalTarget?: Element\n /** Locale translate seat (namespace-bound). */\n t: TranslateNS<typeof NS>\n /**\n * Active UI locale id, used to pick a pet-declared English rank name\n * (`rankEn`). Defaults to the document language for direct mounts/tests.\n */\n lang?: string\n}\n\n/** Clamp a drag offset inside the viewport with a margin. */\nfunction clampOffset(value: number, max: number): number {\n return Math.max(0, Math.min(max, value))\n}\n\n/**\n * The status decoration ornament (pet-center M5, #567). Renders the active\n * phase's frame segment as a CSS-background strip at a compact bubble\n * height; prefers-reduced-motion holds the segment's first frame, and a\n * missing or undecodable asset simply paints nothing (CSS background\n * failure) — the bubble text is never disturbed. The span is aria-hidden;\n * the bubble keeps its own semantics untouched.\n */\nfunction StatusOrnament(props: { decoration: DecorationView; phase: ActivityPhase }): ReactElement | null {\n const { decoration, phase } = props\n const segment = decoration.phases[phase]\n const shown = segment !== undefined && segment !== 'hide'\n const segmentKey = segment !== undefined && segment !== 'hide' ? segment.from + ':' + segment.to : 'none'\n const spanRef = useRef<HTMLSpanElement | null>(null)\n const scale = 18 / decoration.cell.height\n const frameWidth = Math.round(decoration.cell.width * scale)\n const stripWidth = decoration.columns * frameWidth\n // Value-stable dependency key: the host serves a fresh DecorationView\n // object on every state poll (2 s), so the effect must not depend on the\n // object identity — otherwise each poll would cancel and restart the\n // frame loop and the animation would jump back to its first frame.\n const durationsKey = decoration.durations.join(',')\n useEffect(() => {\n if (segment === undefined || segment === 'hide') return\n const el = spanRef.current\n if (el === null) return\n const position = (index: number): string => (-index * frameWidth) + 'px 0px'\n const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches === true\n el.style.backgroundPosition = position(segment.from)\n // A single-frame segment (from === to) has nothing to animate: with\n // loop=true the wrap branch would reset index to the same frame and the\n // tick would keep rescheduling a no-op rAF forever. Settle on the one\n // frame instead — same as the reduced-motion static hold.\n if (reduceMotion || segment.from === segment.to) return\n let timer = 0\n let index = segment.from\n let elapsed = 0\n let last = performance.now()\n const tick = (): void => {\n const now = performance.now()\n const delta = now - last\n last = now\n elapsed += delta\n let duration = decoration.durations[index] ?? 120\n // The segment's frame rate (duration ms, typically 90-160) is far\n // below the rAF cadence, so a 60fps loop would spend ~90% of its\n // ticks doing nothing. Schedule by the remaining time to the next\n // frame instead — the ornament wakes once per frame, not once per\n // screen refresh. A late wake (background tab, jank) carries extra\n // elapsed time, so catch up every due frame like the sprite loop.\n if (elapsed >= duration) {\n do {\n elapsed -= duration\n if (index < segment.to) index += 1\n else if (decoration.loop) index = segment.from\n // Durations are per frame: a catch-up that crosses frames must\n // subtract and schedule with the frame it lands on, not the one\n // the tick started from.\n duration = decoration.durations[index] ?? 120\n } while (elapsed >= duration)\n // Only advance the background when the frame actually changes.\n el.style.backgroundPosition = position(index)\n }\n // A non-looping segment settles on its last frame; stop scheduling\n // instead of repainting the same position every frame.\n if (!decoration.loop && index === segment.to) return\n timer = window.setTimeout(tick, Math.max(1, duration - elapsed))\n }\n timer = window.setTimeout(tick, 0)\n return () => window.clearTimeout(timer)\n }, [shown, segmentKey, frameWidth, decoration.loop, durationsKey])\n if (!shown) return null\n return (\n <span\n ref={spanRef}\n aria-hidden=\"true\"\n data-dsh-pet-decoration={decoration.id}\n style={{\n display: 'inline-block',\n width: frameWidth,\n height: 18,\n marginRight: 6,\n verticalAlign: 'middle',\n flexShrink: 0,\n backgroundImage: 'url(' + decoration.entryUrl + ')',\n backgroundSize: stripWidth + 'px 18px',\n backgroundRepeat: 'no-repeat',\n backgroundPosition: '0px 0px',\n }}\n />\n )\n}\n\n/**\n * The announcement bubble (dsh-usage linkage): a dedicated, specially\n * designed surface for sibling-plugin facts — a balance or today-spend pill,\n * or a plan-quota card with a tone-tinted accent, a mini meter for percent\n * windows, and the reset instant. It rides the top of the session bubble\n * stack (column-reverse puts the DOM-last child farthest from the sprite)\n * and persists for its TTL instead of the short feedback pop.\n */\nfunction UsageAnnouncementBubble(props: { announcement: PetAnnouncement }): ReactNode {\n const { announcement } = props\n const tone = announcement.tone === 'low'\n ? styles.bubbleUsageLow\n : announcement.tone === 'warn'\n ? styles.bubbleUsageWarn\n : styles.bubbleUsageOk\n return (\n <div\n className={clsx(styles.bubble, styles.bubbleUsage, tone)}\n role=\"status\"\n aria-live=\"polite\"\n data-dsh-pet-announcement={announcement.source}\n >\n <span className={styles.bubbleUsageHead}>\n <span className={styles.bubbleUsageTitle}>{announcement.title}</span>\n {(announcement.kind === 'balance' || announcement.kind === 'cost') && announcement.amount !== undefined && (\n <span className={styles.bubbleUsageValue}>{announcement.amount}</span>\n )}\n {announcement.kind === 'plan' && announcement.percent !== undefined && (\n <span className={styles.bubbleUsageValue}>{Math.round(announcement.percent) + '%'}</span>\n )}\n </span>\n {announcement.kind === 'plan' && announcement.percent !== undefined && (\n <span className={styles.bubbleUsageMeter}>\n <span\n className={styles.bubbleUsageMeterFill}\n style={{ width: Math.min(100, Math.max(0, announcement.percent)) + '%' }}\n />\n </span>\n )}\n {announcement.note !== undefined && (\n <span className={styles.bubbleUsageNote}>{announcement.note}</span>\n )}\n </div>\n )\n}\n\n/**\n * The floating pet. The spritesheet frame advances on a timer scheduled for the\n * current frame's remaining time (per-frame durations come from the\n * definition's tracks), so the loop wakes once per frame change instead of once\n * per screen refresh; the atlas image is loaded once and the background\n * position is written straight to the sprite element (no per-frame React\n * state). Roaming writes the sprite's position the same way (issue #17).\n */\nexport function PetSprite(props: PetSpriteProps): ReactPortal {\n const { snapshot, definition, display, feedback } = props\n const spriteRef = useRef<HTMLDivElement | null>(null)\n const floatRef = useRef<HTMLDivElement | null>(null)\n const panelRef = useRef<HTMLDivElement | null>(null)\n // Whichever bubble surface is currently rendered (feedback, the session\n // stack, or the legacy status bubble) — only one exists at a time.\n const bubbleRef = useRef<HTMLDivElement | null>(null)\n const [imageReady, setImageReady] = useState(false)\n const [hovered, setHovered] = useState(false)\n // Multi-session bubble stack: collapsed by default (only the display\n // session's bubble + a '+N' badge), expanded on stack hover (peek) or by\n // tapping the badge (pinned, for touch). The display session's bubble\n // anchors the bottom of the stack and never moves when extras open above\n // it, so the pointer target cannot flicker.\n const [stackPeek, setStackPeek] = useState(false)\n const [stackPinned, setStackPinned] = useState(false)\n const [renaming, setRenaming] = useState(false)\n const [panelAbove, setPanelAbove] = useState(false)\n // Extra margin-bottom for the above-panel so it stacks clear of the\n // bubbles instead of overlapping them (both anchor at the sprite's top).\n const [panelLift, setPanelLift] = useState(0)\n const [nameDraft, setNameDraft] = useState('')\n // Explicit IME composition tracking: some input methods (WeChat IME on\n // Windows) report keydowns with isComposing === false mid-composition, so\n // the native flag alone is not a safe submit/cancel guard (#303).\n const composingRef = useRef(false)\n const [dragPos, setDragPos] = useState<{ right: number; bottom: number } | null>(null)\n const dragRef = useRef<{ startX: number; startY: number; right: number; bottom: number } | null>(null)\n const hideTimerRef = useRef<number | null>(null)\n const frameRef = useRef<{ track: PetAnimation | null; index: number; elapsed: number }>({\n track: null,\n index: 0,\n elapsed: 0,\n })\n\n const cell = definition.cell\n const columns = definition.columns\n const rows = definition.rows\n const tracks = definition.tracks\n const sequences = definition.sequences\n // Hover-panel chrome from the pet's voice pack (pet-center M4, issue\n // #677): every slot falls back to the i18n dictionary when unset. Stat\n // formats carry {rank}/{n}/{points} placeholders the host validated.\n const panel = definition.panel\n const panelLabel = (slot: 'feed' | 'rename' | 'hide' | 'confirm', i18n: string): string =>\n panel?.labels?.[slot] ?? i18n\n // The active rank name is display-only: a pet-declared ladder may carry an\n // English variant, while built-in names still resolve through the i18n\n // dictionary. `lang` is handed down by the mount; the document language is\n // the direct-mount/test fallback.\n const englishUi = (props.lang ?? (typeof document === 'undefined' ? 'zh' : document.documentElement.lang))\n .toLowerCase()\n .startsWith('en')\n const rankNameOf = (): string => {\n const rawRank = snapshot?.affinity.rank ?? '?'\n const rankEn = snapshot?.affinity.rankEn\n if (englishUi && rankEn !== undefined) return rankEn\n const rankKey = `pet.rank.name.${rawRank}`\n const localized = props.t(rankKey as never)\n return localized !== rankKey ? localized : rawRank\n }\n const panelStat = (\n slot: 'rank' | 'treats' | 'points',\n i18nKey: 'pet.rank' | 'pet.treats' | 'pet.points',\n values: Record<string, string | number>,\n ): string => {\n const format = panel?.stats?.[slot] ?? props.t(i18nKey, values)\n if (panel?.stats?.[slot] === undefined) return format\n // The host whitelists {rank}/{n}/{points} in every stat slot, so a pack\n // format may reference any of them; substitute all three live values\n // (the slot's own value plus the siblings) instead of only the slot's.\n // {rank} carries the effective name, so a pet ladder's English variant\n // also reaches a custom stat format.\n const all: Record<string, string | number> = {\n rank: values.rank !== undefined ? values.rank : rankNameOf(),\n n: snapshot?.treats.stocked ?? 0,\n points: snapshot?.affinity.points ?? 0,\n }\n let text = format\n for (const [name, value] of Object.entries(all)) text = text.replaceAll('{' + name + '}', String(value))\n return text\n }\n const panelShows = (action: 'feed' | 'rename' | 'hide'): boolean =>\n panel?.actions === undefined || panel.actions.includes(action)\n\n // Load the atlas once; the definition carries the authoritative per-row\n // frame counts and per-track durations, so nothing else is fetched. A\n // custom visual (pet-center M3) replaces the atlas entirely.\n useEffect(() => {\n if (props.visual !== undefined) return\n setImageReady(false)\n let cancelled = false\n let retryTimer: ReturnType<typeof setTimeout> | undefined\n let attempt = 0\n const maxAttempts = 3\n let activeImg: HTMLImageElement | null = null\n\n const loadAtlas = () => {\n const img = new Image()\n activeImg = img\n img.onload = () => {\n if (!cancelled) setImageReady(true)\n }\n img.onerror = () => {\n if (cancelled) return\n if (attempt < maxAttempts) {\n attempt += 1\n const delay = Math.min(1000 * Math.pow(2, attempt - 1), 8000)\n retryTimer = setTimeout(loadAtlas, delay)\n }\n }\n img.src = definition.atlasUrl\n }\n\n loadAtlas()\n\n return () => {\n cancelled = true\n if (retryTimer !== undefined) clearTimeout(retryTimer)\n if (activeImg !== null) {\n activeImg.onload = null\n activeImg.onerror = null\n }\n }\n }, [definition.atlasUrl, props.visual])\n\n // Frame loop: advance the current track and write background-position.\n // Offsets must be in SCALED coordinates (background-position applies to the\n // scaled background image), so the current sprite scale rides a ref that\n // the loop reads every tick. Under prefers-reduced-motion the sprite holds\n // its track's first frame instead of animating (presentation-only; the\n // animation state machine is untouched).\n const spriteScale = display.size / cell.height\n const phase = snapshot?.phase ?? 'idle'\n const animation = snapshot?.animation ?? 'idle'\n const scaleRef = useRef(spriteScale)\n scaleRef.current = spriteScale\n // The frame the loop painted last. A settled non-looping track leaves the\n // loop stopped, so a later scale change repaints it from here instead of\n // waking the loop.\n const paintedRef = useRef<{ row: number; col: number } | null>(null)\n useEffect(() => {\n if (props.visual !== undefined) return\n const reduceMotion = typeof window !== 'undefined'\n && window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches === true\n const sequence = animation === animationForPhase(phase) ? sequences?.[phase] : undefined\n // Sequence state hoisted into the effect scope: the cumulative duration\n // table and each item's trimmed track would otherwise be recomputed every\n // tick (map/reduce plus two slices per frame), the same waste the\n // single-track branch below avoids.\n const timeline = sequence === undefined ? undefined : createSequenceTimeline(sequence, tracks)\n const sequenceItems = sequence === undefined ? undefined : new Map(\n sequence.map(itemAnimation => {\n const itemRow = rowOfTrack(itemAnimation)\n return [itemAnimation, {\n row: itemRow,\n track: trimTrack(tracks[itemAnimation], rows[itemRow] ?? tracks[itemAnimation].frames.length),\n }]\n }),\n )\n const leadAnimation = sequence?.[0] ?? animation\n const row = rowOfTrack(leadAnimation)\n const track = trimTrack(tracks[leadAnimation], rows[row] ?? tracks[leadAnimation].frames.length)\n // Write one frame's offset to the sprite element, skipping the assignment\n // when the coordinates did not change. lastPosStr is the cache the whole\n // loop shares, so a tick that changes nothing costs no style write.\n let lastPosStr = ''\n const paint = (frameRow: number, col: number): void => {\n paintedRef.current = { row: frameRow, col }\n const pos = framePosition(cell, frameRow, col, scaleRef.current)\n const posStr = pos.x + 'px ' + pos.y + 'px'\n if (posStr === lastPosStr) return\n lastPosStr = posStr\n if (spriteRef.current !== null) {\n spriteRef.current.style.backgroundPosition = posStr\n }\n }\n // Paint one static sprite frame up front either way, so the pet is never\n // blank while the loop heat-up runs.\n paint(row, track.frames[0]!)\n if (reduceMotion) return\n let timer = 0\n let last = performance.now()\n let sequenceElapsed = 0\n // Sleep to the next frame boundary instead of waking on every screen\n // refresh: track durations are 300-700 ms, so a 60 Hz loop spent the vast\n // majority of its ticks proving that nothing had changed -- the same rule\n // StatusOrnament already follows. A late wake (throttled tab, jank) still\n // catches up every due frame, so the track keeps its own clock.\n const schedule = (delay: number): void => {\n timer = window.setTimeout(tick, Math.max(1, delay))\n }\n const tick = (): void => {\n timer = 0\n const now = performance.now()\n const delta = now - last\n last = now\n if (timeline !== undefined && sequenceItems !== undefined) {\n sequenceElapsed += delta\n const current = timeline.frameAt(sequenceElapsed)\n const item = sequenceItems.get(current.animation)!\n paint(item.row, item.track.frames[current.frameIndex]!)\n schedule(timeline.remainingAt(sequenceElapsed))\n return\n }\n // row/track come from the effect scope: they were computed once above\n // and this effect re-runs when animation/tracks/rows change, so the\n // per-frame recompute (trimTrack slices fresh arrays) is pure waste.\n const st = frameRef.current\n if (st.track !== animation) {\n st.track = animation\n st.index = 0\n st.elapsed = 0\n }\n st.elapsed += delta\n const maxIndex = track.frames.length - 1\n while (st.elapsed >= (track.durations[st.index] ?? 0) && st.index < maxIndex) {\n st.elapsed -= track.durations[st.index] ?? 0\n st.index += 1\n }\n if (st.elapsed >= (track.durations[st.index] ?? 0)) {\n if (!track.loop) {\n // Hold the final frame; the host owns the switch to the fallback, so\n // stop scheduling instead of re-painting the same frame forever.\n st.index = maxIndex\n paint(row, track.frames[st.index]!)\n return\n }\n st.elapsed = 0\n st.index = 0\n }\n paint(row, track.frames[st.index]!)\n schedule((track.durations[st.index] ?? 0) - st.elapsed)\n }\n schedule(0)\n return () => window.clearTimeout(timer)\n }, [animation, phase, cell, columns, rows, tracks, sequences, props.visual])\n\n // A stopped loop is woken by nothing, so a sprite scale change repaints the\n // frame it settled on: without this a resized pet would keep the old scale's\n // cell offsets and show a neighbouring cell until the track changed.\n useLayoutEffect(() => {\n const painted = paintedRef.current\n if (props.visual !== undefined || painted === null || spriteRef.current === null) return\n const pos = framePosition(cell, painted.row, painted.col, spriteScale)\n spriteRef.current.style.backgroundPosition = pos.x + 'px ' + pos.y + 'px'\n }, [spriteScale, cell, props.visual])\n\n // Auto-clear the feedback bubble after its CSS animation. The callback\n // rides a ref so re-renders never reset the timer: the 2s poll rebuilds\n // `props` every tick, and depending on it would starve the timeout.\n const feedbackDoneRef = useRef(props.onFeedbackDone)\n feedbackDoneRef.current = props.onFeedbackDone\n useEffect(() => {\n if (feedback === null) return\n const timer = window.setTimeout(() => feedbackDoneRef.current(), 2600)\n return () => window.clearTimeout(timer)\n }, [feedback])\n\n // Dragging: pointer events on the sprite; position is right/bottom based.\n // `draggedRef` records whether the pointer actually moved, so the browser's\n // trailing click (fired after pointerup) does not pet the sprite.\n const draggedRef = useRef(false)\n const clearHideTimer = (): void => {\n if (hideTimerRef.current !== null) {\n window.clearTimeout(hideTimerRef.current)\n hideTimerRef.current = null\n }\n }\n\n // Clear any pending auto-hide timer on unmount: a stray callback after\n // teardown reads window through react-dom and failed CI runs with\n // \"window is not defined\" (slow-runner timing, PetSprite.test.tsx).\n useEffect(() => () => clearHideTimer(), [])\n\n const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>): void => {\n if (props.dragDisabled === true) return\n // Read the live position before ending a walk: the walk keeps it in a ref\n // rather than React state, so a drag grabbed mid-walk starts where the pet\n // actually is instead of snapping back to where the walk began.\n const current = walkTargetRef.current ?? dragPosRef.current ?? { right: display.right, bottom: display.bottom }\n endWalk(false)\n e.preventDefault()\n ;(e.target as HTMLElement).setPointerCapture?.(e.pointerId)\n dragRef.current = { startX: e.clientX, startY: e.clientY, ...current }\n draggedRef.current = false\n setHovered(false)\n }\n const onPointerMove = (e: ReactPointerEvent<HTMLDivElement>): void => {\n const drag = dragRef.current\n if (drag === null) return\n const dx = e.clientX - drag.startX\n const dy = e.clientY - drag.startY\n if (Math.abs(dx) > 4 || Math.abs(dy) > 4) {\n if (!draggedRef.current) props.onDraggingChange?.(true)\n draggedRef.current = true\n }\n const right = clampOffset(drag.right - dx, window.innerWidth - 40)\n const bottom = clampOffset(drag.bottom - dy, window.innerHeight - 40)\n setDragPos({ right, bottom })\n }\n const onPointerUp = (): void => {\n if (dragRef.current === null) return\n dragRef.current = null\n if (draggedRef.current) props.onDraggingChange?.(false)\n if (dragPos !== null) props.onDragEnd(dragPos.right, dragPos.bottom)\n }\n\n // --- roaming ---------------------------------------------------------\n // The gameplay HUD rolls when the pet may wander; this side owns the motion\n // (clamped to the viewport), the walk art's facing and the persisted resting\n // spot -- the walk ends on the same write a drag ends with. The walk art\n // faces left, so a rightward walk mirrors the sprite (a vertical walk keeps\n // the side view); every other track stays unmirrored.\n const [facingRight, setFacingRight] = useState(false)\n const walkRafRef = useRef(0)\n // Live position while a walk is in flight. The walk writes the element's\n // right/bottom directly and mirrors them here instead of calling setState:\n // a walk is 1-3 s of 60 fps motion, and each frame used to re-render the\n // whole sprite tree (bubble stack, dock panel) for a position the DOM already\n // knew. Keeping it in a ref means a render that lands mid-walk (a poll, a\n // hover) still sees where the sprite actually is (issue #17).\n const walkTargetRef = useRef<{ right: number; bottom: number } | null>(null)\n const dragPosRef = useRef(dragPos)\n dragPosRef.current = dragPos\n\n const pos = walkTargetRef.current ?? dragPos ?? { right: display.right, bottom: display.bottom }\n // One integral cell size for the sprite box, the atlas grid and every frame\n // offset: background-size is this size times the column/row count, so the\n // scaled atlas shares a pixel grid with the box that shows one cell (#17).\n const scaled = scaledCellSize(cell, spriteScale)\n const spriteWidth = scaled.width\n const spriteHeight = scaled.height\n\n /** Stop an active walk; `persist` lands the pet on the spot it reached. */\n const endWalk = (persist: boolean): void => {\n if (walkRafRef.current === 0) return\n window.cancelAnimationFrame(walkRafRef.current)\n walkRafRef.current = 0\n setFacingRight(false)\n const settled = walkTargetRef.current\n walkTargetRef.current = null\n if (settled === null) return\n // Hand the reached spot back to React state: the walk's own frames never\n // updated it, and a render (or a drag that starts here) would otherwise\n // put the sprite back where the walk began.\n setDragPos(settled)\n if (persist) props.onDragEnd(settled.right, settled.bottom)\n }\n\n useEffect(() => {\n const bus = props.bus\n if (bus === undefined) return undefined\n bus.walk = (direction: PetRoamDirection, distance: number, speed: number): number => {\n if (dragRef.current !== null || walkRafRef.current !== 0) return 0\n const current = dragPosRef.current ?? { right: display.right, bottom: display.bottom }\n // Keep the whole sprite on screen with an 8px breathing margin. `right`\n // and `bottom` are CSS offsets: right grows leftwards, bottom upwards.\n const margin = 8\n const maxRight = Math.max(margin, window.innerWidth - spriteWidth - margin)\n const maxBottom = Math.max(margin, window.innerHeight - spriteHeight - margin)\n const wanted = { ...current }\n if (direction === 'left') wanted.right = current.right + distance\n else if (direction === 'right') wanted.right = current.right - distance\n else if (direction === 'up') wanted.bottom = current.bottom + distance\n else wanted.bottom = current.bottom - distance\n const target = {\n right: Math.max(margin, clampOffset(wanted.right, maxRight)),\n bottom: Math.max(margin, clampOffset(wanted.bottom, maxBottom)),\n }\n const travelled = direction === 'left' ? target.right - current.right\n : direction === 'right' ? current.right - target.right\n : direction === 'up' ? target.bottom - current.bottom\n : current.bottom - target.bottom\n if (travelled < 1) return 0\n const duration = Math.max(150, (travelled / Math.max(1, speed)) * 1000)\n const startedAt = performance.now()\n // The crawl art faces left, so only a rightward walk mirrors it; a\n // vertical walk keeps the side view (there is no front/back art).\n setFacingRight(direction === 'right')\n walkTargetRef.current = current\n const step = (now: number): void => {\n const t = Math.min(1, (now - startedAt) / duration)\n const next = {\n right: current.right + (target.right - current.right) * t,\n bottom: current.bottom + (target.bottom - current.bottom) * t,\n }\n walkTargetRef.current = next\n // The position goes straight to the element: a walk is the one motion\n // that moved every frame, and a setState here re-rendered the bubble\n // stack and the dock panel for a value the DOM already knew (issue\n // #17). React state takes over once, on the landing frame.\n const el = floatRef.current\n if (el !== null) {\n el.style.right = next.right + 'px'\n el.style.bottom = next.bottom + 'px'\n }\n if (t < 1) {\n walkRafRef.current = window.requestAnimationFrame(step)\n return\n }\n walkRafRef.current = 0\n walkTargetRef.current = null\n setFacingRight(false)\n setDragPos(next)\n props.onDragEnd(next.right, next.bottom)\n }\n walkRafRef.current = window.requestAnimationFrame(step)\n return travelled\n }\n return () => {\n bus.walk = undefined\n if (walkRafRef.current !== 0) {\n window.cancelAnimationFrame(walkRafRef.current)\n walkRafRef.current = 0\n }\n // A cancelled walk must not leave the sprite mirrored.\n setFacingRight(false)\n walkTargetRef.current = null\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps -- one registration per sprite\n }, [props.bus, definition.id, display.right, display.bottom, spriteWidth])\n // Bubble typography follows the sprite's own scale (#1549), bounded so a\n // shrunk pet never carries unreadably small text.\n const bubbleScale = bubbleScaleFor(display)\n\n // Concurrent sessions share one bubble slot: only the display session\n // speaks by default, and the rest hide behind a '+N' badge until the stack\n // is hovered/pinned open. The legacy single 'bubble' is the fallback when\n // the host serves no per-session list. The hover panel normally sits below\n // the sprite, so the bubbles stay visible and clickable — no region swap.\n // Whether the pet renders its OWN session/status bubbles (issue #6). Only\n // these are gated: the interaction feedback bubble and a sibling plugin's\n // announcement bubble are separate surfaces and keep rendering, so a plugin\n // that drives its own bubble can switch the built-in ones off. A host that\n // predates the field serves no mode at all, which reads as 'auto' — the\n // behavior that shipped before the switch existed.\n const statusBubblesOn = (snapshot?.statusBubbles ?? 'auto') !== 'off'\n const sessionBubbles = statusBubblesOn ? (snapshot?.sessions ?? []) : []\n const stackOpen = stackPeek || stackPinned\n const collapsed = !stackOpen && sessionBubbles.length > 1\n const visibleSessions = collapsed ? sessionBubbles.slice(0, 1) : sessionBubbles\n const statusBubble = statusBubblesOn && feedback === null && sessionBubbles.length === 0\n ? snapshot?.bubble\n : undefined\n // The plugin-authored announcements: one dedicated, specially styled bubble\n // per publishing plugin above the session stack (issue #1812 — the contract\n // used to hold a single slot, so a second publisher displaced the first).\n // The host already TTL-filters; this client-side check covers the last poll\n // tick. A host predating the array serves the singular field only, and a\n // browser half predating it (this file, before the upgrade) renders the same\n // one bubble, so neither side of a rolling upgrade loses a publisher.\n const announced = snapshot?.announcements ?? (snapshot?.announcement !== undefined ? [snapshot.announcement] : [])\n const now = Date.now()\n const usageAnnouncements = feedback === null ? announced.filter(entry => announcementFresh(entry, now)) : []\n // Each session's inner whisper (碎碎念) rides its own bubble — short\n // inner-voice copy woken by that session's activity, never the model's or\n // another session's. Instead of a second bubble of its own, a fresh\n // whisper takes over its session's bubble and re-tints it, so the pet\n // never wears two voices at once. Interaction feedback takes over the\n // whole bubble area while it plays, so whispers yield to it like status\n // copy.\n const bubblePresent = feedback !== null || sessionBubbles.length > 0 || statusBubble !== undefined || usageAnnouncements.length > 0\n const displayName = snapshot?.name ?? definition.displayName\n // The host-served status decoration (M5, #567); absent = text-only bubbles.\n const decoration = snapshot?.decoration\n\n // A settled session list can no longer stay pinned open.\n useEffect(() => {\n if (sessionBubbles.length <= 1) setStackPinned(false)\n }, [sessionBubbles.length])\n\n useLayoutEffect(() => {\n if (!hovered) {\n setPanelAbove(false)\n setPanelLift(0)\n return\n }\n const updatePanelPlacement = (): void => {\n const sprite = spriteRef.current\n const panel = panelRef.current\n if (sprite === null || panel === null) return\n const availableBelow = window.innerHeight - sprite.getBoundingClientRect().bottom\n const above = availableBelow < panel.getBoundingClientRect().height + 8\n setPanelAbove(above)\n // The fallback above-placement shares the sprite's top edge with the\n // bubble(s); lift the panel by the bubble area's height so the two\n // never overlap (8px base gap + 6px clearance above the top bubble).\n const bubbleHeight = above ? bubbleRef.current?.getBoundingClientRect().height ?? 0 : 0\n setPanelLift(bubbleHeight > 0 ? Math.ceil(bubbleHeight) + 14 : 0)\n }\n updatePanelPlacement()\n window.addEventListener('resize', updatePanelPlacement)\n return () => window.removeEventListener('resize', updatePanelPlacement)\n }, [hovered, renaming, pos.right, pos.bottom, display.size, bubblePresent, sessionBubbles.length, stackOpen, feedback])\n\n const float = (\n <div\n ref={floatRef}\n className={styles.float}\n style={{\n right: pos.right,\n bottom: pos.bottom,\n zIndex: 2147483000,\n // Read by .bubble / .bubbleStatus in pet.module.css.\n ...({ '--pet-bubble-scale': String(bubbleScale) } as CSSProperties),\n }}\n onPointerEnter={() => {\n clearHideTimer()\n setHovered(true)\n }}\n onPointerLeave={(e) => {\n // The panel renders OUTSIDE the container's box (absolute, below\n // the sprite), so moving onto it fires pointerleave on the container.\n // Treat a target still inside the container's DOM (the overflowed\n // panel) as \"still hovering\"; otherwise give the pointer a short\n // grace period to reach the panel across the gap below the sprite.\n // The bridge ('.panel::after') keeps the pointer inside the hit\n // area, and the grace period covers a slow mouse crossing the\n // remaining sliver.\n const next = e.relatedTarget\n if (next instanceof Node && floatRef.current?.contains(next)) return\n // Never auto-hide while the rename box is open: moving the pointer\n // onto an IME candidate window (an OS-level window outside the\n // webview) fires pointerleave, and unmounting the input mid-IME-\n // composition crashes some input methods / the renderer (#303).\n if (renaming) return\n clearHideTimer()\n hideTimerRef.current = window.setTimeout(() => setHovered(false), 300)\n }}\n >\n <div\n className={styles.spriteWrap}\n style={{ width: spriteWidth, height: spriteHeight }}\n >\n <div\n ref={spriteRef}\n className={styles.sprite}\n style={{\n width: spriteWidth,\n height: spriteHeight,\n ...(props.visual === undefined\n ? {\n backgroundImage: imageReady ? 'url(' + definition.atlasUrl + ')' : undefined,\n backgroundSize: (scaled.width * columns) + 'px ' + (scaled.height * (definition.atlasRows ?? rows.length)) + 'px',\n backgroundRepeat: 'no-repeat',\n backgroundPosition: '0 0',\n }\n : {}),\n cursor: dragRef.current === null ? 'grab' : 'grabbing',\n ...(facingRight ? { transform: 'scaleX(-1)' } : {}),\n }}\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n onPointerUp={onPointerUp}\n onClick={(e) => {\n // A pointer sequence that moved (dragged) still fires a trailing\n // click; skip the pet when that happened.\n if (draggedRef.current) return\n if (props.onGameplayTap !== undefined && spriteRef.current !== null) {\n const rect = spriteRef.current.getBoundingClientRect()\n if (rect.width > 0 && rect.height > 0) {\n props.onGameplayTap((e.clientX - rect.left) / rect.width, (e.clientY - rect.top) / rect.height)\n }\n }\n props.onPet()\n }}\n role=\"button\"\n aria-label={definition.displayName}\n >\n {props.visual}\n </div>\n </div>\n {props.hud}\n {feedback !== null && (\n <div key={feedback.at} ref={bubbleRef} className={clsx(styles.bubble, feedback.kind === 'feed' ? styles.bubbleFeed : styles.bubblePet)}>\n {feedback.text}\n </div>\n )}\n {feedback === null && (sessionBubbles.length > 0 || statusBubble !== undefined || usageAnnouncements.length > 0) && (\n <div\n ref={bubbleRef}\n className={styles.bubbleStack}\n onPointerEnter={() => setStackPeek(true)}\n onPointerLeave={() => setStackPeek(false)}\n >\n {visibleSessions.map((session, index) => {\n // A session's whisper rides ITS OWN bubble (the stack lead when\n // the current session has one, any bubble when the stack is\n // expanded). The key swap restarts the entrance animation so the\n // mood change reads as the bubble re-speaking.\n const speaksWhisper = session.whisper !== undefined\n const bubble = (\n <button\n key={speaksWhisper ? 'whisper:' + session.whisper : session.sessionId}\n type=\"button\"\n className={clsx(\n styles.bubble,\n styles.bubbleStatus,\n styles.bubbleClickable,\n speaksWhisper && styles.bubbleWhisper,\n )}\n title={props.t('pet.openSessionHint')}\n onClick={() => { props.onOpenSession(session.sessionId) }}\n >\n {index === 0 && !speaksWhisper && decoration !== undefined && (\n <StatusOrnament decoration={decoration} phase={phase} />\n )}\n {session.whisper ?? session.bubble}\n </button>\n )\n // The primary bubble carries the '+N' badge while other sessions\n // hide behind it; the badge toggles the pinned (touch) expansion.\n if (index !== 0 || sessionBubbles.length <= 1) return bubble\n return (\n <span key=\"primary\" className={styles.bubbleAnchor}>\n {bubble}\n <button\n type=\"button\"\n className={styles.bubbleMore}\n title={stackOpen\n ? props.t('pet.collapseSessions')\n : props.t('pet.moreSessions', { n: sessionBubbles.length - 1 })}\n aria-label={stackOpen\n ? props.t('pet.collapseSessions')\n : props.t('pet.moreSessions', { n: sessionBubbles.length - 1 })}\n aria-expanded={stackOpen}\n onClick={(e) => {\n e.stopPropagation()\n setStackPinned(open => !open)\n }}\n >\n {stackOpen ? '×' : '+' + String(sessionBubbles.length - 1)}\n </button>\n </span>\n )\n })}\n {sessionBubbles.length === 0 && statusBubble !== undefined && (\n <div\n key=\"status\"\n className={clsx(styles.bubble, styles.bubbleStatus)}\n role=\"status\"\n aria-live=\"polite\"\n >\n {decoration !== undefined && (\n <StatusOrnament decoration={decoration} phase={phase} />\n )}\n {statusBubble}\n </div>\n )}\n {/*\n One bubble per publishing plugin, in the order the host serves\n them. Keyed by `source`, not by arrival: a repeating publisher\n updates its own bubble in place instead of remounting (which would\n replay the entrance animation on every poll), and two publishers on\n different cadences keep their positions.\n */}\n {usageAnnouncements.map(entry => (\n <UsageAnnouncementBubble key={entry.source} announcement={entry} />\n ))}\n </div>\n )}\n {hovered && dragRef.current === null && (\n <div\n ref={panelRef}\n className={clsx(styles.panel, panelAbove && styles.panelAbove)}\n data-placement={panelAbove ? 'above' : 'below'}\n style={panelAbove && panelLift > 0\n ? ({ marginBottom: panelLift } as CSSProperties)\n : undefined}\n onPointerEnter={() => {\n // Reaching the panel (or its bridge) must cancel any hide timer\n // the container's pointerleave may have armed while the pointer\n // crossed the sliver between the sprite and the panel.\n clearHideTimer()\n }}\n >\n {renaming ? (\n <div className={styles.renameRow}>\n <input\n className={styles.nameInput}\n value={nameDraft}\n maxLength={20}\n placeholder={props.t('pet.namePlaceholder')}\n autoFocus\n onChange={(e) => setNameDraft(e.target.value)}\n onCompositionStart={() => { composingRef.current = true }}\n onCompositionEnd={() => { composingRef.current = false }}\n onKeyDown={(e) => {\n // While an IME composition is active (e.g. selecting a\n // Chinese candidate), Enter/Escape keydowns belong to the\n // input method: ignore them so candidate selection can\n // neither submit the draft nor close the rename box. The\n // explicit ref and the 'Process' key cover IMEs that mark\n // composition keydowns with isComposing === false (#303).\n if (composingRef.current || e.nativeEvent.isComposing || e.key === 'Process') return\n if (e.key === 'Enter') {\n const trimmed = nameDraft.trim()\n if (trimmed !== '') {\n props.onRename(trimmed)\n setRenaming(false)\n }\n } else if (e.key === 'Escape') {\n setRenaming(false)\n }\n }}\n />\n <button\n type=\"button\"\n className={styles.action}\n onClick={() => {\n const trimmed = nameDraft.trim()\n if (trimmed !== '') {\n props.onRename(trimmed)\n setRenaming(false)\n }\n }}\n >\n {panelLabel('confirm', props.t('pet.confirm'))}\n </button>\n </div>\n ) : (\n <>\n <div className={styles.rankRow}>\n <span className={styles.nameCell}>{displayName}</span>\n <span className={styles.statRank}>\n {panelStat('rank', 'pet.rank', { rank: rankNameOf() })}\n </span>\n </div>\n <div className={styles.rankRow}>\n <span className={styles.statTreats}>{panelStat('treats', 'pet.treats', { n: snapshot?.treats.stocked ?? 0 })}</span>\n <span className={styles.statPoints}>{panelStat('points', 'pet.points', { points: snapshot?.affinity.points ?? 0 })}</span>\n </div>\n <div className={styles.actions}>\n {panelShows('feed') && (\n <button type=\"button\" className={styles.action} onClick={props.onFeed}>\n {panelLabel('feed', props.t('pet.feed'))}\n </button>\n )}\n {panelShows('rename') && (\n <button\n type=\"button\"\n className={styles.action}\n onClick={() => {\n // Cancel any pending hide so the rename box cannot\n // unmount right as the user starts typing (#303).\n clearHideTimer()\n setNameDraft(displayName)\n setRenaming(true)\n }}\n >\n {panelLabel('rename', props.t('pet.rename'))}\n </button>\n )}\n {panelShows('hide') && (\n <button type=\"button\" className={styles.action} onClick={props.onHide}>\n {panelLabel('hide', props.t('pet.hide'))}\n </button>\n )}\n {props.onGameplayMenu !== undefined && (\n <button type=\"button\" className={styles.action} onClick={props.onGameplayMenu}>\n {props.t('pet.gameplay.menu')}\n </button>\n )}\n {/*\n Plugin-registered actions (issue #6). They follow the built-in\n ones so the pet's own row keeps its fixed order, and they\n carry their registration id as a data attribute so a test (or\n a skin) can address one action without depending on its label.\n */}\n {(snapshot?.panelActions ?? []).map(action => (\n <button\n key={action.id}\n type=\"button\"\n className={styles.action}\n data-dsh-pet-panel-action={action.id}\n {...(action.title === undefined ? {} : { title: action.title })}\n onClick={() => { props.onPanelAction(action.id) }}\n >\n {action.label}\n </button>\n ))}\n </div>\n </>\n )}\n </div>\n )}\n </div>\n )\n\n return createPortal(float, props.portalTarget ?? document.body)\n}\n","/**\n * Drag stream — bridges the chrome's pointer drag state onto the renderer\n * contract's { get, subscribe } shape, so renderers with a dedicated drag\n * track (frames2d) can follow the chrome-owned drag gesture. Dispatch is\n * change-only, mirroring the phase stream.\n * @module @linxin666/dsh-pet/client/drag-stream\n */\n\n/** The renderer-facing drag stream. */\nexport interface DragStream {\n /** Whether the chrome reports an active drag gesture. */\n get(): boolean\n /** Subscribe to drag state changes; returns the unsubscribe. */\n subscribe(listener: (dragging: boolean) => void): () => void\n /** Feed a fresh drag state; no-op when unchanged. */\n push(dragging: boolean): void\n}\n\n/** Create the stream (one per pet activation, owned by the renderer switch). */\nexport function createDragStream(): DragStream {\n let current = false\n const listeners = new Set<(dragging: boolean) => void>()\n return {\n get: () => current,\n subscribe(listener) {\n listeners.add(listener)\n return () => { listeners.delete(listener) }\n },\n push(dragging) {\n if (dragging === current) return\n current = dragging\n for (const listener of [...listeners]) listener(dragging)\n },\n }\n}\n","/**\n * Renderer registry — dispatches a manifest's renderer kind to its\n * implementation (pet-center M2 P4, issue #623). Unknown kinds never blank\n * the pet: a fallback card names the problem and reports the kinds this\n * build actually supports.\n * @module @linxin666/dsh-pet/client/renderers/registry\n */\n\nimport type { PetRenderer, PetRendererContext, PetRendererHandle } from '../../contracts/renderer.ts'\n\n/** Renderer dispatch table. */\nexport class RendererRegistry {\n private readonly renderers = new Map<string, PetRenderer>()\n\n /** Register one renderer implementation (id wins on re-register). */\n register(renderer: PetRenderer): void {\n this.renderers.set(renderer.id, renderer)\n }\n\n /** Whether a renderer kind is available in this build. */\n has(id: string): boolean {\n return this.renderers.has(id)\n }\n\n /** The registered renderer kinds (for diagnostics). */\n kinds(): string[] {\n return [...this.renderers.keys()].sort()\n }\n\n /** Remove every registration (tests; the client index registers once). */\n clear(): void {\n this.renderers.clear()\n }\n\n /**\n * Mount a renderer for one activation. An unknown kind renders a clear\n * diagnostic card into the container instead of failing silently.\n */\n mount(kind: string, ctx: PetRendererContext, config: unknown): PetRendererHandle {\n const renderer = this.renderers.get(kind)\n if (renderer === undefined) {\n const note = document.createElement('div')\n note.dataset.dshPetRendererFallback = kind\n note.textContent = 'Pet renderer \"' + kind + '\" is not available in this build (supported: ' + this.kinds().join(', ') + ').'\n ctx.container.appendChild(note)\n ctx.onCleanup(() => note.remove())\n return { dispose: () => note.remove() }\n }\n return renderer.mount(ctx, renderer.validateConfig(config))\n }\n}\n\n/**\n * The plugin-wide renderer registry. The client entry registers the\n * built-in renderers at apply time; the renderer switch and the live2d\n * bridge dispatch through this instance.\n */\nexport const defaultPetRendererRegistry = new RendererRegistry()\n","/**\n * Phase stream — bridges the polled host snapshots onto the renderer\n * contract's { get, subscribe } shape (pet-center M2 P4, issue #623). The\n * existing poll loop pushes each snapshot's ActivityPhase; subscribers are\n * dispatched on CHANGE only (phase transitions are sparse — done/failed hold\n * a timed window before falling back to idle — and renderers like Live2D pay\n * per transition, not per tick).\n * @module @linxin666/dsh-pet/client/phase-stream\n */\n\nimport type { ActivityPhase } from '../state.ts'\n\n/** The renderer-facing phase stream. */\nexport interface PhaseStream {\n /** The latest pushed phase. */\n get(): ActivityPhase\n /** Subscribe to phase changes; returns the unsubscribe. */\n subscribe(listener: (phase: ActivityPhase) => void): () => void\n /** Feed a fresh snapshot phase; no-op when unchanged. */\n push(phase: ActivityPhase): void\n}\n\n/** Create the stream (one per pet entry lifetime, owned by the plugin body). */\nexport function createPhaseStream(initial: ActivityPhase = 'idle'): PhaseStream {\n let current = initial\n const listeners = new Set<(phase: ActivityPhase) => void>()\n return {\n get: () => current,\n subscribe(listener) {\n listeners.add(listener)\n return () => { listeners.delete(listener) }\n },\n push(phase) {\n if (phase === current) return\n current = phase\n for (const listener of [...listeners]) listener(phase)\n },\n }\n}\n","/**\n * Live2D visual mount (pet-center M3) — the React bridge between the pet\n * center chrome and the imperative live2d renderer. The bridge owns the\n * contract context (asset base, phase stream, interaction write-back,\n * activation cleanups), feeds the polled phase into the stream, forwards\n * sub-4px taps as hit-test coordinates, and renders the localized error\n * card when the renderer reports a fatal boot failure.\n * @module @linxin666/dsh-pet/client/renderers/live2d/Live2dVisualMount\n */\n\nimport { useEffect, useRef, useState, type ReactElement } from 'react'\nimport type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { PetDefinition } from '../../../registry.ts'\nimport type { ActivityPhase } from '../../../state.ts'\nimport { createPhaseStream, type PhaseStream } from '../../phase-stream.ts'\nimport type { PetRendererContext } from '../../../contracts/renderer.ts'\nimport { defaultPetRendererRegistry } from '../registry.ts'\nimport type { Live2dErrorCode, Live2dRendererHandle } from '../live2d.ts'\nimport type { NS } from '../../locales.ts'\n\n/** Mount the live2d renderer as the sprite's visual (inside the chrome). */\nexport function Live2dVisualMount(props: {\n definition: PetDefinition\n phase: ActivityPhase\n onPet: () => void\n t: PropsLocale<typeof NS>['t']\n}): ReactElement {\n const containerRef = useRef<HTMLDivElement | null>(null)\n const streamRef = useRef<PhaseStream | null>(null)\n const handleRef = useRef<Live2dRendererHandle | null>(null)\n const downRef = useRef<{ x: number; y: number } | null>(null)\n const [error, setError] = useState<Live2dErrorCode | null>(null)\n\n // One activation per pet definition: build the contract context and mount.\n useEffect(() => {\n setError(null)\n const container = containerRef.current\n const live2d = props.definition.live2d\n if (container === null || live2d === undefined) return undefined\n streamRef.current ??= createPhaseStream(props.phase)\n const cleanups: (() => void)[] = []\n const ctx: PetRendererContext = {\n petId: props.definition.id,\n assetBase: '/pet/' + encodeURIComponent(props.definition.id),\n container,\n phase: streamRef.current,\n interact: props.onPet,\n onCleanup: (fn) => { cleanups.push(fn) },\n }\n let handle: Live2dRendererHandle\n try {\n handle = defaultPetRendererRegistry.mount('live2d', ctx, live2d) as Live2dRendererHandle\n } catch {\n setError('load-failed')\n return () => { for (const fn of cleanups.splice(0)) fn() }\n }\n handleRef.current = handle\n handle.onError?.(setError)\n return () => {\n handleRef.current = null\n for (const fn of cleanups.splice(0)) fn()\n handle.dispose()\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps -- one activation per pet identity\n }, [props.definition])\n\n // Feed the polled phase into the activation's stream (change-only).\n useEffect(() => {\n streamRef.current?.push(props.phase)\n }, [props.phase])\n\n return (\n <div\n ref={containerRef}\n data-dsh-pet-live2d={props.definition.id}\n style={{ width: '100%', height: '100%' }}\n onPointerDown={(e) => { downRef.current = { x: e.clientX, y: e.clientY } }}\n onPointerUp={(e) => {\n const down = downRef.current\n downRef.current = null\n if (down === null) return\n // A moved pointer is a drag (the chrome owns it), not a tap.\n if (Math.abs(e.clientX - down.x) > 4 || Math.abs(e.clientY - down.y) > 4) return\n const rect = e.currentTarget.getBoundingClientRect()\n handleRef.current?.tap(e.clientX - rect.left, e.clientY - rect.top)\n }}\n >\n {error !== null && (\n <span data-dsh-pet-live2d-error={error}>\n {error === 'core-missing'\n ? props.t('pet.live2d.core-missing')\n : error === 'vendor-missing'\n ? props.t('pet.live2d.vendor-missing')\n : props.t('pet.live2d.load-failed')}\n </span>\n )}\n </div>\n )\n}\n","/**\n * Frames2d visual mount — the React bridge between the pet center chrome\n * and the imperative frames2d renderer, mirroring the live2d mount. The\n * bridge owns the contract context (asset base, phase stream, interaction\n * write-back, activation cleanups), feeds the polled phase into the stream,\n * forwards the chrome's drag gesture onto the conventional 'drag' track\n * (when the pet declares one), and renders the localized fallback card when\n * the served config is invalid.\n * @module @linxin666/dsh-pet/client/renderers/Frames2dVisualMount\n */\n\nimport { useEffect, useRef, useState, type ReactElement } from 'react'\nimport type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { PetDefinition } from '../../registry.ts'\nimport type { ActivityPhase } from '../../state.ts'\nimport { createPhaseStream, type PhaseStream } from '../phase-stream.ts'\nimport type { DragStream } from '../drag-stream.ts'\nimport type { PetRendererContext } from '../../contracts/renderer.ts'\nimport { defaultPetRendererRegistry } from './registry.ts'\nimport type { Frames2dRendererHandle } from './frames2d.ts'\nimport type { GameplayBus } from '../gameplay-hud.tsx'\nimport type { NS } from '../locales.ts'\n\n/** Mount the frames2d renderer as the sprite's visual (inside the chrome). */\nexport function Frames2dVisualMount(props: {\n definition: PetDefinition\n phase: ActivityPhase\n onPet: () => void\n /** Chrome drag gesture stream (the renderer switch owns it). */\n drag: DragStream\n /** Gameplay coordination bus; the mount registers its track override. */\n bus?: GameplayBus\n t: PropsLocale<typeof NS>['t']\n}): ReactElement {\n const containerRef = useRef<HTMLDivElement | null>(null)\n const streamRef = useRef<PhaseStream | null>(null)\n const handleRef = useRef<Frames2dRendererHandle | null>(null)\n const [invalid, setInvalid] = useState(false)\n\n // One activation per pet definition: build the contract context and mount.\n useEffect(() => {\n setInvalid(false)\n const container = containerRef.current\n const frames2d = props.definition.frames2d\n if (container === null || frames2d === undefined) return undefined\n streamRef.current ??= createPhaseStream(props.phase)\n const cleanups: (() => void)[] = []\n const ctx: PetRendererContext = {\n petId: props.definition.id,\n assetBase: '/pet/' + encodeURIComponent(props.definition.id),\n container,\n phase: streamRef.current,\n interact: props.onPet,\n onCleanup: (fn) => { cleanups.push(fn) },\n }\n let handle: Frames2dRendererHandle\n try {\n handle = defaultPetRendererRegistry.mount('frames2d', ctx, frames2d) as Frames2dRendererHandle\n } catch {\n setInvalid(true)\n return () => { for (const fn of cleanups.splice(0)) fn() }\n }\n handleRef.current = handle\n // The gameplay HUD steers one shared override slot through the bus;\n // mode rules (work blocks drag, sleep wakes on it) keep the two\n // producers from fighting over the slot.\n if (props.bus !== undefined) {\n const gameplayBus = props.bus\n gameplayBus.setTrack = (track) => { handleRef.current?.setState(track) }\n gameplayBus.setIdleTrack = (track) => { handleRef.current?.setIdleTrack(track) }\n // The HUD latches the wanted base idle (skin selection, restored from the\n // host snapshot): apply it on activation, so a late or repeated mount\n // never repaints the pet with the default look.\n if (gameplayBus.idleTrack !== undefined) handle.setIdleTrack(gameplayBus.idleTrack)\n cleanups.push(() => {\n gameplayBus.setTrack = undefined\n gameplayBus.setIdleTrack = undefined\n })\n }\n // The drag gesture drives the conventional 'drag' track when declared.\n // On release, a declared gameplay.dragEndState (miku: standup) plays\n // once; its fallback auto-releases the override back to the phase map.\n const dragTrack = props.definition.gameplay?.dragState ?? (frames2d.tracks.drag === undefined ? undefined : 'drag')\n const offDrag = props.drag.subscribe((dragging) => {\n if (dragTrack === undefined) return\n if (dragging) {\n handle.setState(dragTrack)\n return\n }\n handle.setState(props.definition.gameplay?.dragEndState)\n })\n cleanups.push(offDrag)\n return () => {\n handleRef.current = null\n for (const fn of cleanups.splice(0)) fn()\n handle.dispose()\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps -- one activation per pet identity\n }, [props.definition])\n\n // Feed the polled phase into the activation's stream (change-only).\n useEffect(() => {\n streamRef.current?.push(props.phase)\n }, [props.phase])\n\n return (\n <div\n ref={containerRef}\n data-dsh-pet-frames2d={props.definition.id}\n style={{ width: '100%', height: '100%', pointerEvents: 'none' }}\n >\n {invalid && (\n <span data-dsh-pet-frames2d-error=\"invalid-config\">\n {props.t('pet.renderer.unavailable', { renderer: 'frames2d' })}\n </span>\n )}\n </div>\n )\n}\n","/**\n * Renderer switch — the client dispatch seam of the pet center (issue #623,\n * milestone M2 P5 / M3). The pet's manifest picks the renderer: sprite2d\n * hands straight through to the sprite; live2d injects its visual INTO the\n * sprite chrome (the dock, bubbles and panel belong to the pet center, not\n * the renderer); a renderer this build cannot serve renders a clear\n * diagnostic card instead of blanking.\n * @module @linxin666/dsh-pet/client/renderers/PetRendererSwitch\n */\n\nimport { cloneElement, isValidElement, useRef, type ReactElement, type ReactNode } from 'react'\nimport type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { PetDefinition } from '../../registry.ts'\nimport type { ActivityPhase } from '../../state.ts'\nimport type { PetSpriteProps } from '../PetSprite.tsx'\nimport { createDragStream, type DragStream } from '../drag-stream.ts'\nimport type { GameplayBus } from '../gameplay-hud.tsx'\nimport { defaultPetRendererRegistry } from './registry.ts'\nimport { Live2dVisualMount } from './live2d/Live2dVisualMount.tsx'\nimport { Frames2dVisualMount } from './Frames2dVisualMount.tsx'\nimport type { NS } from '../locales.ts'\n\n/** Dispatch one pet definition to its renderer; unknown kinds get a card. */\nexport function PetRendererSwitch(props: {\n definition: PetDefinition\n /** Current activity phase (fed to renderer visuals). */\n phase: ActivityPhase\n /** The chrome's pet interaction (affinity write-back owner). */\n onPet: () => void\n /** External drag stream (gameplay HUD shares it); created locally otherwise. */\n drag?: DragStream\n /** Gameplay coordination bus forwarded to the frames2d visual mount. */\n bus?: GameplayBus\n t: PropsLocale<typeof NS>['t']\n children?: ReactNode\n}): ReactElement {\n const renderer = props.definition.renderer ?? 'sprite2d'\n // The frames2d drag stream lives one level up: the chrome (PetSprite)\n // reports the gesture through onDraggingChange, the visual subscribes.\n const dragRef = useRef<{ id: string; stream: ReturnType<typeof createDragStream> } | null>(null)\n if (dragRef.current === null || dragRef.current.id !== props.definition.id) {\n dragRef.current = { id: props.definition.id, stream: createDragStream() }\n }\n const drag = props.drag ?? dragRef.current.stream\n if (renderer === 'sprite2d') return <>{props.children}</>\n if (renderer === 'frames2d' && defaultPetRendererRegistry.has('frames2d') && isValidElement<PetSpriteProps>(props.children)) {\n const visual = (\n <Frames2dVisualMount\n definition={props.definition}\n phase={props.phase}\n onPet={props.onPet}\n drag={drag}\n {...(props.bus === undefined ? {} : { bus: props.bus })}\n t={props.t}\n />\n )\n return cloneElement(props.children, { visual, onDraggingChange: (dragging: boolean) => drag.push(dragging) })\n }\n if (renderer === 'live2d' && defaultPetRendererRegistry.has('live2d') && isValidElement<PetSpriteProps>(props.children)) {\n const visual = (\n <Live2dVisualMount\n definition={props.definition}\n phase={props.phase}\n onPet={props.onPet}\n t={props.t}\n />\n )\n return cloneElement(props.children, { visual })\n }\n return (\n <span data-dsh-pet-renderer-fallback={renderer}>\n {props.t('pet.renderer.unavailable', { renderer })}\n </span>\n )\n}\n","/**\n * Pet gameplay — the optional manifest 'gameplay' block and its host engine.\n * The block layers an opt-in mini-game over any frames2d pet: decaying stat\n * bars, currencies, a weighted idle director, touch zones, a work loop, a\n * sleep loop, passive income and a shop (issue: miku-pet generalization).\n *\n * Discipline split matches manifest-v2: STRUCTURE is fail-closed (types,\n * ranges, references into stats/tracks); the host engine is pure — every\n * verb takes an explicit clock and rng so tests stay deterministic. Decay,\n * passive income and sleep restore are lazy-settled on read (the treats.ts\n * discipline): the host runs no timers for gameplay.\n * @module @linxin666/dsh-pet/gameplay\n */\n\n/** One roam direction the pet may walk in. */\nexport type PetRoamDirection = 'up' | 'down' | 'left' | 'right'\n\n/** Every roam direction, in roll order (equal chance each unless restricted). */\nexport const PET_ROAM_DIRECTIONS: readonly PetRoamDirection[] = ['up', 'down', 'left', 'right']\n\n/** One gameplay effect: add amount to a declared stat or a currency. */\nexport interface PetGameplayEffect {\n stat?: string\n currency?: string\n amount: number\n}\n\n/** One roll branch inside a touch zone; uncovered roll mass is a no-op. */\nexport interface PetGameplayTouchBranch {\n probability: number\n effects?: PetGameplayEffect[]\n /** Track played on hit (held for stateMs, then the renderer settles). */\n state?: string\n stateMs?: number\n /** Bubble phrase pool; one is picked on hit. */\n phrases?: string[]\n}\n\nexport interface PetGameplayTouchZone {\n name: string\n /** Vertical slice of the hit box (fractions, y0 < y1). */\n y0: number\n y1: number\n branches: PetGameplayTouchBranch[]\n}\n\nexport interface PetGameplayStatDef {\n max: number\n initial?: number\n decayPerMinute?: number\n /** Decay rate while the work mode is active (defaults to decayPerMinute). */\n workingDecayPerMinute?: number\n /** Extra decay rate while no session is active. */\n idleDecayPerMinute?: number\n}\n\nexport interface PetGameplayShopItem {\n id: string\n label: string\n /** Optional frame path (manifest-relative) shown as the item icon. */\n image?: string\n price: number\n currency: string\n effects?: PetGameplayEffect[]\n lottery?: {\n effects?: PetGameplayEffect[]\n /** Default currency the prize is paid in (tiers may override). */\n currency?: string\n tiers: { probability: number; prize: number; currency?: string }[]\n }\n}\n\n/**\n * One extra named gameplay mode beyond work/sleep (a bath, a play session…).\n * The host holds `state` while the mode is active and may restore a stat on\n * a fixed cadence — the same lazy-settle rule the sleep mode uses. A mode is\n * pure data: adding one to a manifest needs no host change.\n */\nexport interface PetGameplayModeDef {\n /** frames2d track held for as long as the mode is active. */\n state: string\n /** Action-button label (plain text); falls back to the i18n key pet.gameplay.<name>. */\n label?: string\n /** Label while the mode is active (plain text); falls back to `label`. */\n activeLabel?: string\n /** Periodic stat restore while the mode is active (omitted = no restore). */\n restore?: { stat: string; amount: number; intervalMs: number }\n}\n\n/** The validated manifest 'gameplay' block. */\nexport interface PetGameplayManifest {\n idleDirector?: {\n intervalMs: number\n maxMiss: number\n idleWeight: number\n acts: { track: string; weight: number; phrases?: string[] }[]\n }\n stats?: Record<string, PetGameplayStatDef>\n /** Click hit box inside the sprite box (fractions). */\n hitBox?: { x0: number; y0: number; x1: number; y1: number }\n touch?: {\n zones: PetGameplayTouchZone[]\n /** Plain-click effect while a touch animation holds (miku: mood +0..3). */\n clickBoost?: { stat: string; min: number; max: number }\n }\n work?: {\n state: string\n successState: string\n failState: string\n tickMs: number\n /** Hold time of the result track before the next round. */\n resultMs?: { success: number; fail: number }\n successProbability: number\n success?: { effects: PetGameplayEffect[] }\n fail?: { effects: PetGameplayEffect[] }\n }\n sleep?: {\n state: string\n wakeState?: string\n restore: { stat: string; amount: number; intervalMs: number }\n }\n /**\n * Extra named modes beyond work/sleep, keyed by a kebab mode id. Each one\n * gets its own menu button, holds its track while active and may restore a\n * stat on a cadence. 'work' and 'sleep' are reserved keys.\n */\n modes?: Record<string, PetGameplayModeDef>\n /**\n * Random roaming: on a slow interval the pet rolls whether to wander and\n * walks to a new spot on screen with `state` held for the travel time. The\n * chrome owns the motion (clamped to the viewport) and persists the resting\n * spot the way a drag does; the roll only runs while the pet is idle and no\n * mode, drag or touch animation owns it.\n */\n roam?: {\n /** frames2d track held while walking. */\n state: string\n /** Ms between roam decisions. */\n intervalMs: number\n /** Chance one decision actually walks (0, 1]. */\n probability: number\n /** Travel per roam in px (distanceMin <= distanceMax). */\n distanceMin: number\n distanceMax: number\n /** Walking speed in px per second. */\n speed: number\n /**\n * Directions the pet may walk in, rolled uniformly (equal chance each).\n * Omitted = all four. A side-view crawl reads best walking left/right, so\n * a pet may restrict the list to those two.\n */\n directions?: PetRoamDirection[]\n }\n passiveIncome?: { currency: string; amount: number; intervalMs: number }\n shop?: { state?: string; items: PetGameplayShopItem[] }\n /** Track played while the chrome reports dragging (default 'drag'). */\n dragState?: string\n /** Track played once when a drag ends (miku: standup), before settling. */\n dragEndState?: string\n}\n\n/* ------------------------------------------------------------------ *\n * Manifest parsing (fail-closed structure)\n * ------------------------------------------------------------------ */\n\nconst KEBAB = /^[a-z0-9][a-z0-9-]*$/\nconst MAX_STATS = 16\nconst MAX_ZONES = 8\nconst MAX_BRANCHES = 8\nconst MAX_ACTS = 16\nconst MAX_SHOP_ITEMS = 32\nconst MAX_LOTTERY_TIERS = 16\nconst MAX_PHRASES = 64\nconst PHRASE_MAX_LENGTH = 120\nconst MAX_MODES = 8\nconst MODE_LABEL_MAX_LENGTH = 40\nconst STAT_VALUE_MAX = 1_000_000\nconst CURRENCY_MAX = 9_999_999\n\nconst KNOWN_GAMEPLAY = new Set(['idleDirector', 'stats', 'hitBox', 'touch', 'work', 'sleep', 'modes', 'roam', 'passiveIncome', 'shop', 'dragState', 'dragEndState'])\nconst KNOWN_STAT = new Set(['max', 'initial', 'decayPerMinute', 'workingDecayPerMinute', 'idleDecayPerMinute'])\nconst KNOWN_ZONE = new Set(['name', 'y0', 'y1', 'branches'])\nconst KNOWN_TOUCH = new Set(['zones', 'clickBoost'])\nconst KNOWN_BRANCH = new Set(['probability', 'effects', 'state', 'stateMs', 'phrases'])\nconst KNOWN_EFFECT = new Set(['stat', 'currency', 'amount'])\nconst KNOWN_WORK = new Set(['state', 'successState', 'failState', 'tickMs', 'resultMs', 'successProbability', 'success', 'fail'])\nconst KNOWN_SLEEP = new Set(['state', 'wakeState', 'restore'])\nconst KNOWN_MODE = new Set(['state', 'label', 'activeLabel', 'restore'])\nconst KNOWN_ROAM = new Set(['state', 'intervalMs', 'probability', 'distanceMin', 'distanceMax', 'speed', 'directions'])\nconst KNOWN_RESTORE = new Set(['stat', 'amount', 'intervalMs'])\nconst KNOWN_SHOP_ITEM = new Set(['id', 'label', 'image', 'price', 'currency', 'effects', 'lottery'])\nconst KNOWN_LOTTERY = new Set(['effects', 'currency', 'tiers'])\nconst KNOWN_IDLE_DIRECTOR = new Set(['intervalMs', 'maxMiss', 'idleWeight', 'acts'])\nconst KNOWN_ACT = new Set(['track', 'weight', 'phrases'])\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction unknownKeys(source: Record<string, unknown>, known: Set<string>): string[] {\n return Object.keys(source).filter(key => !known.has(key))\n}\n\nexport interface GameplayParseHooks {\n /** State names the renderer can play (frames2d track ids). */\n stateNames: ReadonlySet<string>\n error: (message: string) => void\n}\n\nfunction validName(name: unknown, max = 32): name is string {\n return typeof name === 'string' && name.length <= max && KEBAB.test(name)\n}\n\nfunction intIn(value: unknown, min: number, max: number): value is number {\n return typeof value === 'number' && Number.isInteger(value) && value >= min && value <= max\n}\n\nfunction numIn(value: unknown, min: number, max: number): value is number {\n return typeof value === 'number' && Number.isFinite(value) && value >= min && value <= max\n}\n\nfunction parseEffects(raw: unknown, field: string, stats: Record<string, PetGameplayStatDef>, hooks: GameplayParseHooks): PetGameplayEffect[] | undefined {\n if (raw === undefined) return undefined\n if (!Array.isArray(raw) || raw.length === 0) {\n hooks.error(field + ' must be a non-empty array of effects')\n return undefined\n }\n const effects: PetGameplayEffect[] = []\n for (const entry of raw) {\n if (!isRecord(entry)) {\n hooks.error(field + ': every effect must be an object')\n continue\n }\n const extra = unknownKeys(entry, KNOWN_EFFECT)\n if (extra.length > 0) hooks.error(field + ': unknown effect field(s) ' + extra.map(k => JSON.stringify(k)).join(', '))\n const hasStat = typeof entry.stat === 'string'\n const hasCurrency = typeof entry.currency === 'string'\n if (hasStat === hasCurrency) {\n hooks.error(field + ': an effect needs exactly one of stat or currency')\n continue\n }\n if (!intIn(entry.amount, -STAT_VALUE_MAX, STAT_VALUE_MAX) || entry.amount === 0) {\n hooks.error(field + ': effect amount must be a non-zero integer within ±' + STAT_VALUE_MAX)\n continue\n }\n if (hasStat && stats[entry.stat as string] === undefined) {\n hooks.error(field + ': effect references undeclared stat ' + JSON.stringify(entry.stat))\n continue\n }\n if (hasCurrency && !validName(entry.currency, 24)) {\n hooks.error(field + ': effect currency must be a kebab id')\n continue\n }\n effects.push({\n ...(hasStat ? { stat: entry.stat as string } : {}),\n ...(hasCurrency ? { currency: entry.currency as string } : {}),\n amount: entry.amount as number,\n })\n }\n return effects.length === 0 ? undefined : effects\n}\n\nfunction parsePhrases(raw: unknown, field: string, hooks: GameplayParseHooks): string[] | undefined {\n if (raw === undefined) return undefined\n if (!Array.isArray(raw) || raw.length === 0 || raw.length > MAX_PHRASES\n || raw.some(line => typeof line !== 'string' || line.trim() === '' || line.length > PHRASE_MAX_LENGTH)) {\n hooks.error(field + ' must be 1..' + MAX_PHRASES + ' non-empty lines of at most ' + PHRASE_MAX_LENGTH + ' chars')\n return undefined\n }\n return raw as string[]\n}\n\nfunction parseStateRef(raw: unknown, field: string, hooks: GameplayParseHooks): string | undefined {\n if (raw === undefined) return undefined\n if (typeof raw !== 'string' || !hooks.stateNames.has(raw)) {\n hooks.error(field + ' must name a declared frames2d track')\n return undefined\n }\n return raw\n}\n\n/** Parse one mode restore rule \"{ stat (declared), amount, intervalMs }\". */\nfunction parseModeRestore(\n raw: unknown,\n field: string,\n stats: Record<string, PetGameplayStatDef>,\n fail: (message: string) => void,\n): { stat: string; amount: number; intervalMs: number } | undefined {\n if (!isRecord(raw)) {\n fail(field + ' must be an object { stat, amount, intervalMs }')\n return undefined\n }\n const extra = unknownKeys(raw, KNOWN_RESTORE)\n if (extra.length > 0) fail(field + ': unknown field(s) ' + extra.map(k => JSON.stringify(k)).join(', '))\n const stat = typeof raw.stat === 'string' && stats[raw.stat] !== undefined ? raw.stat : undefined\n if (stat === undefined) fail(field + '.stat must reference a declared stat')\n if (!intIn(raw.amount, 1, 1000)) fail(field + '.amount must be an integer in [1, 1000]')\n if (!intIn(raw.intervalMs, 1000, 600_000)) fail(field + '.intervalMs must be an integer in [1000, 600000]')\n if (stat === undefined || !intIn(raw.amount, 1, 1000) || !intIn(raw.intervalMs, 1000, 600_000)) return undefined\n return { stat, amount: raw.amount, intervalMs: raw.intervalMs }\n}\n\n/**\n * Validate the manifest 'gameplay' block (fail-closed). Only frames2d pets\n * may declare gameplay today: every state reference checks against the\n * declared track names.\n */\nexport function parseGameplayManifest(raw: unknown, hooks: GameplayParseHooks): PetGameplayManifest | undefined {\n const error = (message: string): void => hooks.error(message)\n if (!isRecord(raw)) {\n error('gameplay must be an object')\n return undefined\n }\n const extra = unknownKeys(raw, KNOWN_GAMEPLAY)\n if (extra.length > 0) error('gameplay: unknown field(s) ' + extra.map(k => JSON.stringify(k)).join(', '))\n let failed = false\n const fail = (message: string): void => { failed = true; error(message) }\n\n // --- stats (parsed first: effects reference them) ---\n const stats: Record<string, PetGameplayStatDef> = {}\n if (raw.stats !== undefined) {\n if (!isRecord(raw.stats)) fail('gameplay.stats must be an object keyed by stat id')\n else {\n const entries = Object.entries(raw.stats)\n if (entries.length > MAX_STATS) fail('gameplay.stats declares too many stats (max ' + MAX_STATS + ')')\n for (const [name, value] of entries) {\n if (!validName(name, 24)) {\n fail('gameplay.stats: invalid stat id ' + JSON.stringify(name))\n continue\n }\n if (!isRecord(value)) {\n fail('gameplay.stats.' + name + ' must be an object')\n continue\n }\n const statExtra = unknownKeys(value, KNOWN_STAT)\n if (statExtra.length > 0) fail('gameplay.stats.' + name + ': unknown field(s) ' + statExtra.map(k => JSON.stringify(k)).join(', '))\n if (!intIn(value.max, 1, STAT_VALUE_MAX)) {\n fail('gameplay.stats.' + name + '.max must be an integer in [1, ' + STAT_VALUE_MAX + ']')\n continue\n }\n const def: PetGameplayStatDef = { max: value.max }\n if (value.initial !== undefined) {\n if (!numIn(value.initial, 0, value.max)) fail('gameplay.stats.' + name + '.initial must be within [0, max]')\n else def.initial = value.initial\n }\n for (const key of ['decayPerMinute', 'workingDecayPerMinute', 'idleDecayPerMinute'] as const) {\n if (value[key] !== undefined) {\n if (!numIn(value[key], 0, 1000)) fail('gameplay.stats.' + name + '.' + key + ' must be a number in [0, 1000]')\n else def[key] = value[key] as number\n }\n }\n stats[name] = def\n }\n }\n }\n\n const block: PetGameplayManifest = {}\n if (Object.keys(stats).length > 0) block.stats = stats\n\n // --- idle director ---\n if (raw.idleDirector !== undefined) {\n if (!isRecord(raw.idleDirector) || !Array.isArray(raw.idleDirector.acts)) {\n fail('gameplay.idleDirector must be an object with an acts array')\n } else {\n const d = raw.idleDirector as Record<string, unknown> & { acts: unknown[] }\n const dExtra = unknownKeys(d, KNOWN_IDLE_DIRECTOR)\n if (dExtra.length > 0) fail('gameplay.idleDirector: unknown field(s) ' + dExtra.map(k => JSON.stringify(k)).join(', '))\n if (d.intervalMs !== undefined && !intIn(d.intervalMs, 1000, 60_000)) fail('gameplay.idleDirector.intervalMs must be an integer in [1000, 60000]')\n if (d.maxMiss !== undefined && !intIn(d.maxMiss, 0, 10)) fail('gameplay.idleDirector.maxMiss must be an integer in [0, 10]')\n if (d.idleWeight !== undefined && !intIn(d.idleWeight, 0, 10_000)) fail('gameplay.idleDirector.idleWeight must be an integer in [0, 10000]')\n if (d.acts.length === 0 || d.acts.length > MAX_ACTS) fail('gameplay.idleDirector.acts must declare 1..' + MAX_ACTS + ' acts')\n const acts: { track: string; weight: number; phrases?: string[] }[] = []\n for (const act of d.acts as unknown[]) {\n if (!isRecord(act) || !intIn(act.weight, 1, 10_000)) {\n fail('gameplay.idleDirector.acts entries need a weight integer in [1, 10000]')\n continue\n }\n const aExtra = unknownKeys(act, KNOWN_ACT)\n if (aExtra.length > 0) fail('gameplay.idleDirector.acts: unknown field(s) ' + aExtra.map(k => JSON.stringify(k)).join(', '))\n const track = parseStateRef(act.track, 'gameplay.idleDirector.acts.track', hooks)\n if (track === undefined) continue\n const entry: { track: string; weight: number; phrases?: string[] } = { track, weight: act.weight }\n const phrases = parsePhrases(act.phrases, 'gameplay.idleDirector.acts.phrases', hooks)\n if (phrases !== undefined) entry.phrases = phrases\n acts.push(entry)\n }\n if (acts.length > 0) {\n block.idleDirector = {\n intervalMs: intIn(d.intervalMs, 1000, 60_000) ? d.intervalMs as number : 5000,\n maxMiss: intIn(d.maxMiss, 0, 10) ? d.maxMiss as number : 2,\n idleWeight: intIn(d.idleWeight, 0, 10_000) ? d.idleWeight as number : 0,\n acts,\n }\n }\n }\n }\n\n // --- hit box ---\n if (raw.hitBox !== undefined) {\n const b = raw.hitBox\n if (!isRecord(b) || !numIn(b.x0, 0, 1) || !numIn(b.x1, 0, 1) || !numIn(b.y0, 0, 1) || !numIn(b.y1, 0, 1)\n || !(b.x0 < b.x1) || !(b.y0 < b.y1)) {\n fail('gameplay.hitBox must be { x0, y0, x1, y1 } fractions with x0 < x1 and y0 < y1')\n } else {\n block.hitBox = { x0: b.x0, y0: b.y0, x1: b.x1, y1: b.y1 }\n }\n }\n\n // --- touch zones ---\n if (raw.touch !== undefined) {\n if (!isRecord(raw.touch) || !Array.isArray(raw.touch.zones)) {\n fail('gameplay.touch must be an object with a zones array')\n } else {\n const tExtra = unknownKeys(raw.touch, KNOWN_TOUCH)\n if (tExtra.length > 0) fail('gameplay.touch: unknown field(s) ' + tExtra.map(k => JSON.stringify(k)).join(', '))\n let clickBoost: { stat: string; min: number; max: number } | undefined\n if (raw.touch.clickBoost !== undefined) {\n const cb = raw.touch.clickBoost\n if (!isRecord(cb) || typeof cb.stat !== 'string' || stats[cb.stat] === undefined\n || !intIn(cb.min, 0, 1000) || !intIn(cb.max, 0, 1000) || (cb.min as number) > (cb.max as number)) {\n fail('gameplay.touch.clickBoost must be { stat (declared), min, max } integers with 0 <= min <= max <= 1000')\n } else clickBoost = { stat: cb.stat, min: cb.min, max: cb.max }\n }\n const zones: PetGameplayTouchZone[] = []\n if (raw.touch.zones.length === 0 || raw.touch.zones.length > MAX_ZONES) fail('gameplay.touch.zones must declare 1..' + MAX_ZONES + ' zones')\n for (const zoneRaw of raw.touch.zones as unknown[]) {\n if (!isRecord(zoneRaw) || !validName(zoneRaw.name) || !numIn(zoneRaw.y0, 0, 1) || !numIn(zoneRaw.y1, 0, 1) || !(zoneRaw.y0 < zoneRaw.y1)) {\n fail('gameplay.touch.zones entries need a kebab name and 0 <= y0 < y1 <= 1')\n continue\n }\n const zExtra = unknownKeys(zoneRaw, KNOWN_ZONE)\n if (zExtra.length > 0) fail('gameplay.touch.' + zoneRaw.name + ': unknown field(s) ' + zExtra.map(k => JSON.stringify(k)).join(', '))\n if (!Array.isArray(zoneRaw.branches) || zoneRaw.branches.length === 0 || zoneRaw.branches.length > MAX_BRANCHES) {\n fail('gameplay.touch.' + zoneRaw.name + '.branches must declare 1..' + MAX_BRANCHES + ' branches')\n continue\n }\n let probabilitySum = 0\n const branches: PetGameplayTouchBranch[] = []\n for (const branchRaw of zoneRaw.branches as unknown[]) {\n if (!isRecord(branchRaw) || !numIn(branchRaw.probability, 0, 1) || branchRaw.probability === 0) {\n fail('gameplay.touch.' + zoneRaw.name + '.branches entries need a probability in (0, 1]')\n continue\n }\n const bExtra = unknownKeys(branchRaw, KNOWN_BRANCH)\n if (bExtra.length > 0) fail('gameplay.touch.' + zoneRaw.name + ': unknown branch field(s) ' + bExtra.map(k => JSON.stringify(k)).join(', '))\n probabilitySum += branchRaw.probability\n const branch: PetGameplayTouchBranch = { probability: branchRaw.probability }\n const effects = parseEffects(branchRaw.effects, 'gameplay.touch.' + zoneRaw.name + '.effects', stats, hooks)\n if (effects !== undefined) branch.effects = effects\n const state = parseStateRef(branchRaw.state, 'gameplay.touch.' + zoneRaw.name + '.state', hooks)\n if (state !== undefined) branch.state = state\n if (branchRaw.stateMs !== undefined) {\n if (!intIn(branchRaw.stateMs, 200, 10_000)) fail('gameplay.touch.' + zoneRaw.name + '.stateMs must be an integer in [200, 10000]')\n else branch.stateMs = branchRaw.stateMs\n }\n const phrases = parsePhrases(branchRaw.phrases, 'gameplay.touch.' + zoneRaw.name + '.phrases', hooks)\n if (phrases !== undefined) branch.phrases = phrases\n branches.push(branch)\n }\n if (probabilitySum > 1 + 1e-9) fail('gameplay.touch.' + zoneRaw.name + ': branch probabilities must sum to at most 1')\n if (branches.length > 0) zones.push({ name: zoneRaw.name, y0: zoneRaw.y0, y1: zoneRaw.y1, branches })\n }\n if (zones.length > 0 || clickBoost !== undefined) block.touch = { zones, ...(clickBoost === undefined ? {} : { clickBoost }) }\n }\n }\n\n // --- work ---\n if (raw.work !== undefined) {\n const w = raw.work\n if (!isRecord(w)) fail('gameplay.work must be an object')\n else {\n const wExtra = unknownKeys(w, KNOWN_WORK)\n if (wExtra.length > 0) fail('gameplay.work: unknown field(s) ' + wExtra.map(k => JSON.stringify(k)).join(', '))\n const state = parseStateRef(w.state, 'gameplay.work.state', hooks)\n const successState = parseStateRef(w.successState, 'gameplay.work.successState', hooks)\n const failState = parseStateRef(w.failState, 'gameplay.work.failState', hooks)\n if (!intIn(w.tickMs, 1000, 60_000)) fail('gameplay.work.tickMs must be an integer in [1000, 60000]')\n if (!numIn(w.successProbability, 0, 1)) fail('gameplay.work.successProbability must be a number in [0, 1]')\n if (state !== undefined && successState !== undefined && failState !== undefined\n && intIn(w.tickMs, 1000, 60_000) && numIn(w.successProbability, 0, 1)) {\n const work: NonNullable<PetGameplayManifest['work']> = {\n state, successState, failState,\n tickMs: w.tickMs,\n successProbability: w.successProbability,\n }\n if (w.resultMs !== undefined) {\n if (!isRecord(w.resultMs) || !intIn(w.resultMs.success, 200, 10_000) || !intIn(w.resultMs.fail, 200, 10_000)) {\n fail('gameplay.work.resultMs must be { success, fail } integers in [200, 10000]')\n } else work.resultMs = { success: w.resultMs.success, fail: w.resultMs.fail }\n }\n for (const key of ['success', 'fail'] as const) {\n if (w[key] !== undefined) {\n if (!isRecord(w[key])) fail('gameplay.work.' + key + ' must be an object { effects }')\n else {\n const effects = parseEffects((w[key] as Record<string, unknown>).effects, 'gameplay.work.' + key + '.effects', stats, hooks)\n if (effects !== undefined) work[key] = { effects }\n }\n }\n }\n block.work = work\n }\n }\n }\n\n // --- sleep ---\n if (raw.sleep !== undefined) {\n const s = raw.sleep\n if (!isRecord(s) || !isRecord(s.restore)) fail('gameplay.sleep must be an object with a restore block')\n else {\n const sExtra = unknownKeys(s, KNOWN_SLEEP)\n if (sExtra.length > 0) fail('gameplay.sleep: unknown field(s) ' + sExtra.map(k => JSON.stringify(k)).join(', '))\n const state = parseStateRef(s.state, 'gameplay.sleep.state', hooks)\n const wakeState = parseStateRef(s.wakeState, 'gameplay.sleep.wakeState', hooks)\n const restore = parseModeRestore(s.restore, 'gameplay.sleep.restore', stats, fail)\n if (state !== undefined && restore !== undefined) {\n block.sleep = {\n state,\n ...(wakeState === undefined ? {} : { wakeState }),\n restore,\n }\n }\n }\n }\n\n // --- extra modes (bath and friends) ---\n if (raw.modes !== undefined) {\n if (!isRecord(raw.modes)) fail('gameplay.modes must be an object keyed by mode id')\n else {\n const entries = Object.entries(raw.modes)\n if (entries.length > MAX_MODES) fail('gameplay.modes declares too many modes (max ' + MAX_MODES + ')')\n const modes: Record<string, PetGameplayModeDef> = {}\n for (const [name, value] of entries) {\n if (!validName(name, 24) || name === 'work' || name === 'sleep') {\n fail('gameplay.modes: invalid mode id ' + JSON.stringify(name) + ' (kebab, and not the reserved work/sleep)')\n continue\n }\n if (!isRecord(value)) {\n fail('gameplay.modes.' + name + ' must be an object')\n continue\n }\n const mExtra = unknownKeys(value, KNOWN_MODE)\n if (mExtra.length > 0) fail('gameplay.modes.' + name + ': unknown field(s) ' + mExtra.map(k => JSON.stringify(k)).join(', '))\n const state = parseStateRef(value.state, 'gameplay.modes.' + name + '.state', hooks)\n let usable = state !== undefined\n let label: string | undefined\n if (value.label !== undefined) {\n if (typeof value.label !== 'string' || value.label.trim() === '' || value.label.length > MODE_LABEL_MAX_LENGTH) {\n fail('gameplay.modes.' + name + '.label must be a non-empty string of at most ' + MODE_LABEL_MAX_LENGTH + ' chars')\n usable = false\n } else label = value.label.trim()\n }\n let activeLabel: string | undefined\n if (value.activeLabel !== undefined) {\n if (typeof value.activeLabel !== 'string' || value.activeLabel.trim() === '' || value.activeLabel.length > MODE_LABEL_MAX_LENGTH) {\n fail('gameplay.modes.' + name + '.activeLabel must be a non-empty string of at most ' + MODE_LABEL_MAX_LENGTH + ' chars')\n usable = false\n } else activeLabel = value.activeLabel.trim()\n }\n const restore = value.restore === undefined ? undefined : parseModeRestore(value.restore, 'gameplay.modes.' + name + '.restore', stats, fail)\n if (value.restore !== undefined && restore === undefined) usable = false\n if (usable && state !== undefined) {\n modes[name] = {\n state,\n ...(label === undefined ? {} : { label }),\n ...(activeLabel === undefined ? {} : { activeLabel }),\n ...(restore === undefined ? {} : { restore }),\n }\n }\n }\n if (Object.keys(modes).length > 0) block.modes = modes\n }\n }\n\n // --- random roaming ---\n if (raw.roam !== undefined) {\n const rm = raw.roam\n if (!isRecord(rm)) fail('gameplay.roam must be an object')\n else {\n const rExtra = unknownKeys(rm, KNOWN_ROAM)\n if (rExtra.length > 0) fail('gameplay.roam: unknown field(s) ' + rExtra.map(k => JSON.stringify(k)).join(', '))\n const state = parseStateRef(rm.state, 'gameplay.roam.state', hooks)\n if (!intIn(rm.intervalMs, 1000, 3_600_000)) fail('gameplay.roam.intervalMs must be an integer in [1000, 3600000]')\n if (!numIn(rm.probability, 0, 1) || rm.probability === 0) fail('gameplay.roam.probability must be a number in (0, 1]')\n if (!intIn(rm.distanceMin, 1, 2000)) fail('gameplay.roam.distanceMin must be an integer in [1, 2000]')\n if (!intIn(rm.distanceMax, 1, 2000)) fail('gameplay.roam.distanceMax must be an integer in [1, 2000]')\n if (intIn(rm.distanceMin, 1, 2000) && intIn(rm.distanceMax, 1, 2000) && rm.distanceMin > rm.distanceMax) {\n fail('gameplay.roam.distanceMin must not exceed distanceMax')\n }\n if (!intIn(rm.speed, 1, 2000)) fail('gameplay.roam.speed must be an integer in [1, 2000] (px per second)')\n let directions: PetRoamDirection[] | undefined\n if (rm.directions !== undefined) {\n if (!Array.isArray(rm.directions) || rm.directions.length === 0) {\n fail('gameplay.roam.directions must be a non-empty array of up, down, left, right')\n } else {\n const picked: PetRoamDirection[] = []\n for (const entry of rm.directions as unknown[]) {\n if (typeof entry !== 'string' || !PET_ROAM_DIRECTIONS.includes(entry as PetRoamDirection)) {\n fail('gameplay.roam.directions entries must be up, down, left or right')\n picked.length = 0\n break\n }\n if (picked.includes(entry as PetRoamDirection)) {\n fail('gameplay.roam.directions must not repeat ' + entry)\n picked.length = 0\n break\n }\n picked.push(entry as PetRoamDirection)\n }\n if (picked.length > 0) directions = picked\n }\n }\n // The guards are repeated inline: tsc only narrows the unknown fields\n // through a call in the condition itself.\n if (state !== undefined\n && intIn(rm.intervalMs, 1000, 3_600_000)\n && numIn(rm.probability, 0, 1) && rm.probability !== 0\n && intIn(rm.distanceMin, 1, 2000)\n && intIn(rm.distanceMax, 1, 2000)\n && rm.distanceMin <= rm.distanceMax\n && intIn(rm.speed, 1, 2000)) {\n block.roam = {\n state,\n intervalMs: rm.intervalMs,\n probability: rm.probability,\n distanceMin: rm.distanceMin,\n distanceMax: rm.distanceMax,\n speed: rm.speed,\n ...(directions === undefined ? {} : { directions }),\n }\n }\n }\n }\n\n // --- passive income ---\n if (raw.passiveIncome !== undefined) {\n const p = raw.passiveIncome\n if (!isRecord(p) || !validName(p.currency, 24) || !intIn(p.amount, 1, 10_000) || !intIn(p.intervalMs, 1000, 86_400_000)) {\n fail('gameplay.passiveIncome must be { currency (kebab), amount 1..10000, intervalMs 1000..86400000 }')\n } else {\n block.passiveIncome = { currency: p.currency, amount: p.amount, intervalMs: p.intervalMs }\n }\n }\n\n // --- shop ---\n if (raw.shop !== undefined) {\n const s = raw.shop\n if (!isRecord(s) || !Array.isArray(s.items) || s.items.length === 0 || s.items.length > MAX_SHOP_ITEMS) {\n fail('gameplay.shop must be an object with 1..' + MAX_SHOP_ITEMS + ' items')\n } else {\n const shopState = parseStateRef(s.state, 'gameplay.shop.state', hooks)\n const items: PetGameplayShopItem[] = []\n const seen = new Set<string>()\n for (const itemRaw of s.items as unknown[]) {\n if (!isRecord(itemRaw) || !validName(itemRaw.id, 24)) {\n fail('gameplay.shop.items entries need a kebab id')\n continue\n }\n if (seen.has(itemRaw.id)) {\n fail('gameplay.shop: duplicate item id ' + JSON.stringify(itemRaw.id))\n continue\n }\n seen.add(itemRaw.id)\n const iExtra = unknownKeys(itemRaw, KNOWN_SHOP_ITEM)\n if (iExtra.length > 0) fail('gameplay.shop.' + itemRaw.id + ': unknown field(s) ' + iExtra.map(k => JSON.stringify(k)).join(', '))\n if (typeof itemRaw.label !== 'string' || itemRaw.label.trim() === '' || itemRaw.label.length > 80) {\n fail('gameplay.shop.' + itemRaw.id + '.label must be a non-empty string of at most 80 chars')\n continue\n }\n if (!intIn(itemRaw.price, 1, 1_000_000)) {\n fail('gameplay.shop.' + itemRaw.id + '.price must be an integer in [1, 1000000]')\n continue\n }\n if (!validName(itemRaw.currency, 24)) {\n fail('gameplay.shop.' + itemRaw.id + '.currency must be a kebab id')\n continue\n }\n const item: PetGameplayShopItem = {\n id: itemRaw.id,\n label: itemRaw.label.trim(),\n price: itemRaw.price,\n currency: itemRaw.currency,\n }\n if (itemRaw.image !== undefined) {\n if (typeof itemRaw.image !== 'string' || itemRaw.image.includes('..') || itemRaw.image.includes('\\\\') || itemRaw.image.startsWith('/')) {\n fail('gameplay.shop.' + itemRaw.id + '.image must be a safe manifest-relative frame path')\n } else item.image = itemRaw.image\n }\n const effects = parseEffects(itemRaw.effects, 'gameplay.shop.' + itemRaw.id + '.effects', stats, hooks)\n if (effects !== undefined) item.effects = effects\n if (itemRaw.lottery !== undefined) {\n const l = itemRaw.lottery\n if (!isRecord(l) || !Array.isArray(l.tiers) || l.tiers.length === 0 || l.tiers.length > MAX_LOTTERY_TIERS) {\n fail('gameplay.shop.' + itemRaw.id + '.lottery needs 1..' + MAX_LOTTERY_TIERS + ' tiers')\n } else {\n const lExtra = unknownKeys(l, KNOWN_LOTTERY)\n if (lExtra.length > 0) fail('gameplay.shop.' + itemRaw.id + '.lottery: unknown field(s) ' + lExtra.map(k => JSON.stringify(k)).join(', '))\n if (l.currency !== undefined && !validName(l.currency, 24)) fail('gameplay.shop.' + itemRaw.id + '.lottery.currency must be a kebab id')\n let tierSum = 0\n const tiers: { probability: number; prize: number; currency?: string }[] = []\n for (const tierRaw of l.tiers as unknown[]) {\n if (!isRecord(tierRaw) || !numIn(tierRaw.probability, 0, 1) || tierRaw.probability === 0\n || !intIn(tierRaw.prize, 0, 1_000_000_000)) {\n fail('gameplay.shop.' + itemRaw.id + '.lottery.tiers entries need probability (0,1] and prize 0..1e9')\n continue\n }\n tierSum += tierRaw.probability\n const tier: { probability: number; prize: number; currency?: string } = {\n probability: tierRaw.probability,\n prize: tierRaw.prize,\n }\n if (tierRaw.currency !== undefined) {\n if (!validName(tierRaw.currency, 24)) fail('gameplay.shop.' + itemRaw.id + '.lottery tier currency must be a kebab id')\n else tier.currency = tierRaw.currency\n }\n tiers.push(tier)\n }\n if (tierSum > 1 + 1e-9) fail('gameplay.shop.' + itemRaw.id + '.lottery tier probabilities must sum to at most 1')\n if (tiers.length > 0) {\n const lotteryEffects = parseEffects(l.effects, 'gameplay.shop.' + itemRaw.id + '.lottery.effects', stats, hooks)\n item.lottery = {\n tiers,\n ...(lotteryEffects === undefined ? {} : { effects: lotteryEffects }),\n ...(validName(l.currency, 24) ? { currency: l.currency } : {}),\n }\n }\n }\n }\n if (item.effects === undefined && item.lottery === undefined) {\n fail('gameplay.shop.' + itemRaw.id + ' needs effects or a lottery')\n continue\n }\n items.push(item)\n }\n if (items.length > 0) block.shop = { ...(shopState === undefined ? {} : { state: shopState }), items }\n }\n }\n\n // --- drag state ---\n if (raw.dragState !== undefined) {\n const state = parseStateRef(raw.dragState, 'gameplay.dragState', hooks)\n if (state !== undefined) block.dragState = state\n }\n if (raw.dragEndState !== undefined) {\n const state = parseStateRef(raw.dragEndState, 'gameplay.dragEndState', hooks)\n if (state !== undefined) block.dragEndState = state\n }\n\n return failed ? undefined : block\n}\n\n/* ------------------------------------------------------------------ *\n * Host engine (pure; clock and rng injected)\n * ------------------------------------------------------------------ */\n\n/** Persisted per-pet gameplay state (pet.json 'gameplay' map values). */\nexport interface PetGameplayState {\n stats: Record<string, number>\n currencies: Record<string, number>\n /** Active gameplay mode id ('work' | 'sleep' | a declared extra mode) or null. */\n mode: string | null\n /** Epoch ms of the last lazy settle. */\n settledAt: number\n /** Accumulated remainder ms towards the next passive income tick. */\n incomeCarryMs?: number\n /** Accumulated remainder ms towards the next mode restore tick. */\n restoreCarryMs?: number\n}\n\n/**\n * One declared extra mode, by OWN key only. A plain `modes[id]` lookup also\n * answers for Object.prototype members ('constructor', 'toString', …), which\n * would let a crafted mode id pass the \"is it declared?\" test.\n */\nfunction declaredModeOf(manifest: PetGameplayManifest, mode: string): PetGameplayModeDef | undefined {\n const modes = manifest.modes\n if (modes === undefined || !Object.prototype.hasOwnProperty.call(modes, mode)) return undefined\n return modes[mode]\n}\n\n/** Every mode the menu offers, in manifest order (sleep first, then extras). */\nexport function declaredModes(manifest: PetGameplayManifest): string[] {\n return [\n ...(manifest.sleep === undefined ? [] : ['sleep']),\n ...Object.keys(manifest.modes ?? {}),\n ]\n}\n\n/**\n * The frames2d track one active mode holds. 'work' is owned by the work loop\n * (its state, result and fallback are its own), so it resolves to undefined.\n */\nexport function modeStateOf(manifest: PetGameplayManifest, mode: string): string | undefined {\n if (mode === 'sleep') return manifest.sleep?.state\n if (mode === 'work') return manifest.work?.state\n return declaredModeOf(manifest, mode)?.state\n}\n\n/** The restore rule of one active mode, when it declares one. */\nexport function modeRestoreOf(\n manifest: PetGameplayManifest,\n mode: string | null,\n): { stat: string; amount: number; intervalMs: number } | undefined {\n if (mode === null) return undefined\n if (mode === 'sleep') return manifest.sleep?.restore\n if (mode === 'work') return undefined\n return declaredModeOf(manifest, mode)?.restore\n}\n\n/** Whether the manifest still declares this gameplay mode id. */\nexport function isDeclaredMode(manifest: PetGameplayManifest, mode: string): boolean {\n if (mode === 'work') return manifest.work !== undefined\n if (mode === 'sleep') return manifest.sleep !== undefined\n return declaredModeOf(manifest, mode) !== undefined\n}\n\n/** Fresh state for one pet: stats at their initial (default max), no currency. */\nexport function initialGameplayState(manifest: PetGameplayManifest, now: number): PetGameplayState {\n const stats: Record<string, number> = {}\n for (const [name, def] of Object.entries(manifest.stats ?? {})) {\n stats[name] = def.initial ?? def.max\n }\n return { stats, currencies: {}, mode: null, settledAt: now }\n}\n\n/** Clamp one stat value into [0, max]; currencies into [0, CURRENCY_MAX]. */\nexport function clampGameplay(state: PetGameplayState, manifest: PetGameplayManifest): void {\n for (const [name, def] of Object.entries(manifest.stats ?? {})) {\n const value = state.stats[name]\n if (value === undefined) state.stats[name] = def.initial ?? def.max\n else state.stats[name] = Math.min(def.max, Math.max(0, value))\n }\n for (const [name, value] of Object.entries(state.currencies)) {\n state.currencies[name] = Math.min(CURRENCY_MAX, Math.max(0, Math.floor(value)))\n }\n}\n\n/**\n * Lazy settle: apply stat decay, passive income and the active mode's restore\n * rule (sleep restores energy, a declared extra mode restores whatever it\n * declares) for the elapsed wall time since the last settle. Mirrors the\n * treats.ts discipline (no host timers; read paths settle). Returns whether\n * anything changed.\n */\nexport function settleGameplay(\n state: PetGameplayState,\n manifest: PetGameplayManifest,\n now: number,\n options: { sessionActive: boolean },\n): boolean {\n const elapsedMs = now - state.settledAt\n if (elapsedMs <= 0) return false\n const minutes = elapsedMs / 60_000\n let changed = false\n for (const [name, def] of Object.entries(manifest.stats ?? {})) {\n const current = state.stats[name]\n if (current === undefined || current <= 0) continue\n let rate = def.decayPerMinute ?? 0\n if (state.mode === 'work' && def.workingDecayPerMinute !== undefined) rate = def.workingDecayPerMinute\n if (!options.sessionActive) rate += def.idleDecayPerMinute ?? 0\n if (rate <= 0) continue\n const next = Math.max(0, current - rate * minutes)\n if (next !== current) {\n state.stats[name] = next\n changed = true\n }\n }\n if (manifest.passiveIncome !== undefined) {\n const incomeElapsed = elapsedMs + (state.incomeCarryMs ?? 0)\n const interval = manifest.passiveIncome.intervalMs\n const ticks = Math.floor(incomeElapsed / interval)\n state.incomeCarryMs = incomeElapsed % interval\n if (ticks > 0) {\n const currency = manifest.passiveIncome.currency\n state.currencies[currency] = (state.currencies[currency] ?? 0) + ticks * manifest.passiveIncome.amount\n changed = true\n }\n }\n const restore = modeRestoreOf(manifest, state.mode)\n if (restore !== undefined) {\n const restoreElapsed = elapsedMs + (state.restoreCarryMs ?? 0)\n const interval = restore.intervalMs\n const ticks = Math.floor(restoreElapsed / interval)\n state.restoreCarryMs = restoreElapsed % interval\n if (ticks > 0) {\n state.stats[restore.stat] = (state.stats[restore.stat] ?? 0) + ticks * restore.amount\n changed = true\n }\n } else {\n state.restoreCarryMs = 0\n }\n state.settledAt = now\n clampGameplay(state, manifest)\n return changed\n}\n\n/** Apply one effect vector (touch/work/shop), clamped. */\nexport function applyGameplayEffects(state: PetGameplayState, manifest: PetGameplayManifest, effects: readonly PetGameplayEffect[]): void {\n for (const effect of effects) {\n if (effect.stat !== undefined) {\n state.stats[effect.stat] = (state.stats[effect.stat] ?? 0) + effect.amount\n } else if (effect.currency !== undefined) {\n state.currencies[effect.currency] = (state.currencies[effect.currency] ?? 0) + effect.amount\n }\n }\n clampGameplay(state, manifest)\n}\n\n/** Roll one touch zone branch; undefined when the roll lands in no-op mass. */\nexport function rollTouchBranch(zone: PetGameplayTouchZone, rng: () => number): PetGameplayTouchBranch | undefined {\n const roll = rng()\n let acc = 0\n for (const branch of zone.branches) {\n acc += branch.probability\n if (roll < acc) return branch\n }\n return undefined\n}\n\n/** Roll one work tick outcome. */\nexport function rollWorkOutcome(work: NonNullable<PetGameplayManifest['work']>, rng: () => number): 'success' | 'fail' {\n return rng() < work.successProbability ? 'success' : 'fail'\n}\n\n/** Draw one lottery prize tier; uncovered mass falls through to the last tier. */\nexport function drawLotteryTier(\n lottery: NonNullable<PetGameplayShopItem['lottery']>,\n rng: () => number,\n): { probability: number; prize: number; currency?: string } {\n const roll = rng()\n let acc = 0\n for (const tier of lottery.tiers) {\n acc += tier.probability\n if (roll < acc) return tier\n }\n return lottery.tiers[lottery.tiers.length - 1]!\n}\n\n/** The zone one normalized hit-box point lands in, if any. */\nexport function touchZoneAt(touch: { zones: PetGameplayTouchZone[] }, yFraction: number): PetGameplayTouchZone | undefined {\n return touch.zones.find(zone => yFraction >= zone.y0 && yFraction < zone.y1)\n}\n","/**\n * Gameplay HUD — the client half of the manifest 'gameplay' block (miku-pet\n * generalization). One component owns everything the block needs: the stat\n * bars and shop card (menu / shop pages), the touch-zone tap\n * handling, the idle director rolls, the work and sleep loops, and the\n * float-text toasts. It talks to the host through the injected verb API,\n * writes results straight back into the store (the 2 s poll stays the\n * backstop), and steers the frames2d renderer through the per-pet bus.\n * @module @linxin666/dsh-pet/client/GameplayHud\n */\n\nimport { useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, type ReactElement } from 'react'\nimport type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { PetDefinition, PetSkinDefinition } from '../registry.ts'\nimport type { PetGameplayVerbResult } from '../service.ts'\nimport { declaredModes, modeStateOf, PET_ROAM_DIRECTIONS, touchZoneAt, type PetRoamDirection } from '../gameplay.ts'\nimport type { PetStoreInstance } from './pet-store.ts'\nimport type { DragStream } from './drag-stream.ts'\nimport type { NS } from './locales.ts'\nimport styles from './pet.module.css'\n\n/** The gameplay verb API the plugin apply body injects (host-authoritative). */\nexport interface GameplayApi {\n touch: (zone?: string) => Promise<PetGameplayVerbResult>\n setMode: (mode: string | null) => Promise<PetGameplayVerbResult>\n workTick: () => Promise<PetGameplayVerbResult>\n buy: (item: string) => Promise<PetGameplayVerbResult>\n /**\n * Persist the selected skin for the current pet (host-authoritative;\n * `undefined` restores the pet's default look).\n */\n setSkin: (skin: string | undefined) => Promise<{ ok: boolean; error?: string }>\n}\n\n/**\n * The per-pet coordination bus. The frames2d visual mount registers the\n * track override (setTrack); the HUD registers the sprite tap handler; the\n * chrome calls into whatever is registered. Optional chaining everywhere —\n * either side may be mid-remount during a hot reload.\n */\nexport interface GameplayBus {\n setTrack?: (track?: string) => void\n /** Swap the pet's base idle track (skin switch); undefined restores default. */\n setIdleTrack?: (track?: string) => void\n /**\n * The base idle track the HUD wants right now, latched on the bus so a\n * renderer that registers late (or remounts: hidden/summoned, StrictMode's\n * double mount) still applies the restored skin instead of snapping back to\n * the default look. Mutating it never requires a re-render.\n */\n idleTrack?: string\n tap?: (fx: number, fy: number) => void\n /**\n * Card open/close request from the chrome (the hover panel's 玩法 action):\n * the HUD registers this, and calling it with no argument toggles the card\n * while a boolean pins the state (same chrome -> HUD direction as tap).\n */\n openCard?: (open?: boolean) => void\n /**\n * Walk the sprite in `direction` by `distance` px at `speed` px/s, clamped\n * to the viewport, and persist the resting spot like a drag. Returns the\n * distance actually travelled (0 when it cannot move), so the caller can\n * hold the walk art for exactly that long. Registered by the chrome\n * (PetSprite); absent while the sprite is unmounted.\n */\n walk?: (direction: PetRoamDirection, distance: number, speed: number) => number\n}\n\ntype HudPage = 'root' | 'shop' | 'skins'\n\n/** One floating toast (prize / insufficient funds). */\ninterface HudFloat {\n id: number\n text: string\n}\n\nlet floatSeq = 0\n\n/** The gameplay overlay for one frames2d pet that declares 'gameplay'. */\nexport function GameplayHud(props: {\n definition: PetDefinition\n store: PetStoreInstance\n api: GameplayApi\n bus: GameplayBus\n drag: DragStream\n t: PropsLocale<typeof NS>['t']\n}): ReactElement | null {\n const { definition, store, api, bus } = props\n const ui = useSyncExternalStore(store.subscribe, store.getSnapshot)\n const def = definition.gameplay\n const view = ui.snapshot?.gameplay\n // Host-persisted skin selection for this pet (undefined = default look).\n const persistedSkin = ui.snapshot?.skin\n\n const [open, setOpen] = useState(false)\n const [page, setPage] = useState<HudPage>('root')\n // Currently selected skin id (base idle swap); undefined = default look.\n const [skinId, setSkinId] = useState<string | undefined>(undefined)\n const skinIdRef = useRef<string | undefined>(undefined)\n skinIdRef.current = skinId\n const hudRef = useRef<HTMLDivElement | null>(null)\n const cardRef = useRef<HTMLDivElement | null>(null)\n const [floats, setFloats] = useState<HudFloat[]>([])\n // Mutable driver state (refs so intervals never re-arm on a poll tick).\n const modeRef = useRef<string | null>(view?.mode ?? null)\n modeRef.current = view?.mode ?? null\n /** Live gameplay view for the interval loops (def identity is stable, view is not). */\n const viewRef = useRef(view)\n viewRef.current = view\n const draggingRef = useRef(false)\n const touchLockUntilRef = useRef(0)\n const missRef = useRef(0)\n const busyRef = useRef(false)\n /** A roam walk owns the visual right now (the idle director must not steal it). */\n const roamHeldRef = useRef(false)\n /** A one-shot idle-director act owns the visual right now (the roam must not cut in). */\n const actHeldRef = useRef(false)\n /** Pending release of the roam's walk track (cleared when another owner takes it). */\n const roamTimerRef = useRef(0)\n\n // Dynamic-key lookups (stat ids / currency ids are manifest data).\n const tr = props.t as unknown as (key: string, values?: Record<string, string | number>) => string\n const statLabel = (name: string): string => tr('pet.gameplay.stat.' + name)\n const currencyLabel = (name: string): string => tr('pet.gameplay.currency.' + name)\n\n const pushFloat = (text: string): void => {\n const id = ++floatSeq\n setFloats(list => [...list.slice(-3), { id, text }])\n window.setTimeout(() => {\n setFloats(list => list.filter(entry => entry.id !== id))\n }, 1100)\n }\n\n const applyResult = (result: PetGameplayVerbResult): void => {\n if (result.view !== undefined) store.actions.setGameplayView(result.view)\n }\n\n /**\n * Give up the roam's claim on the shared track-override slot. Every other\n * owner (a mode, a touch reaction, a drag) calls this before it takes the\n * slot, so a walk that is still in flight can never release someone else's\n * track when its own hold window elapses.\n */\n const yieldRoam = (): void => {\n if (roamTimerRef.current !== 0) {\n window.clearTimeout(roamTimerRef.current)\n roamTimerRef.current = 0\n }\n roamHeldRef.current = false\n }\n\n // Tap handling (registered on the bus; PetSprite reports sprite-box\n // fractions). Sleep wakes on tap; work blocks taps; a held touch\n // animation turns taps into the plain-click boost.\n // Skin contract: while a skin is selected, taps only ever play that\n // skin's own click actions — a miss resolves to the plain click boost,\n // never the default touch zones (so a skinned pet cannot trigger the\n // default pet's shy/work reactions).\n useEffect(() => {\n if (def === undefined) return undefined\n // Play a one-shot override track and lock tap input for its duration so\n // consecutive taps cannot retrigger mid-play (skin click actions and\n // default touch-zone reactions share this path).\n const holdTrack = (track: string, holdMs: number): void => {\n yieldRoam()\n bus.setTrack?.(track)\n touchLockUntilRef.current = Date.now() + holdMs\n window.setTimeout(() => {\n if (Date.now() >= touchLockUntilRef.current) bus.setTrack?.(undefined)\n }, holdMs)\n }\n const speak = (phrases?: string[]): void => {\n if (phrases !== undefined && phrases.length > 0) {\n const phrase = phrases[Math.floor(Math.random() * phrases.length)]!\n store.actions.setFeedback({ text: phrase, kind: 'none', at: Date.now() })\n }\n }\n // Total play time of a track in ms (its fallback lands back in the skin\n // base idle, so holding the lock for the full loop is unnecessary).\n const trackDuration = (track: string): number =>\n definition.frames2d?.tracks[track]?.durations.reduce((sum, ms) => sum + ms, 0) ?? 0\n bus.tap = (fx, fy) => {\n // Any non-work mode ends on a tap (sleep wakes up, a bath steps out);\n // work keeps swallowing taps while its round is running.\n if (modeRef.current !== null && modeRef.current !== 'work') {\n void api.setMode(null).then(applyResult, () => undefined)\n return\n }\n if (modeRef.current === 'work') return\n const box = def.hitBox ?? { x0: 0, y0: 0, x1: 1, y1: 1 }\n const hx = (fx - box.x0) / (box.x1 - box.x0)\n const hy = (fy - box.y0) / (box.y1 - box.y0)\n if (hx < 0 || hx > 1 || hy < 0 || hy > 1) return\n if (Date.now() < touchLockUntilRef.current) {\n void api.touch().then(applyResult, () => undefined)\n return\n }\n const activeSkin = definition.frames2d?.skins?.find(skin => skin.id === skinIdRef.current)\n if (activeSkin !== undefined) {\n // Skin click actions roll first (declared order, cumulative\n // probabilities); on a hit play the action's track once. A miss\n // stays on the plain click boost — never the default touch zones.\n const actions = activeSkin.clickActions ?? []\n if (actions.length > 0) {\n let roll = Math.random()\n const fired = actions.find(action => {\n if (roll < action.probability) return true\n roll -= action.probability\n return false\n })\n if (fired !== undefined) {\n holdTrack(fired.track, trackDuration(fired.track) || 3000)\n speak(fired.phrases)\n return\n }\n }\n void api.touch().then(applyResult, () => undefined)\n return\n }\n const zone = def.touch === undefined ? undefined : touchZoneAt(def.touch, hy)\n if (zone === undefined) return\n void api.touch(zone.name).then((result) => {\n applyResult(result)\n if (result.hit !== true) return\n if (result.state !== undefined) holdTrack(result.state, result.stateMs ?? 3000)\n if (result.phrase !== undefined) {\n store.actions.setFeedback({ text: result.phrase, kind: 'none', at: Date.now() })\n }\n }, () => undefined)\n }\n return () => { bus.tap = undefined }\n // eslint-disable-next-line react-hooks/exhaustive-deps -- one registration per pet definition\n }, [definition.id, def])\n\n // Panel entry (chrome -> HUD): the hover panel's 玩法 button drives the\n // card through this channel so the chrome never needs the card's state.\n useEffect(() => {\n bus.openCard = (next?: boolean) => {\n setOpen(prev => next ?? !prev)\n setPage('root')\n }\n return () => { bus.openCard = undefined }\n // eslint-disable-next-line react-hooks/exhaustive-deps -- one registration per bus\n }, [bus])\n\n // Card placement: the card must not enter the bubble band above the sprite\n // or the hover-panel band below it, so it opens beside the sprite instead\n // of growing upward from the pet's feet. It is vertically centered on the\n // sprite box, clamped to the sprite's height, and the side is chosen by\n // the space available to each side (right first; a pet parked near the\n // right viewport edge flips the card to the left).\n useLayoutEffect(() => {\n if (!open) return undefined\n const hud = hudRef.current\n const card = cardRef.current\n if (hud === null || card === null) return undefined\n const place = (): void => {\n const box = hud.parentElement?.getBoundingClientRect()\n if (box === undefined) return\n const gap = 8\n const width = card.getBoundingClientRect().width\n const toRight = window.innerWidth - box.right\n const x = toRight >= width + gap ? box.width + gap : -(width + gap)\n card.style.transform = 'translate(' + Math.round(x) + 'px, ' + Math.round(-box.height / 2) + 'px) translateY(50%)'\n card.style.maxHeight = Math.round(box.height) + 'px'\n }\n place()\n window.addEventListener('resize', place)\n return () => { window.removeEventListener('resize', place) }\n // eslint-disable-next-line react-hooks/exhaustive-deps -- one placement per open/page change\n }, [open, page])\n\n // Drag gestures end any non-work mode (sleep wakes, a bath steps out); the\n // drag stream also feeds the idle director's suppression check.\n useEffect(() => {\n return props.drag.subscribe((dragging) => {\n draggingRef.current = dragging\n if (dragging) yieldRoam()\n if (dragging && modeRef.current !== null && modeRef.current !== 'work') {\n void api.setMode(null).then(applyResult, () => undefined)\n }\n })\n // eslint-disable-next-line react-hooks/exhaustive-deps -- one subscription per drag stream\n }, [props.drag])\n\n // Idle director: weighted rolls between staying idle and playing an act.\n // Rolls in every phase -- an ambient act is not a waiting-room performance,\n // and the idle phase only appears when neither the agent nor the user is busy\n // -- but only while nothing else owns the visual: no mode, no drag, no held\n // touch animation, no roam walk and no act already playing. maxMiss forces an\n // act after too many idle rolls in a row.\n useEffect(() => {\n const director = def?.idleDirector\n if (def === undefined || director === undefined) return undefined\n const total = director.idleWeight + director.acts.reduce((sum, act) => sum + act.weight, 0)\n if (total <= 0) return undefined\n let actTimer = 0\n const timer = window.setInterval(() => {\n if (modeRef.current !== null || draggingRef.current) return\n if (Date.now() < touchLockUntilRef.current) return\n if (roamHeldRef.current) return // a roam walk owns the visual\n if (actHeldRef.current) return // the previous act is still playing\n let pickedAct: { track: string; weight: number; phrases?: string[] } | undefined\n if (missRef.current >= director.maxMiss) {\n // Forced act: pick among the acts only.\n const actTotal = director.acts.reduce((sum, act) => sum + act.weight, 0)\n let actRoll = Math.random() * actTotal\n for (const act of director.acts) {\n actRoll -= act.weight\n if (actRoll < 0) { pickedAct = act; break }\n }\n } else {\n let roll = Math.random() * total\n for (const act of director.acts) {\n roll -= act.weight\n if (roll < 0) { pickedAct = act; break }\n }\n }\n if (pickedAct === undefined) {\n missRef.current += 1\n return\n }\n missRef.current = 0\n actHeldRef.current = true\n bus.setTrack?.(pickedAct.track)\n // A one-shot act owns the visual until its own duration elapses (the\n // renderer then falls back to the phase map); the roam must not cut in.\n const holdMs = definition.frames2d?.tracks[pickedAct.track]?.durations.reduce((sum, ms) => sum + ms, 0) ?? 0\n window.clearTimeout(actTimer)\n actTimer = window.setTimeout(() => { actHeldRef.current = false }, holdMs > 0 ? holdMs : 3000)\n // Acts with a phrase pool speak one line while they play (miku parity).\n if (pickedAct.phrases !== undefined && pickedAct.phrases.length > 0) {\n const phrase = pickedAct.phrases[Math.floor(Math.random() * pickedAct.phrases.length)]!\n store.actions.setFeedback({ text: phrase, kind: 'none', at: Date.now() })\n }\n }, director.intervalMs)\n return () => {\n window.clearInterval(timer)\n window.clearTimeout(actTimer)\n actHeldRef.current = false\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps -- one director per pet definition\n }, [definition.id, def])\n\n // Work loop: hold the work track, adjudicate one round per tick, play the\n // result track for its hold window, then resume. Leaving the mode\n // releases the override so the phase mapping takes over. A skin that\n // declares gameplayTracks for the work states plays its own art instead.\n useEffect(() => {\n const work = def?.work\n if (def === undefined || work === undefined || view?.mode !== 'work') return undefined\n const skinGameplay = definition.frames2d?.skins?.find(skin => skin.id === skinIdRef.current)?.gameplayTracks\n /** The state's track, swapped for the skin's override when it declares one. */\n const trackOf = (state: string): string => skinGameplay?.[state] ?? state\n bus.setTrack?.(trackOf(work.state))\n let resultTimer = 0\n const timer = window.setInterval(() => {\n if (busyRef.current) return\n busyRef.current = true\n void api.workTick().then((result) => {\n busyRef.current = false\n // Leaving work mode while the adjudication is in flight drops the late\n // result: writing it back would show work rewards and play the result\n // track for a mode the user has already left (#1495).\n if (modeRef.current !== 'work') return\n applyResult(result)\n if (result.ok !== true || result.outcome === undefined) return\n const resultTrack = trackOf(result.outcome === 'success' ? work.successState : work.failState)\n const hold = result.outcome === 'success' ? work.resultMs?.success ?? 1300 : work.resultMs?.fail ?? 1900\n bus.setTrack?.(resultTrack)\n resultTimer = window.setTimeout(() => {\n if (modeRef.current === 'work') bus.setTrack?.(trackOf(work.state))\n }, hold)\n }, () => { busyRef.current = false })\n }, work.tickMs)\n return () => {\n window.clearInterval(timer)\n window.clearTimeout(resultTimer)\n bus.setTrack?.(undefined)\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps -- the loop keys on the mode and the selected skin\n }, [definition.id, def, view?.mode, skinId])\n\n // Mode loop: hold the active non-work mode's track (sleep, a bath, any\n // extra 'modes' entry). The stat restore is host-side (lazy settle). While a\n // skin with a matching gameplayTracks override is selected, the skin's own\n // track replaces the default one (e.g. a skin-specific doze).\n useEffect(() => {\n const active = view?.mode\n if (def === undefined || active === undefined || active === null || active === 'work') return undefined\n const hold = modeStateOf(def, active)\n if (hold === undefined) return undefined\n const skinGameplay = definition.frames2d?.skins?.find(skin => skin.id === skinIdRef.current)?.gameplayTracks\n yieldRoam()\n bus.setTrack?.(skinGameplay?.[active] ?? hold)\n return () => bus.setTrack?.(undefined)\n // eslint-disable-next-line react-hooks/exhaustive-deps -- the loop keys on the mode value\n }, [definition.id, def, view?.mode, skinId])\n\n // Random roaming (manifest 'roam'): on a slow interval -- in any phase, as long\n // as no mode, drag, touch animation or director act owns the pet -- roll a\n // wander. The chrome walks the sprite and persists the new spot; this side\n // holds the walk track for exactly the travel time.\n useEffect(() => {\n const roam = def?.roam\n if (def === undefined || roam === undefined) return undefined\n const roll = (): void => {\n // Every phase: a wandering pet is ambient, not a performance, so she\n // keeps walking while the agent works (the idle director's acts stay\n // idle-only). A mode, a drag, a touch animation and a director\n // act all still own the pet and suppress the roll.\n if (modeRef.current !== null || draggingRef.current) return\n if (Date.now() < touchLockUntilRef.current) return\n if (roamHeldRef.current || actHeldRef.current) return\n if (Math.random() >= roam.probability) return\n const span = roam.distanceMax - roam.distanceMin\n const distance = roam.distanceMin + Math.random() * span\n const directions = roam.directions ?? PET_ROAM_DIRECTIONS\n const direction = directions[Math.floor(Math.random() * directions.length)] ?? 'left'\n const travelled = bus.walk?.(direction, distance, roam.speed) ?? 0\n if (travelled === 0) return\n roamHeldRef.current = true\n bus.setTrack?.(roam.state)\n roamTimerRef.current = window.setTimeout(() => {\n roamTimerRef.current = 0\n if (!roamHeldRef.current) return // another owner already took the slot\n roamHeldRef.current = false\n bus.setTrack?.(undefined)\n }, Math.max(150, (Math.abs(travelled) / roam.speed) * 1000))\n }\n // The two decision timers must never share a tick. The roam starts half an\n // interval late, so its ticks interleave with the idle director's instead\n // of landing on the same instant (10 s and 15 s coincide every 30 s).\n let timer = 0\n const lead = window.setTimeout(() => {\n roll()\n timer = window.setInterval(roll, roam.intervalMs)\n }, Math.round(roam.intervalMs / 2))\n return () => {\n window.clearTimeout(lead)\n window.clearInterval(timer)\n yieldRoam()\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps -- one director per pet definition\n }, [definition.id, def])\n\n if (def === undefined || view === undefined) return null\n\n const mode = view.mode\n const stats = def.stats ?? {}\n const shop = def.shop\n\n // Every menu mode beyond work: sleep plus any extra 'modes' the pet declares.\n const menuModes = declaredModes(def)\n\n /** Action-button label for one mode (active = the button that leaves it). */\n const modeLabel = (name: string, active: boolean): string => {\n if (name === 'sleep') return tr(active ? 'pet.gameplay.wake' : 'pet.gameplay.sleep')\n const declared = def.modes?.[name]\n return (active ? declared?.activeLabel ?? declared?.label : declared?.label) ?? tr('pet.gameplay.' + name)\n }\n\n /** Chip label for the mode the pet is in right now. */\n const modeChip = (name: string): string => {\n if (name === 'work') return tr('pet.gameplay.working')\n if (name === 'sleep') return tr('pet.gameplay.sleeping')\n const declared = def.modes?.[name]\n return declared?.activeLabel ?? declared?.label ?? tr('pet.gameplay.' + name)\n }\n\n const buy = (itemId: string): void => {\n void api.buy(itemId).then((result) => {\n applyResult(result)\n if (result.ok !== true) {\n if (result.error === 'insufficient-funds') {\n const item = shop?.items.find(entry => entry.id === itemId)\n pushFloat(tr('pet.gameplay.insufficient', { currency: currencyLabel(item?.currency ?? 'treats') }))\n }\n return\n }\n if (result.prize !== undefined) {\n pushFloat(tr('pet.gameplay.prize', { amount: result.prize.amount, currency: currencyLabel(result.prize.currency) }))\n }\n }, () => undefined)\n }\n\n const setMode = (next: string | null): void => {\n void api.setMode(next).then(applyResult, () => undefined)\n }\n\n // Skin selection is persisted host-side (per pet): re-seed the menu from\n // every fresh state view, so a page reload or client restart keeps the last\n // choice instead of snapping back to the default look.\n useEffect(() => {\n setSkinId(persistedSkin)\n }, [definition.id, persistedSkin])\n\n // Push the resolved base idle track into the renderer whenever the pet or\n // the selection changes. The value is latched on the bus first: the visual\n // may register later, or remount later (hidden/summoned), and reads the\n // latch back on activation so a restored skin never falls back to default.\n useEffect(() => {\n const skin = definition.frames2d?.skins?.find(candidate => candidate.id === skinId)\n bus.idleTrack = skin?.idleTrack\n bus.setIdleTrack?.(skin?.idleTrack)\n // persistedSkin rides the deps so the host's value also re-pushes on\n // arrival (a renderer that mounted early still converges).\n // eslint-disable-next-line react-hooks/exhaustive-deps -- one push per selection\n }, [definition.id, skinId, persistedSkin])\n\n const skins = definition.frames2d?.skins\n /** The base idle track one skin id resolves to (undefined = default look). */\n const skinTrackOf = (id: string | undefined): string | undefined =>\n id === undefined ? undefined : definition.frames2d?.skins?.find(candidate => candidate.id === id)?.idleTrack\n\n const selectSkin = (skin: PetSkinDefinition | undefined): void => {\n setSkinId(skin?.id)\n bus.setIdleTrack?.(skin?.idleTrack)\n // The host owns the choice: a refusal (unknown skin) restores both the\n // menu highlight and the renderer to the value it still serves.\n const restore = (): void => {\n setSkinId(persistedSkin)\n bus.setIdleTrack?.(skinTrackOf(persistedSkin))\n }\n void api.setSkin(skin?.id).then((result) => {\n if (result.ok) return\n restore()\n }, restore)\n }\n\n return (\n <div ref={hudRef} className={styles.gameplayHud} data-dsh-pet-gameplay={definition.id}>\n {floats.map(entry => (\n <div key={entry.id} className={styles.gameplayFloat}>{entry.text}</div>\n ))}\n {mode !== null && (\n <div className={styles.gameplayModeChip}>\n {modeChip(mode)}\n </div>\n )}\n {open && (\n <div ref={cardRef} className={styles.gameplayCard} data-page={page}>\n {page === 'root' && (\n <>\n <div className={styles.gameplayBars}>\n {Object.entries(stats).map(([name, stat]) => {\n const value = view.stats[name] ?? 0\n return (\n <div key={name} className={styles.gameplayBarRow} title={statLabel(name) + ' ' + String(value) + '/' + String(stat.max)}>\n <span className={styles.gameplayBarLabel}>{statLabel(name)}</span>\n <span className={styles.gameplayBarTrack}>\n <span\n className={styles.gameplayBarFill}\n style={{ width: Math.round((value / stat.max) * 100) + '%' }}\n />\n </span>\n </div>\n )\n })}\n </div>\n <div className={styles.gameplayActions}>\n {menuModes.map(name => (\n <button\n key={name}\n type=\"button\"\n className={styles.action}\n onClick={() => setMode(mode === name ? null : name)}\n >\n {modeLabel(name, mode === name)}\n </button>\n ))}\n {shop !== undefined && (\n <button type=\"button\" className={styles.action} onClick={() => setPage('shop')}>\n {tr('pet.gameplay.shop')}\n </button>\n )}\n {skins !== undefined && skins.length > 0 && (\n <button type=\"button\" className={styles.action} onClick={() => setPage('skins')}>\n {tr('pet.gameplay.skin')}\n </button>\n )}\n {def.work !== undefined && (\n <button\n type=\"button\"\n className={styles.action}\n onClick={() => setMode(mode === 'work' ? null : 'work')}\n >\n {tr(mode === 'work' ? 'pet.gameplay.stopWork' : 'pet.gameplay.work')}\n </button>\n )}\n </div>\n </>\n )}\n {page === 'shop' && shop !== undefined && (\n <>\n <div className={styles.gameplayShopItems}>\n {shop.items.map(item => (\n <button\n key={item.id}\n type=\"button\"\n className={styles.gameplayShopItem}\n onClick={() => buy(item.id)}\n title={item.label + ' — ' + String(item.price) + ' ' + currencyLabel(item.currency)}\n >\n {item.image !== undefined && (\n <img className={styles.gameplayShopItemImage} src={item.image} alt=\"\" draggable={false} />\n )}\n <span className={styles.gameplayShopItemLabel}>{item.label}</span>\n <span className={styles.gameplayShopItemPrice}>\n {item.price} {currencyLabel(item.currency)}\n </span>\n </button>\n ))}\n </div>\n <div className={styles.gameplayActions}>\n <button type=\"button\" className={styles.action} onClick={() => setPage('root')}>\n {tr('pet.gameplay.back')}\n </button>\n </div>\n </>\n )}\n {page === 'skins' && skins !== undefined && (\n <>\n <div className={styles.gameplaySkinItems}>\n <button\n type=\"button\"\n className={skinId === undefined ? styles.gameplaySkinItem + ' ' + styles.gameplaySkinItemActive : styles.gameplaySkinItem}\n onClick={() => selectSkin(undefined)}\n >\n {tr('pet.gameplay.skinDefault')}\n </button>\n {skins.map(skin => (\n <button\n key={skin.id}\n type=\"button\"\n className={skinId === skin.id ? styles.gameplaySkinItem + ' ' + styles.gameplaySkinItemActive : styles.gameplaySkinItem}\n onClick={() => selectSkin(skin)}\n >\n {skin.label}\n </button>\n ))}\n </div>\n <div className={styles.gameplayActions}>\n <button type=\"button\" className={styles.action} onClick={() => setPage('root')}>\n {tr('pet.gameplay.back')}\n </button>\n </div>\n </>\n )}\n <button\n type=\"button\"\n className={styles.gameplayClose}\n aria-label={tr('pet.gameplay.back')}\n onClick={() => setOpen(false)}\n >\n ×\n </button>\n </div>\n )}\n </div>\n )\n}\n","/**\n * Global floating pet entry. The pet is host-global (its state, display and\n * interactions live on '/api/pet/*' endpoints with no session dimension), so\n * it must not ride a session-scoped slot — on the new-conversation screen no\n * session exists to scope a slot by, and the pet would vanish (issue #48).\n * The client half therefore mounts this entry straight onto 'document.body'\n * (see index.ts): while visible it renders the floating PetSprite (a portal\n * into the plugin root, so the root owns the whole surface), while hidden it\n * renders a fixed-position summon button. Which sprite renders is decided by\n * the host snapshot's pet id resolved against the registry list — no per-pet\n * component exists.\n * @module @linxin666/dsh-pet/client/PetDockEntry\n */\n\nimport { useEffect, useRef, useSyncExternalStore, type ReactElement } from 'react'\nimport type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { PetDisplayConfig } from '../persist.ts'\nimport type { PetStoreInstance } from './pet-store.ts'\nimport { PetSprite } from './PetSprite.tsx'\nimport { PetRendererSwitch } from './renderers/PetRendererSwitch.tsx'\nimport { createDragStream, type DragStream } from './drag-stream.ts'\nimport { GameplayHud, type GameplayApi, type GameplayBus } from './gameplay-hud.tsx'\nimport { NS } from './locales.ts'\nimport styles from './pet.module.css'\n\n/** Injected actions handed to the dock entry component. */\nexport interface PetInjected {\n /** The app-wide pet store instance (snapshot + registry list + feedback). */\n store: PetStoreInstance\n /** Ensure the first snapshot (and registry list) is fetched (called on mount). */\n ensure: () => void\n /** Pet the sprite (click). */\n pet: () => void\n /** Feed the sprite. */\n feed: () => void\n /** Hide the sprite. */\n hide: () => void\n /** Summon the hidden sprite back. */\n summon: () => void\n /** Persist a drag position. */\n dragEnd: (right: number, bottom: number) => void\n /** Rename the selected pet (persisted by the host). */\n rename: (name: string) => void\n /**\n * Report a click on one plugin-registered panel action (issue #6). The host\n * dispatches it to the plugin that registered the action; the panel itself\n * only renders the button the state snapshot served.\n */\n panelAction: (id: string) => void\n /** Navigate the GUI to the session a bubble reports on. */\n openSession: (sessionId: string) => void\n /** Clear the reaction bubble. */\n feedbackDone: () => void\n /** Gameplay verb API (miku-pet generalization); wired but unused for pets without a gameplay block. */\n gameplay: GameplayApi\n}\n\n/** Composed props of the global pet entry (locale + injected; no slot runtime share). */\nexport type PetDockEntryProps =\n PetInjected\n & PropsLocale<typeof NS>\n & {\n /**\n * DOM node the floating sprite chrome portals into. Defaults to\n * document.body; the plugin apply passes its [data-dsh-plugin=\"pet\"]\n * root so root-keyed suppressors (the portrait mobile layer) and skins\n * own the whole pet surface as one unit.\n */\n portalTarget?: Element\n /**\n * Active UI locale id, forwarded to the sprite so a pet-declared English\n * rank name (`rankEn`) applies when the UI language is English.\n */\n lang?: string\n }\n\nconst DEFAULT_DISPLAY: PetDisplayConfig = { visible: true, size: 160, right: 24, bottom: 20, bubbleScale: 1 }\n\n/**\n * Dock entry: while the pet is visible, mount the floating PetSprite (it\n * portals itself onto document.body); while hidden, render the summon\n * button so the pet can always come back. The store is the plugin-owned\n * single instance — the slot system provides none because the pet is\n * host-global, not session-scoped.\n */\nexport function PetDockEntry(props: PetDockEntryProps): ReactElement {\n const { store, ensure } = props\n const ui = useSyncExternalStore(store.subscribe, store.getSnapshot)\n const snapshot = ui.snapshot\n const feedback = ui.feedback\n const definition = ui.pets.find(entry => entry.id === snapshot?.pet.id) ?? null\n const visible = snapshot?.display.visible ?? true\n\n useEffect(() => {\n ensure()\n }, [ensure])\n\n // Per-pet gameplay wiring: the coordination bus (HUD taps <-> chrome,\n // HUD track overrides <-> frames2d mount) and the shared drag stream.\n const auxRef = useRef<{ id: string; bus: GameplayBus; drag: DragStream } | null>(null)\n if (definition !== null && (auxRef.current === null || auxRef.current.id !== definition.id)) {\n auxRef.current = { id: definition.id, bus: {}, drag: createDragStream() }\n }\n const aux = auxRef.current\n const gameplay = definition?.gameplay\n\n if (visible) {\n return (\n <span data-pet-dock data-testid=\"pet-dock\">\n {snapshot === null || definition === null\n ? null\n : (\n <PetRendererSwitch\n definition={definition}\n phase={snapshot?.phase ?? 'idle'}\n onPet={props.pet}\n {...(aux === null ? {} : { drag: aux.drag, bus: aux.bus })}\n t={props.t}\n >\n <PetSprite\n snapshot={snapshot}\n definition={definition}\n display={snapshot.display}\n feedback={feedback}\n onPet={props.pet}\n onFeed={props.feed}\n onHide={props.hide}\n onDragEnd={props.dragEnd}\n onRename={props.rename}\n onPanelAction={props.panelAction}\n onOpenSession={props.openSession}\n onFeedbackDone={props.feedbackDone}\n portalTarget={props.portalTarget}\n dragDisabled={snapshot.gameplay?.mode === 'work'}\n {...(aux === null ? {} : { bus: aux.bus })}\n lang={props.lang}\n {...(gameplay === undefined || aux === null\n ? {}\n : {\n onGameplayTap: (fx: number, fy: number) => aux.bus.tap?.(fx, fy),\n onGameplayMenu: () => aux.bus.openCard?.(),\n hud: (\n <GameplayHud\n definition={definition}\n store={store}\n api={props.gameplay}\n bus={aux.bus}\n drag={aux.drag}\n t={props.t}\n />\n ),\n })}\n t={props.t}\n />\n </PetRendererSwitch>\n )}\n </span>\n )\n }\n const display = snapshot?.display ?? DEFAULT_DISPLAY\n return (\n <button\n type=\"button\"\n className={styles.summon}\n style={{\n position: 'fixed',\n right: display.right,\n bottom: display.bottom,\n zIndex: 2147483000,\n }}\n onClick={props.summon}\n data-testid=\"pet-summon\"\n data-dsh-part=\"summon-button\"\n >\n {props.t('pet.summon', { name: snapshot?.name ?? '' })}\n </button>\n )\n}\n","/**\n * Renderer contract — the seam between the pet center and its renderers\n * (issue #623, milestone M2 P4). Renderers never see the DSH session, the\n * registry, or the network: they receive exactly three capabilities — an\n * asset base URL, the ActivityPhase stream, and the interaction write-back —\n * inside a center-owned container. Every mount is a fresh activation whose\n * cleanups must be idempotent.\n *\n * This contract only serves real consumers: sprite2d (existing) and live2d\n * (M3). Speculative capabilities join only when a renderer actually needs\n * them.\n * @module @linxin666/dsh-pet/contracts/renderer\n */\n\nimport type { ActivityPhase } from '../state.ts'\n\n/** Contract version renderers declare against (independent of the manifest). */\nexport const PET_RENDERER_API_VERSION = 'x-org.linxin666.pet-center/v1alpha1'\n\n/** What the pet center hands a renderer on mount. */\nexport interface PetRendererContext {\n /** The selected pet's id. */\n readonly petId: string\n /** Same-origin URL prefix of this pet's assets ('/pet/<id>'). */\n readonly assetBase: string\n /** Center-owned mount root; renderers must not attach to document.body. */\n readonly container: HTMLElement\n /** The ActivityPhase stream (pet-center owned; renderers subscribe). */\n readonly phase: {\n get(): ActivityPhase\n subscribe(listener: (phase: ActivityPhase) => void): () => void\n }\n /** The single interaction write-back into the affinity economy. */\n readonly interact: (kind: 'tap') => void\n /** Register an activation-scoped cleanup; run on dispose, idempotently. */\n onCleanup(fn: () => void): void\n}\n\n/** A mounted renderer activation. */\nexport interface PetRendererHandle {\n /** Tear the activation down; may be called 0/1/N times. */\n dispose(): void\n}\n\n/**\n * One renderer implementation. validateConfig is fail-closed over the\n * renderer-specific manifest block (schema v2 'sprite2d'/'live2d' blocks).\n */\nexport interface PetRenderer<Config = unknown> {\n readonly id: string\n readonly apiVersion: string\n validateConfig(config: unknown): Config\n mount(ctx: PetRendererContext, config: Config): PetRendererHandle\n}\n","/**\n * Live2D runtime loading (pet-center M3) — the two scripts a live2d mount\n * needs, fetched lazily through the plugin's own runtime route: the\n * user-supplied Cubism Core (proprietary; the plugin never bundles or\n * downloads it — issue #623 M1 §0) and the plugin-shipped MIT vendor bundle\n * (pixi.js + untitled-pixi-live2d-engine). Each loads at most once per page;\n * concurrent mounts share the in-flight promise, and a failure is cached as\n * 'absent' so a broken install stops retrying the network every mount.\n *\n * The vendor surface below is the structural slice the renderer consumes;\n * the real objects come from 'window.__dshPetLive2d' (lib/live2d-vendor.js),\n * so this module never imports pixi — the client bundle stays lean.\n * @module @linxin666/dsh-pet/client/renderers/live2d/runtime\n */\n\n/** Runtime file URLs the host serves ('/api/pet/runtime/<name>', M3-2). */\nconst CORE_URL = '/api/pet/runtime/live2dcubismcore.min.js'\nconst VENDOR_URL = '/api/pet/runtime/live2d-vendor.js'\n\n/** The pixi Application slice the renderer uses. */\nexport interface Live2dVendorApp {\n canvas: HTMLCanvasElement\n stage: { addChild(child: unknown): unknown }\n renderer: {\n readonly width: number\n readonly height: number\n resize(width: number, height: number): void\n }\n init(options: Record<string, unknown>): Promise<void>\n destroy(rendererOptions?: boolean | { removeView?: boolean; releaseGlobalResources?: boolean }, options?: Record<string, unknown>): void\n}\n\n/** The Live2DModel slice the renderer uses. */\nexport interface Live2dVendorModel {\n automator: { autoUpdate: boolean }\n anchor: { set(x: number, y?: number): void }\n position: { set(x: number, y: number): void }\n scale: { set(x: number, y?: number): void }\n readonly width: number\n readonly height: number\n internalModel: {\n settings: {\n motions?: Record<string, unknown[]>\n hitAreas?: readonly { Name?: string }[]\n }\n }\n motion(group: string, index?: number): Promise<unknown>\n expression(name?: string): unknown\n hitTest(x: number, y: number): string[]\n on(event: string, fn: () => void): unknown\n destroy(options?: { children?: boolean; texture?: boolean; baseTexture?: boolean }): void\n}\n\n/** The vendor bundle global (window.__dshPetLive2d). */\nexport interface Live2dVendor {\n Application: new () => Live2dVendorApp\n extensions: { add(...items: unknown[]): void }\n Live2DPlugin: unknown\n configureCubismSDK(options: Record<string, unknown>): void\n Live2DModel: { from(source: string, options?: Record<string, unknown>): Promise<Live2dVendorModel> }\n}\n\ndeclare global {\n interface Window {\n Live2DCubismCore?: unknown\n __dshPetLive2d?: Live2dVendor\n }\n}\n\n/** Injects one classic script tag; resolves on load, rejects on error. */\ntype ScriptInjector = (src: string) => Promise<void>\n\nconst defaultInjector: ScriptInjector = (src) => new Promise<void>((resolve, reject) => {\n const tag = document.createElement('script')\n tag.src = src\n tag.onload = () => resolve()\n tag.onerror = () => reject(new Error('script failed to load: ' + src))\n document.head.appendChild(tag)\n})\n\n/** Test seam: swap the network for a stub injector. */\nexport interface Live2dRuntimeProbe {\n inject?: ScriptInjector\n}\n\nlet corePromise: Promise<boolean> | undefined\nlet vendorPromise: Promise<Live2dVendor | undefined> | undefined\n\n/**\n * Ensure the Cubism Core global exists, injecting the runtime-route script\n * once when absent. Resolves false when the user has not installed the core\n * (a normal state — the renderer turns it into install guidance).\n */\nexport function ensureCubismCore(probe: Live2dRuntimeProbe = {}): Promise<boolean> {\n if (typeof window !== 'undefined' && window.Live2DCubismCore !== undefined) return Promise.resolve(true)\n if (probe.inject !== undefined) {\n return probe.inject(CORE_URL)\n .then(() => typeof window !== 'undefined' && window.Live2DCubismCore !== undefined)\n .catch(() => false)\n }\n corePromise ??= defaultInjector(CORE_URL)\n .then(() => typeof window !== 'undefined' && window.Live2DCubismCore !== undefined)\n .catch(() => false)\n return corePromise\n}\n\n/** Ensure the plugin vendor bundle global exists (same caching discipline). */\nexport function ensureLive2dVendor(probe: Live2dRuntimeProbe = {}): Promise<Live2dVendor | undefined> {\n if (typeof window !== 'undefined' && window.__dshPetLive2d !== undefined) return Promise.resolve(window.__dshPetLive2d)\n if (probe.inject !== undefined) {\n return probe.inject(VENDOR_URL)\n .then(() => typeof window !== 'undefined' ? window.__dshPetLive2d : undefined)\n .catch(() => undefined)\n }\n vendorPromise ??= defaultInjector(VENDOR_URL)\n .then(() => typeof window !== 'undefined' ? window.__dshPetLive2d : undefined)\n .catch(() => undefined)\n return vendorPromise\n}\n\n/** Reset the cached script promises (tests). */\nexport function resetLive2dRuntime(): void {\n corePromise = undefined\n vendorPromise = undefined\n}\n","/**\n * Live2D renderer (pet-center M3, issue #623) — mounts a Cubism model into\n * the center-owned container through the lazy vendor stack. The mount call\n * itself is synchronous per the renderer contract: the boot (core script →\n * vendor script → pixi → model) continues asynchronously and reports fatal\n * failures through the handle's error sink, so the React bridge can render\n * localized guidance. Disposing mid-boot is race-safe.\n *\n * Interaction model: the center chrome owns the affinity economy (its click\n * handler fires the pet interaction exactly like sprite2d); this renderer's\n * 'tap' affordance only drives the model's hit-area motion feedback. The\n * contract's interact write-back stays available for future standalone\n * mounts and is intentionally not invoked here.\n *\n * Motion mapping: manifests map ActivityPhases to motion GROUP names; every\n * unmapped phase (and any mapped-but-absent group) falls back to the idle\n * group — official sample models only ship Idle/TapBody, so the fallback is\n * mandatory. Groups with multiple motions pick a random entry, and a tap\n * that hits a declared hit area plays the conventional 'TapBody' group,\n * returning to the phase's group when the tap motion finishes.\n * @module @linxin666/dsh-pet/client/renderers/live2d\n */\n\nimport type { ActivityPhase } from '../../state.ts'\nimport {\n PET_RENDERER_API_VERSION,\n type PetRenderer,\n type PetRendererContext,\n type PetRendererHandle,\n} from '../../contracts/renderer.ts'\nimport {\n ensureCubismCore,\n ensureLive2dVendor,\n type Live2dVendor,\n type Live2dVendorApp,\n type Live2dVendorModel,\n} from './live2d/runtime.ts'\n\n/** Renderer config: the client-visible live2d block (fail-closed validated). */\nexport interface PetLive2dConfig {\n modelUrl: string\n scale?: number\n translate?: { x?: number; y?: number }\n motions: Partial<Record<ActivityPhase, string>> & { idle: string }\n expressions?: Partial<Record<ActivityPhase, string>>\n hitAreas?: string[]\n}\n\n/** Fatal mount failure codes the bridge localizes. */\nexport type Live2dErrorCode = 'core-missing' | 'vendor-missing' | 'load-failed'\n\n/** The live2d activation handle: contract dispose plus tap + error sink. */\nexport interface Live2dRendererHandle extends PetRendererHandle {\n /** Forward a chrome tap in container coordinates; plays the hit motion. */\n tap(x: number, y: number): void\n /** Subscribe to fatal mount errors (at most one fires per activation). */\n onError(listener: (code: Live2dErrorCode) => void): void\n}\n\n/** The de-facto tap-motion group of Cubism sample models. */\nconst TAP_GROUP = 'TapBody'\n\n/**\n * Keep one screen-appropriate atlas LOD instead of asking Pixi for the\n * engine's default full mip chain. A user model can legitimately carry an\n * 8192px texture while the pet itself is only a few hundred pixels tall;\n * `single-auto` preserves the source for larger renders and generates one\n * downsampled atlas only when the effective on-screen scale warrants it.\n */\nconst TEXTURE_OPTIONS = { lod: 'single-auto' } as const\n/** Recursively release the activation without invalidating shared texture caches. */\nconst DESTROY_OPTIONS = { children: true } as const\n/** Remove only this activation's canvas; `true` would release Pixi globals. */\nconst RENDERER_DESTROY_OPTIONS = { removeView: true } as const\n\ninterface Live2dModelSize {\n width: number\n height: number\n}\n\n/** Ignore hidden/zero boxes and keep Pixi dimensions stable and integral. */\nfunction normalizeRendererSize(width: number, height: number): Live2dModelSize | undefined {\n if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) return undefined\n return {\n width: Math.max(1, Math.round(width)),\n height: Math.max(1, Math.round(height)),\n }\n}\n\n/** Fit the model from its unscaled dimensions into the current Pixi screen. */\nfunction layoutModel(\n app: Live2dVendorApp,\n model: Live2dVendorModel,\n sourceSize: Live2dModelSize,\n config: PetLive2dConfig,\n): void {\n const fit = Math.min(\n app.renderer.width / sourceSize.width,\n app.renderer.height / sourceSize.height,\n ) * 0.92\n model.scale.set(fit * (config.scale ?? 1))\n model.anchor.set(0.5)\n model.position.set(\n app.renderer.width / 2 + (config.translate?.x ?? 0),\n app.renderer.height / 2 + (config.translate?.y ?? 0),\n )\n}\n\nlet vendorConfigured = false\n\n/** Configure pixi extensions + the Cubism SDK once per page. */\nfunction configureOnce(vendor: Live2dVendor): void {\n if (vendorConfigured) return\n vendorConfigured = true\n vendor.extensions.add(vendor.Live2DPlugin)\n vendor.configureCubismSDK({ memorySizeMB: 32 })\n}\n\n/** Reset module state (tests). */\nexport function resetLive2dRenderer(): void {\n vendorConfigured = false\n}\n\n/** Fail-closed config validation (contract: unknown manifest block in). */\nfunction validateLive2dConfig(config: unknown): PetLive2dConfig {\n if (typeof config !== 'object' || config === null) throw new Error('live2d config is not an object')\n const source = config as Record<string, unknown>\n if (typeof source.modelUrl !== 'string' || source.modelUrl === '') throw new Error('live2d config modelUrl is required')\n const motions = source.motions\n if (typeof motions !== 'object' || motions === null || typeof (motions as Record<string, unknown>).idle !== 'string') {\n throw new Error('live2d config motions.idle is required')\n }\n return config as PetLive2dConfig\n}\n\n/** The live2d renderer implementation. */\nexport const live2dRenderer: PetRenderer<PetLive2dConfig> = {\n id: 'live2d',\n apiVersion: PET_RENDERER_API_VERSION,\n validateConfig: validateLive2dConfig,\n mount(ctx: PetRendererContext, config: PetLive2dConfig): Live2dRendererHandle {\n let disposed = false\n let app: Live2dVendorApp | undefined\n let model: Live2dVendorModel | undefined\n let modelAttached = false\n let modelSourceSize: Live2dModelSize | undefined\n let resizeObserver: ResizeObserver | undefined\n let resizeTracking = false\n let errorListener: ((code: Live2dErrorCode) => void) | undefined\n let unsubscribe: (() => void) | undefined\n /** The motion group the current phase maps to (resume target after taps). */\n let phaseGroup: string = config.motions.idle\n let tapPlaying = false\n\n const stopResizeTracking = (): void => {\n resizeTracking = false\n resizeObserver?.disconnect()\n resizeObserver = undefined\n }\n\n const resizeRenderer = (pixiApp: Live2dVendorApp, width: number, height: number): void => {\n const next = normalizeRendererSize(width, height)\n if (disposed || !resizeTracking || next === undefined) return\n if (pixiApp.renderer.width === next.width && pixiApp.renderer.height === next.height) return\n pixiApp.renderer.resize(next.width, next.height)\n if (model !== undefined && modelSourceSize !== undefined) {\n layoutModel(pixiApp, model, modelSourceSize, config)\n }\n }\n\n const trackContainerSize = (pixiApp: Live2dVendorApp): void => {\n if (typeof ResizeObserver === 'undefined') return\n resizeTracking = true\n resizeObserver = new ResizeObserver((entries) => {\n const entry = entries.find(candidate => candidate.target === ctx.container)\n if (entry === undefined) return\n resizeRenderer(pixiApp, entry.contentRect.width, entry.contentRect.height)\n })\n resizeObserver.observe(ctx.container)\n // Catch a synchronous layout change between init() and observe().\n resizeRenderer(pixiApp, ctx.container.clientWidth, ctx.container.clientHeight)\n }\n\n /** Release every resource currently owned by this activation exactly once. */\n const destroyResources = (): void => {\n stopResizeTracking()\n unsubscribe?.()\n unsubscribe = undefined\n const currentApp = app\n const currentModel = model\n const modelOwnedByApp = currentApp !== undefined && modelAttached\n app = undefined\n model = undefined\n modelSourceSize = undefined\n modelAttached = false\n try {\n if (currentModel !== undefined && !modelOwnedByApp) currentModel.destroy(DESTROY_OPTIONS)\n } finally {\n currentApp?.destroy(RENDERER_DESTROY_OPTIONS, DESTROY_OPTIONS)\n }\n }\n\n const playGroup = (group: string): void => {\n if (model === undefined) return\n const groups = model.internalModel.settings.motions ?? {}\n const count = Array.isArray(groups[group]) ? groups[group]!.length : 0\n if (count === 0) {\n // A mapped-but-absent group falls back to idle (never blank motion).\n if (group !== config.motions.idle) playGroup(config.motions.idle)\n return\n }\n const index = count > 1 ? Math.floor(Math.random() * count) : 0\n void model.motion(group, index)\n }\n\n const applyPhase = (phase: ActivityPhase): void => {\n phaseGroup = config.motions[phase] ?? config.motions.idle\n playGroup(phaseGroup)\n const expression = config.expressions?.[phase]\n if (expression !== undefined && model !== undefined) void model.expression(expression)\n }\n\n const boot = async (): Promise<void> => {\n if (!await ensureCubismCore()) {\n if (!disposed) errorListener?.('core-missing')\n return\n }\n const vendor = await ensureLive2dVendor()\n if (vendor === undefined) {\n if (!disposed) errorListener?.('vendor-missing')\n return\n }\n configureOnce(vendor)\n const pixiApp = new vendor.Application()\n const initialSize = normalizeRendererSize(ctx.container.clientWidth, ctx.container.clientHeight) ?? {\n width: 160,\n height: 174,\n }\n try {\n await pixiApp.init({\n width: initialSize.width,\n height: initialSize.height,\n backgroundAlpha: 0,\n antialias: true,\n autoDensity: true,\n preference: 'webgl',\n })\n } catch (error) {\n // init() can fail after allocating a partial renderer; cleanup is\n // best-effort because Pixi may not consider that partial app ready.\n try { pixiApp.destroy(RENDERER_DESTROY_OPTIONS, DESTROY_OPTIONS) } catch {}\n throw error\n }\n if (disposed) {\n pixiApp.destroy(RENDERER_DESTROY_OPTIONS, DESTROY_OPTIONS)\n return\n }\n app = pixiApp\n pixiApp.canvas.style.display = 'block'\n pixiApp.canvas.style.width = '100%'\n pixiApp.canvas.style.height = '100%'\n ctx.container.appendChild(pixiApp.canvas)\n // Keep a model that rejects during setup off Ticker.shared; from()\n // does not expose that partial instance to callers for disposal.\n trackContainerSize(pixiApp)\n const loaded = await vendor.Live2DModel.from(config.modelUrl, {\n autoUpdate: false,\n autoHitTest: false,\n autoFocus: false,\n textureOptions: TEXTURE_OPTIONS,\n })\n model = loaded\n if (disposed) {\n destroyResources()\n return\n }\n modelSourceSize = {\n width: Math.max(1, loaded.width),\n height: Math.max(1, loaded.height),\n }\n // Auto-fit the model into the container; the manifest scale multiplies\n // the fit and translate offsets from the center anchor.\n layoutModel(pixiApp, loaded, modelSourceSize, config)\n pixiApp.stage.addChild(loaded)\n modelAttached = true\n loaded.automator.autoUpdate = true\n // Resume the phase group once a tap motion finishes playing.\n loaded.on('motionFinish', () => {\n if (tapPlaying) {\n tapPlaying = false\n playGroup(phaseGroup)\n }\n })\n applyPhase(ctx.phase.get())\n unsubscribe = ctx.phase.subscribe(applyPhase)\n }\n\n void boot().catch(() => {\n try {\n destroyResources()\n } finally {\n if (!disposed) errorListener?.('load-failed')\n }\n })\n\n return {\n dispose() {\n if (disposed) return\n disposed = true\n destroyResources()\n },\n tap(x: number, y: number) {\n const current = model\n if (disposed || current === undefined) return\n const hits = current.hitTest(x, y)\n const allowed = config.hitAreas\n const hit = allowed === undefined ? hits.length > 0 : hits.some(name => allowed.includes(name))\n if (!hit) return\n const groups = current.internalModel.settings.motions ?? {}\n const group = groups[TAP_GROUP]\n if (!Array.isArray(group) || group.length === 0) return\n tapPlaying = true\n const index = group.length > 1 ? Math.floor(Math.random() * group.length) : 0\n void current.motion(TAP_GROUP, index)\n },\n onError(listener: (code: Live2dErrorCode) => void) {\n errorListener = listener\n },\n }\n },\n}\n","/**\n * frames2d renderer — plays the free-form named frame-sequence tracks of a\n * frames2d pet (manifest v2 'frames2d' block). The pet center picks the\n * track from the ActivityPhase stream (phase -> track map, idle fallback);\n * the gameplay driver may force a track through the handle's setState\n * override (drag/work/sleep/shop...), and a finished non-loop track settles\n * into its fallback, releasing the override when the fallback matches the\n * phase-mapped track. Rendering never throws: a broken track list degrades\n * to the first decodable frame, and the 1.2 s stall watchdog re-kicks the\n * playback chain after timer throttling.\n *\n * Frame presentation has two modes picked once at mount by capability\n * probing:\n * - Canvas bitmap buffer (default where createImageBitmap/fetch/2D context\n * exist): frames are decoded once into an ImageBitmap on demand, with a\n * bounded look-ahead window over the playing track, and drawn onto one\n * <canvas>. Steady-state playback issues zero DOM mutations and re-decodes\n * only what the retention budget evicted: decoded frames are held under\n * MAX_RETAINED_BYTES, so a long-lived pet that plays every track of every\n * skin cannot pin every bitmap for the life of the page (measured hotspot:\n * swapping <img>.src per frame drove image decode + invalidation every tick).\n * - Classic <img> fallback (jsdom/tests or missing APIs): identical to the\n * historical behavior - cache-warm Image elements plus guarded src swaps,\n * so environments without modern decoding keep working unchanged.\n *\n * @module @linxin666/dsh-pet/client/renderers/frames2d\n */\n\nimport { PET_RENDERER_API_VERSION, type PetRenderer, type PetRendererContext, type PetRendererHandle } from '../../contracts/renderer.ts'\nimport type { ActivityPhase } from '../../state.ts'\n\n/** One track as served inside the pet definition (browser URLs). */\nexport interface Frames2dTrackConfig {\n frames: string[]\n durations: number[]\n loop: boolean\n fallback?: string\n}\n\n/** The frames2d block as served inside the pet definition. */\nexport interface PetFrames2dConfig {\n tracks: Record<string, Frames2dTrackConfig>\n phases: Partial<Record<ActivityPhase, string>> & { idle: string }\n /** Selectable skins; each swaps the base idle target while selected. */\n skins?: Frames2dSkinConfig[]\n}\n\n/** One selectable skins entry as served inside the pet definition. */\nexport interface Frames2dSkinConfig {\n id: string\n label: string\n /** A declared looping track that becomes the base idle while selected. */\n idleTrack: string\n /** Click actions exclusive to this skin (roll by probability; miss → touch zones). */\n clickActions?: Frames2dSkinClickActionConfig[]\n /** Gameplay-state overrides (state -> track) swapped in while selected. */\n gameplayTracks?: Record<string, string>\n}\n\n/** One probability-rolled tap action a skin may declare. */\nexport interface Frames2dSkinClickActionConfig {\n track: string\n probability: number\n phrases?: string[]\n}\n\nexport interface Frames2dRendererHandle extends PetRendererHandle {\n /** Force a track id (gameplay override); undefined returns to phase mapping. */\n setState(track: string | undefined): void\n /**\n * Swap the base idle target (idle phase, unmapped phases and every\n * fallback back to idle) to a declared looping track — a skin. undefined\n * restores the manifest idle track.\n */\n setIdleTrack(track: string | undefined): void\n /** The track currently playing (diagnostics and tests). */\n currentTrack(): string\n}\n\n/** Stall watchdog period: a looping track stuck longer re-kicks its chain. */\nconst WATCHDOG_MS = 1200\n\n/**\n * Retention budget for decoded frame bitmaps, in bytes.\n *\n * The budget is expressed in bytes rather than in frames because a frame's\n * decoded footprint is `width * height * 4` and published pets differ by more\n * than an order of magnitude (a 512x683 frame is 1.33 MB, a 128x128 frame is\n * 64 KB): a frame count would be either useless for small atlases or too tight\n * for large ones. 128 MiB holds this repository's longest shipped track (78\n * frames, 104 MB) in full, so a running loop still re-decodes nothing, while\n * capping a pet that played every track of every skin at roughly a tenth of\n * the ~1.7 GB the unbounded memo reached.\n */\nconst MAX_RETAINED_BYTES = 128 * 1024 * 1024\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** Fail-closed client-side validation of the served frames2d block. */\nfunction validateFrames2dConfig(config: unknown): PetFrames2dConfig {\n if (!isRecord(config) || !isRecord(config.tracks) || !isRecord(config.phases)) {\n throw new Error('frames2d config requires tracks and phases objects')\n }\n const tracks: Record<string, Frames2dTrackConfig> = {}\n for (const [name, raw] of Object.entries(config.tracks)) {\n if (!isRecord(raw) || !Array.isArray(raw.frames) || raw.frames.length === 0\n || raw.frames.some(f => typeof f !== 'string' || f === '')\n || !Array.isArray(raw.durations) || raw.durations.length !== raw.frames.length\n || raw.durations.some(d => typeof d !== 'number' || !(d > 0))) {\n throw new Error('frames2d track ' + JSON.stringify(name) + ' needs same-length frames/durations')\n }\n tracks[name] = {\n frames: raw.frames as string[],\n durations: raw.durations as number[],\n loop: raw.loop !== false,\n ...(typeof raw.fallback === 'string' ? { fallback: raw.fallback } : {}),\n }\n }\n const phases = config.phases as Partial<Record<ActivityPhase, string>>\n if (typeof phases.idle !== 'string' || tracks[phases.idle] === undefined) {\n throw new Error('frames2d phases.idle must name an existing track')\n }\n // Skins: keep entries whose idleTrack survives validation and loops —\n // a non-looping base idle would settle into itself forever. Click actions\n // with an unresolvable track are dropped from that skin.\n let skins: Frames2dSkinConfig[] | undefined\n if (Array.isArray(config.skins)) {\n const resolved: Frames2dSkinConfig[] = []\n for (const skin of config.skins as unknown[]) {\n if (!isRecord(skin) || typeof skin.id !== 'string' || typeof skin.label !== 'string'\n || typeof skin.idleTrack !== 'string' || skin.idleTrack === '') continue\n const target = tracks[skin.idleTrack]\n if (target === undefined || !target.loop) continue\n let clickActions: Frames2dSkinClickActionConfig[] | undefined\n if (Array.isArray(skin.clickActions)) {\n const kept: Frames2dSkinClickActionConfig[] = []\n for (const action of skin.clickActions as unknown[]) {\n if (!isRecord(action) || typeof action.track !== 'string' || action.track === ''\n || typeof action.probability !== 'number' || !(action.probability > 0) || action.probability > 1) continue\n if (tracks[action.track] === undefined) continue\n kept.push({\n track: action.track,\n probability: action.probability,\n ...(Array.isArray(action.phrases) ? { phrases: action.phrases as string[] } : {}),\n })\n }\n if (kept.length > 0) clickActions = kept\n }\n let gameplayTracks: Record<string, string> | undefined\n if (isRecord(skin.gameplayTracks)) {\n const kept: Record<string, string> = {}\n for (const [state, trackName] of Object.entries(skin.gameplayTracks)) {\n if (typeof trackName !== 'string' || trackName === '' || tracks[trackName] === undefined) continue\n kept[state] = trackName\n }\n if (Object.keys(kept).length > 0) gameplayTracks = kept\n }\n resolved.push({\n id: skin.id,\n label: skin.label,\n idleTrack: skin.idleTrack,\n ...(clickActions === undefined ? {} : { clickActions }),\n ...(gameplayTracks === undefined ? {} : { gameplayTracks }),\n })\n }\n if (resolved.length > 0) skins = resolved\n }\n return { tracks, phases: phases as PetFrames2dConfig['phases'], ...(skins === undefined ? {} : { skins }) }\n}\n\ninterface DecodedFrame {\n source: ImageBitmap | HTMLImageElement\n width: number\n height: number\n}\n\n/**\n * One memoized decode job. `frame` and `bytes` appear only once the job\n * resolved with a frame — exactly the set the retention budget may release;\n * pending and failed jobs carry neither. The owning map's insertion order is\n * the LRU order (re-inserting an entry marks it most recently used).\n */\ninterface DecodeEntry {\n job: Promise<DecodedFrame | undefined>\n frame?: DecodedFrame\n bytes?: number\n}\n\n/**\n * Release one decoded frame. `close()` is browser-only and idempotent, so the\n * call is guarded for exotic hosts and for frames that were already released;\n * the `<img>` fallback has no close, where dropping the reference is the\n * release.\n */\nfunction releaseFrame(frame: DecodedFrame | undefined): void {\n if (frame === undefined) return\n try {\n const maybeClose = (frame.source as { close?: () => void }).close\n if (typeof maybeClose === 'function') maybeClose.call(frame.source)\n } catch { /* already released */ }\n}\n\nexport const frames2dRenderer: PetRenderer<PetFrames2dConfig> = {\n id: 'frames2d',\n apiVersion: PET_RENDERER_API_VERSION,\n validateConfig: validateFrames2dConfig,\n\n mount(ctx: PetRendererContext, config: PetFrames2dConfig): Frames2dRendererHandle {\n const reducedMotion = typeof window !== 'undefined'\n && typeof window.matchMedia === 'function'\n && window.matchMedia('(prefers-reduced-motion: reduce)').matches\n\n // Capability probe: the canvas path needs decode-to-bitmap, same-origin\n // fetch, and a real 2D context (jsdom returns null and falls back below).\n let canvas: HTMLCanvasElement | null = null\n let context2d: CanvasRenderingContext2D | null = null\n let img: HTMLImageElement | null = null\n try {\n if (typeof createImageBitmap === 'function' && typeof fetch === 'function') {\n const probe = document.createElement('canvas')\n const c2d = probe.getContext('2d')\n if (c2d !== null) {\n canvas = probe\n context2d = c2d\n }\n }\n } catch {\n canvas = null\n context2d = null\n }\n\n if (canvas !== null && context2d !== null) {\n canvas.dataset.dshPetFrames2d = ctx.petId\n canvas.draggable = false\n canvas.style.width = '100%'\n canvas.style.height = '100%'\n canvas.style.objectFit = 'contain'\n canvas.style.pointerEvents = 'none'\n ctx.container.appendChild(canvas)\n } else {\n img = document.createElement('img')\n img.dataset.dshPetFrames2d = ctx.petId\n img.alt = ''\n img.draggable = false\n img.style.width = '100%'\n img.style.height = '100%'\n img.style.objectFit = 'contain'\n img.style.pointerEvents = 'none'\n ctx.container.appendChild(img)\n }\n\n // Decode cache: one concurrent decode per URL, retained under a decoded\n // byte budget. The historical map memoized every decoded frame forever, so\n // a pet that had played all of its tracks (every skin) kept every bitmap\n // alive for the life of the page: a shipped three-skin pet measures 1276\n // frames at 512x683 RGBA, about 1.7 GB, growing monotonically. Entries now\n // carry their decoded footprint, sit in Map insertion order (delete + set\n // is an LRU touch) and the least recently used ones outside the playing\n // window are closed once MAX_RETAINED_BYTES is crossed. A failed decode\n // still resolves undefined and leaves the memo, so a transient fetch error\n // retries instead of sticking.\n const decoding = new Map<string, DecodeEntry>()\n let retainedBytes = 0\n // All frame fetches funnel through a small pool. Full-library warm passes\n // on large pets fire 1100+ requests at once, which trips the browser's\n // in-flight request limit (net::ERR_INSUFFICIENT_RESOURCES) and fails\n // whole batches of frames while starving the rest of the page. Playback\n // demand jumps ahead of the warm backlog.\n const FRAME_POOL_LIMIT = 8\n const frameQueue: Array<{ url: string; release: () => void }> = []\n let activeFrames = 0\n\n const decodeFrame = async (url: string): Promise<DecodedFrame | undefined> => {\n try {\n const response = await fetch(url)\n if (!response.ok) throw new Error('http ' + response.status)\n const bitmap = await createImageBitmap(await response.blob())\n return { source: bitmap, width: bitmap.width, height: bitmap.height }\n } catch {\n // Fail-open: classic Image decode keeps non-modern runtimes alive.\n return await new Promise<DecodedFrame | undefined>((resolve) => {\n try {\n const pre = new Image()\n pre.onload = (): void => {\n resolve(pre.naturalWidth > 0 ? { source: pre, width: pre.naturalWidth, height: pre.naturalHeight } : undefined)\n }\n pre.onerror = (): void => resolve(undefined)\n pre.src = url\n } catch {\n resolve(undefined)\n }\n })\n }\n }\n\n const pumpFrames = (): void => {\n while (activeFrames < FRAME_POOL_LIMIT && frameQueue.length > 0) {\n const queued = frameQueue.shift()!\n activeFrames += 1\n queued.release()\n }\n }\n\n const loadFrame = (url: string, jump = false): Promise<DecodedFrame | undefined> => {\n // Jump first: warm-enqueued frames already carry their memo, so a\n // playback demand must reorder the unstarted entry before the cache\n // lookup short-circuits.\n if (jump) {\n const index = frameQueue.findIndex((queued) => queued.url === url)\n if (index > 0) frameQueue.unshift(frameQueue.splice(index, 1)[0]!)\n }\n const cached = decoding.get(url)\n if (cached !== undefined) {\n // LRU touch: a hit means playback just asked for this frame, so it must\n // not be the next victim. Re-inserting the same entry only reorders.\n decoding.delete(url)\n decoding.set(url, cached)\n return cached.job\n }\n let release!: () => void\n const gate = new Promise<void>((resolve) => { release = resolve })\n const job: Promise<DecodedFrame | undefined> = gate.then(() => (disposed ? undefined : decodeFrame(url)))\n const entry: DecodeEntry = { job }\n job.then(\n (frame) => {\n if (frame === undefined) {\n decoding.delete(url)\n return\n }\n // A decode that lands after dispose is closed here: nothing can close\n // it later, and the map was already drained.\n if (disposed) {\n releaseFrame(frame)\n decoding.delete(url)\n return\n }\n entry.frame = frame\n entry.bytes = frame.width * frame.height * 4\n retainedBytes += entry.bytes\n // Only a resolved frame is evictable, and its decoded size is known\n // only now, so the budget is enforced here.\n enforceRetentionBudget()\n },\n () => decoding.delete(url),\n )\n void job.finally(() => {\n activeFrames -= 1\n pumpFrames()\n })\n decoding.set(url, entry)\n const queued = { url, release }\n if (jump) frameQueue.unshift(queued)\n else frameQueue.push(queued)\n pumpFrames()\n return job\n }\n\n /**\n * Release decoded bitmaps until the retained footprint is back under\n * MAX_RETAINED_BYTES. Two properties keep this from breaking playback:\n *\n * - The playing track's look-ahead window, plus the frame a draw is waiting\n * on, are never released. Releasing one would hand a closed bitmap to\n * `drawImage`, and re-decoding it would stall the next tick.\n * - Frames of any other track go first. That is what keeps a running loop\n * warm under a budget smaller than two whole tracks: eviction reclaims the\n * track the pet left instead of eating the cycle it is playing.\n *\n * When the protected window alone exceeds the budget nothing is released —\n * a pet whose frames are that large cannot be bounded further without\n * breaking playback, and the overshoot is then exactly one window.\n */\n function enforceRetentionBudget(): void {\n if (retainedBytes <= MAX_RETAINED_BYTES) return\n const def = config.tracks[track]\n const playing = new Set<string>(def === undefined ? [] : def.frames)\n const protectedUrls = new Set<string>()\n if (pinned !== undefined) protectedUrls.add(pinned)\n if (def !== undefined) {\n const end = Math.min(def.frames.length, frameIndex + 1 + PREFETCH_AHEAD)\n for (let index = frameIndex; index < end; index += 1) {\n const url = def.frames[index]\n if (url !== undefined) protectedUrls.add(url)\n }\n }\n // Pass 1 reclaims frames of tracks the pet is not playing; pass 2 is the\n // backstop for a single track larger than the whole budget.\n for (const foreignOnly of [true, false]) {\n for (const [url, entry] of decoding) {\n if (retainedBytes <= MAX_RETAINED_BYTES) return\n if (entry.bytes === undefined || protectedUrls.has(url)) continue\n if (foreignOnly && playing.has(url)) continue\n releaseFrame(entry.frame)\n retainedBytes -= entry.bytes\n decoding.delete(url)\n }\n }\n }\n\n /**\n * Bounded look-ahead window: decode only the frames playback is about to\n * need. The historical warm pass decoded every frame of every track up\n * front - a shipped pet carries ~1.1k 512x683 frames, so that pass pulls\n * tens of megabytes and retains every decoded bitmap for the life of the\n * page. Prefetching the playing track's next frames keeps loops and phase\n * switches warm while unplayed tracks (and every unselected skin's\n * frames) stay on demand, where playback jumps the queue anyway.\n */\n const PREFETCH_AHEAD = 12\n\n const prefetchAhead = (trackId: string, index: number): void => {\n const def = config.tracks[trackId]\n if (def === undefined) return\n const end = Math.min(def.frames.length, index + 1 + PREFETCH_AHEAD)\n for (let ahead = index + 1; ahead < end; ahead += 1) {\n const url = def.frames[ahead]\n if (url !== undefined) void loadFrame(url)\n }\n }\n\n let disposed = false\n let timer: ReturnType<typeof setTimeout> | undefined\n let watchdog: ReturnType<typeof setInterval> | undefined\n let track: string = config.phases.idle\n let frameIndex = 0\n let lastAdvance = Date.now()\n let override: string | undefined\n // Skin base idle: every \"back to idle\" target resolves through this\n // (idle phase, unmapped phases and fallbacks), so a selected skin swaps\n // the pet's resting look without touching gameplay tracks.\n let baseIdle: string = config.phases.idle\n let drawToken = 0\n let lastDrawnUrl: string | undefined\n // The frame a draw is currently awaiting. Eviction must not release it:\n // the callback below holds the bitmap and would draw a closed one.\n let pinned: string | undefined\n\n const trackForPhase = (phase: ActivityPhase): string => {\n const mapped = config.phases[phase]\n if (mapped === undefined) return baseIdle\n const target = mapped === config.phases.idle ? baseIdle : mapped\n return config.tracks[target] !== undefined ? target : baseIdle\n }\n\n /** Canvas path: paints the newest requested frame; stale draws drop out. */\n const paintCanvas = (url: string): void => {\n if (context2d === null || canvas === null) return\n const myToken = ++drawToken\n pinned = url\n void loadFrame(url, true).then((frame) => {\n if (pinned === url) pinned = undefined\n if (disposed || frame === undefined || myToken !== drawToken) return\n if (lastDrawnUrl === url) return\n lastDrawnUrl = url\n // Resizing clears the canvas, so size only when it actually differs.\n if (canvas.width !== frame.width || canvas.height !== frame.height) {\n canvas.width = frame.width\n canvas.height = frame.height\n } else {\n context2d.clearRect(0, 0, canvas.width, canvas.height)\n }\n context2d.drawImage(frame.source as CanvasImageSource, 0, 0)\n }).catch(() => { if (pinned === url) pinned = undefined /* keep last frame */ })\n }\n\n const show = (trackId: string, index: number): void => {\n const def = config.tracks[trackId]\n const url = def?.frames[index]\n if (url === undefined) return\n prefetchAhead(trackId, index)\n if (img !== null) {\n if (img.getAttribute('src') !== url) img.src = url\n return\n }\n paintCanvas(url)\n }\n\n const schedule = (ms: number): void => {\n if (disposed) return\n timer = setTimeout(tick, ms)\n }\n\n function tick(): void {\n if (disposed) return\n const def = config.tracks[track]\n if (def === undefined || def.frames.length === 0) return\n lastAdvance = Date.now()\n const next = frameIndex + 1\n if (next < def.frames.length) {\n frameIndex = next\n show(track, frameIndex)\n schedule(def.durations[frameIndex] ?? 200)\n return\n }\n if (def.loop) {\n frameIndex = 0\n show(track, frameIndex)\n schedule(def.durations[frameIndex] ?? 200)\n return\n }\n // Non-loop completion: settle into the fallback — an explicit fallback to\n // a real track wins, except when it points back at the manifest idle\n // (that resolves through the skin base idle); anything else lands on\n // the skin base idle. When the settle target is what the phase map\n // plays anyway, release the gameplay override.\n const target = def.fallback !== undefined && config.tracks[def.fallback] !== undefined\n ? (def.fallback === config.phases.idle ? baseIdle : def.fallback)\n : baseIdle\n if (target === trackForPhase(ctx.phase.get())) override = undefined\n play(target)\n }\n\n function play(trackId: string): void {\n if (disposed) return\n if (config.tracks[trackId] === undefined) trackId = baseIdle\n if (timer !== undefined) clearTimeout(timer)\n track = trackId\n frameIndex = 0\n lastAdvance = Date.now()\n show(track, frameIndex)\n if (reducedMotion) return\n const def = config.tracks[track]!\n schedule(def.durations[0] ?? 200)\n }\n\n const unsubscribe = ctx.phase.subscribe((phase) => {\n if (override !== undefined) return\n const target = trackForPhase(phase)\n if (target !== track) play(target)\n })\n\n // Watchdog: a throttled-away timer (background tab) leaves the chain\n // dead; re-kick when a looping track has not advanced on schedule.\n if (!reducedMotion) {\n watchdog = setInterval(() => {\n if (disposed) return\n const def = config.tracks[track]\n if (def === undefined || !def.loop) return\n const expected = (def.durations[frameIndex] ?? 200) + WATCHDOG_MS\n if (Date.now() - lastAdvance > expected) tick()\n }, WATCHDOG_MS)\n }\n\n play(track)\n\n let disposedOnce = false\n const dispose = (): void => {\n if (disposedOnce) return\n disposedOnce = true\n disposed = true\n unsubscribe()\n if (timer !== undefined) clearTimeout(timer)\n if (watchdog !== undefined) clearInterval(watchdog)\n // Release every retained bitmap and drain the pool. Queued-but-unstarted\n // frames resolve as no-ops (the gate skips decodeFrame once disposed), and\n // a decode that lands after this loop is closed by the resolution guard\n // above, so teardown leaves nothing pending and nothing retained.\n for (const queued of frameQueue.splice(0)) queued.release()\n for (const entry of decoding.values()) releaseFrame(entry.frame)\n decoding.clear()\n retainedBytes = 0\n canvas?.remove()\n img?.remove()\n }\n ctx.onCleanup(dispose)\n\n return {\n dispose,\n setState(next: string | undefined): void {\n if (disposed) return\n if (next === undefined) {\n override = undefined\n const target = trackForPhase(ctx.phase.get())\n if (target !== track) play(target)\n return\n }\n if (config.tracks[next] === undefined) return\n override = next\n if (next !== track) play(next)\n },\n setIdleTrack(next: string | undefined): void {\n if (disposed) return\n if (next === undefined || (config.tracks[next] !== undefined && config.tracks[next]!.loop)) {\n baseIdle = next ?? config.phases.idle\n }\n // A skin only owns the resting look: re-resolve only when no\n // gameplay override is active (active overrides end into baseIdle).\n if (override === undefined) {\n const target = trackForPhase(ctx.phase.get())\n if (target !== track) play(target)\n }\n },\n currentTrack(): string {\n return track\n },\n }\n },\n}\n","/**\n * Cross-bundle-instance teardown slot for the page-global pet root\n * (issue #785).\n *\n * A client bundle swap (HMR rebuilt frame, plugin update, duplicate\n * injection) runs a new apply body while the previous instance's fiber\n * may still be draining. Module state does not survive the swap, so a\n * closure guard only sees one apply body and the previous instance's\n * container keeps sitting on document.body: the page shows two pets\n * until a full refresh. The slot rides globalThis (which does survive)\n * so a re-apply can find the previous instance and unmount its React\n * root cleanly before mounting its own; the previous fiber's later\n * disposal stays a no-op through the idempotent teardowns.\n */\n\nconst SLOT = Symbol.for('dsh-pet.client-ui-teardown')\n\ninterface TeardownSlot {\n [SLOT]?: (() => void) | undefined\n}\n\n/**\n * Claim the page-global pet UI slot with the current instance's teardown\n * (React root unmount + container removal + poll stop).\n * @param teardown - what a later instance runs to take the slot over.\n * @returns a disposer that clears the slot when the current instance's\n * UI is torn down (settings toggle, takeover, or fiber disposal).\n */\nexport function registerPetUiTeardown(teardown: () => void): () => void {\n const slot = globalThis as TeardownSlot\n slot[SLOT] = teardown\n return () => {\n if (slot[SLOT] === teardown) slot[SLOT] = undefined\n }\n}\n\n/**\n * Run the previous instance's teardown if one is registered, so the\n * re-applying instance becomes the sole owner of the page-global pet\n * root. No-op when the previous fiber already tore down cleanly.\n */\nexport function takeoverPetUiTeardown(): void {\n const slot = globalThis as TeardownSlot\n const teardown = slot[SLOT]\n slot[SLOT] = undefined\n teardown?.()\n}\n","/**\n * Coarse adjustment for a bounded number: resting the pointer on the control\n * (or moving focus into it) raises a small bubble holding a slider across the\n * field's whole range, so a large change is one drag instead of many presses\n * or a retyped value. The control itself stays the precise entry.\n *\n * The bubble belongs to the anchor's subtree, so moving from the control onto\n * the bubble never counts as leaving. It opens after a short rest and closes a\n * moment after the pointer and focus have both gone, so crossing the control\n * on the way elsewhere does not flash it. While a drag is in progress the\n * bubble stays put even if the pointer strays off it.\n *\n * Dragging reports each value through `onInput`, so the field shows it live;\n * releasing the thumb, or a key press on it, reports `onCommit` once. The\n * bubble opens on the side of the control that has room inside the nearest\n * scrolling ancestor, so a row near the top of a settings page does not hang\n * its bubble under the page edge.\n */\n\nimport { useEffect, useRef, useState, type ChangeEvent, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react'\nimport css from './settings-card.module.css'\n\n/** Rest on the control before the bubble opens. */\nconst OPEN_DELAY_MS = 220\n/** Grace after pointer and focus have left before the bubble closes. */\nconst CLOSE_DELAY_MS = 200\n/** Room the bubble needs between the control and the scroller's edge. */\nconst BUBBLE_ROOM_PX = 64\n\n/** Props of {@link RangeBubble}. */\nexport interface RangeBubbleProps {\n /** Lowest value the slider reaches. */\n min: number\n /** Highest value the slider reaches. */\n max: number\n /** Slider granularity. */\n step: number\n /** Current value; a value outside the range parks the thumb at the nearer end. */\n value: number\n /** Accessible name of the slider. */\n label: string\n /** Disables the bubble along with the control. */\n disabled?: boolean\n /** Each value while the thumb moves. */\n onInput: (value: number) => void\n /** The value the thumb was released on, once per drag or key press. */\n onCommit: (value: number) => void\n /** The precise control the bubble hangs off. */\n children: ReactNode\n}\n\n/** The nearest ancestor that scrolls vertically, or the viewport's root. */\nfunction scroller(node: HTMLElement): HTMLElement {\n for (let parent = node.parentElement; parent !== null; parent = parent.parentElement) {\n const overflow = getComputedStyle(parent).overflowY\n if (overflow === 'auto' || overflow === 'scroll') return parent\n }\n return node.ownerDocument.documentElement\n}\n\n/**\n * Render the control with its coarse-adjustment bubble.\n * @param props - the range, the value and the two report callbacks.\n * @returns the anchor holding the control and the bubble.\n */\nexport function RangeBubble(props: RangeBubbleProps): ReactNode {\n const { min, max, step, disabled = false } = props\n const [open, setOpen] = useState(false)\n const [side, setSide] = useState<'above' | 'below'>('above')\n const [live, setLive] = useState<number | null>(null)\n const anchorRef = useRef<HTMLDivElement | null>(null)\n const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)\n const hovered = useRef(false)\n const focused = useRef(false)\n const dragging = useRef(false)\n\n useEffect(() => () => { clearTimeout(timer.current) }, [])\n useEffect(() => {\n if (disabled) {\n clearTimeout(timer.current)\n setOpen(false)\n }\n }, [disabled])\n\n const show = (): void => {\n const anchor = anchorRef.current\n if (anchor !== null) {\n const room = anchor.getBoundingClientRect().top - scroller(anchor).getBoundingClientRect().top\n setSide(room >= BUBBLE_ROOM_PX ? 'above' : 'below')\n }\n setOpen(true)\n }\n const schedule = (): void => {\n clearTimeout(timer.current)\n if (disabled) return\n if (hovered.current || focused.current || dragging.current) {\n if (!open) timer.current = setTimeout(show, focused.current ? 0 : OPEN_DELAY_MS)\n return\n }\n timer.current = setTimeout(() => { setOpen(false) }, CLOSE_DELAY_MS)\n }\n\n const commit = (value: number): void => {\n dragging.current = false\n setLive(null)\n props.onCommit(value)\n schedule()\n }\n const onChange = (event: ChangeEvent<HTMLInputElement>): void => {\n const value = Number(event.target.value)\n setLive(value)\n props.onInput(value)\n }\n const onKeyUp = (event: KeyboardEvent<HTMLInputElement>): void => {\n if (live !== null) commit(live)\n if (event.key === 'Escape') {\n clearTimeout(timer.current)\n setOpen(false)\n }\n }\n const shown = live ?? Math.min(max, Math.max(min, props.value))\n\n return (\n <div\n ref={anchorRef}\n className={css.rangeAnchor}\n onPointerEnter={() => { hovered.current = true; schedule() }}\n onPointerLeave={() => { hovered.current = false; schedule() }}\n onFocus={() => { focused.current = true; schedule() }}\n onBlur={(event) => {\n if (event.currentTarget.contains(event.relatedTarget as Node | null)) return\n focused.current = false\n if (live !== null) commit(live)\n else schedule()\n }}\n >\n {props.children}\n <div className={css.rangeBubble} data-open={open ? '' : undefined} data-side={side}>\n <input\n type=\"range\"\n className={css.rangeSlider}\n min={min}\n max={max}\n step={step}\n value={shown}\n aria-label={props.label}\n tabIndex={open ? 0 : -1}\n disabled={disabled}\n style={{ '--range-fill': `${((shown - min) / (max - min)) * 100}%` } as CSSProperties}\n onPointerDown={() => { dragging.current = true }}\n onPointerUp={(event) => { commit(Number(event.currentTarget.value)) }}\n onPointerCancel={(event) => { commit(Number(event.currentTarget.value)) }}\n onChange={onChange}\n onKeyUp={onKeyUp}\n />\n <span className={css.rangeEnds} aria-hidden=\"true\">\n <span>{min}</span>\n <span>{max}</span>\n </span>\n </div>\n </div>\n )\n}\n","/**\n * The family's segmented control: a quiet track whose options share one\n * highlight that slides to the pressed option, instead of each option fading\n * its own background out and the next one in. The settings fields' small\n * choices and the Web Extensions TAB strip both render through it, so the two\n * read as one control.\n *\n * The caller builds the option buttons and marks the pressed one with\n * `data-active`; the group measures that button after every render and writes\n * its box as four custom properties, and the stylesheet draws the highlight\n * there (`.segmentGroup[data-pill]::before`). Attribute and first placement\n * land in the same task, so the highlight appears in place and only later\n * changes slide. A ResizeObserver re-measures when the group or an option\n * changes size: a longer locale, a font arriving, a container growing, a\n * strip wrapping onto a second line.\n */\n\nimport { Children, useLayoutEffect, useRef, type HTMLAttributes, type ReactNode } from 'react'\nimport css from './settings-card.module.css'\n\n/** The attribute marking a group whose highlight has been placed. */\nconst PILL_ATTR = 'data-pill'\n/** The pressed option, relative to the group. */\nconst ACTIVE_SELECTOR = ':scope > [data-active]'\nconst PILL_PROPERTIES = ['--segment-pill-x', '--segment-pill-y', '--segment-pill-w', '--segment-pill-h'] as const\n\n/** Props of {@link SegmentGroup}: the track's own attributes and the option buttons. */\nexport interface SegmentGroupProps extends HTMLAttributes<HTMLDivElement> {\n /** The option buttons; the pressed one carries `data-active`. */\n children: ReactNode\n}\n\n/**\n * Write the highlight's box from the pressed option's box, or take the\n * highlight off when nothing is pressed or the group has no layout yet.\n * The two boxes are read in viewport pixels and turned back into the group's\n * own CSS pixels, so a dialog that opens through a scale transform still\n * lands the highlight on its option.\n */\nfunction placePill(group: HTMLElement): void {\n const item = group.querySelector<HTMLElement>(ACTIVE_SELECTOR)\n const box = group.getBoundingClientRect()\n if (item === null || group.offsetWidth === 0 || box.width === 0) {\n group.removeAttribute(PILL_ATTR)\n for (const property of PILL_PROPERTIES) group.style.removeProperty(property)\n return\n }\n const scale = box.width / group.offsetWidth\n const itemBox = item.getBoundingClientRect()\n const values = [\n (itemBox.left - box.left) / scale - group.clientLeft,\n (itemBox.top - box.top) / scale - group.clientTop,\n itemBox.width / scale,\n itemBox.height / scale,\n ]\n values.forEach((value, index) => {\n group.style.setProperty(PILL_PROPERTIES[index], `${Math.round(value * 100) / 100}px`)\n })\n if (!group.hasAttribute(PILL_ATTR)) group.setAttribute(PILL_ATTR, '')\n}\n\n/**\n * Render a segmented track around the caller's option buttons.\n * @param props - the track's attributes (role, accessible name, key handler) and its options.\n * @returns the track.\n */\nexport function SegmentGroup(props: SegmentGroupProps): ReactNode {\n const { children, className, ...rest } = props\n const group = useRef<HTMLDivElement | null>(null)\n const count = Children.count(children)\n\n // Placed before the frame is painted, after every render: a press moves the\n // pressed mark and the highlight follows it in the same frame.\n useLayoutEffect(() => {\n if (group.current !== null) placePill(group.current)\n })\n\n useLayoutEffect(() => {\n const element = group.current\n if (element === null || typeof ResizeObserver === 'undefined') return undefined\n const observer = new ResizeObserver(() => { placePill(element) })\n observer.observe(element)\n for (const item of Array.from(element.children)) observer.observe(item)\n return () => { observer.disconnect() }\n }, [count])\n\n return (\n <div {...rest} ref={group} className={className === undefined ? css.segmentGroup : `${css.segmentGroup} ${className}`}>\n {children}\n </div>\n )\n}\n","/**\n * Family-shared chrome for plugin settings cards: a disclosure header naming\n * the plugin and what its settings govern, the controls inside, and the line\n * that reports a refused write. A pick is written the moment it is made and a\n * typed value after a pause, so the card has no save button and nothing waits\n * on the reader. Renders nothing while the namespace is unavailable — a\n * deployment that does not compose the owning plugin should show no trace of\n * it. Inlined into each consumer's client bundle; mirrors the official\n * ui-plugin-config PluginCard in a self-contained slice.\n *\n * Every field inside the body is one settings row: the label and its hint on\n * the left, the control on the right, a hairline between two rows; a narrow\n * card stacks the control under the text (settings-card.module.css).\n */\n\nimport { createContext, useCallback, useContext, useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode } from 'react'\nimport type { CardShell } from './settings-form.ts'\nimport { RangeBubble } from './RangeBubble.tsx'\nimport { SegmentGroup } from './SegmentGroup.tsx'\nimport css from './settings-card.module.css'\n\n/** Copy keys the card chrome itself reads; every consumer locale carries this shared vocabulary. */\nexport const CARD_COPY_KEYS = [\n 'settings.collapse',\n 'settings.expand',\n 'settings.notExposed',\n 'settings.readOnly',\n 'settings.saveFailed',\n] as const\n\n/**\n * What a text field inside a card reaches without its plugin wiring it: write\n * the pending draft now (Enter, leaving the field) or put it back (Escape).\n * Picks need neither; they are written the moment they are made.\n */\nconst CardApply = createContext<{ commit(): void, revert(): void } | null>(null)\n\n/** Copy key the card chrome itself reads. */\nexport type CardCopyKey = (typeof CARD_COPY_KEYS)[number]\n\n/** Key domain for the plugin's own copy (inferred per consumer). */\nexport type SettingsCardKey<TKey extends string = string> = TKey | CardCopyKey\n\n/** Card chrome shared by every plugin settings card. */\nexport interface PluginSettingsCardProps<TKey extends string = string> {\n /** Locale reader for this card's copy. */\n t: (key: SettingsCardKey<TKey>, params?: Record<string, string | number>) => string\n /** Locale key of the plugin's name. */\n titleKey: TKey\n /** Locale key of the line describing what this plugin's settings govern. */\n descriptionKey: TKey\n /** Optional rich header description rendered instead of the plain t(descriptionKey) text (the plain text stays as the tooltip). */\n descriptionNode?: ReactNode\n /**\n * Locale key of the full sentence behind a shortened description: when\n * present, the header's native `title` takes this text while the visible\n * line keeps `descriptionKey`/`descriptionNode`, so a compact card can\n * compress the sentence without keeping a second visible copy of it.\n * Defaults to the description key.\n */\n descriptionTitleKey?: TKey\n /**\n * Optional leading mark identifying the plugin. A card without one keeps the\n * plain official header shape, so the chrome stays a readable sibling of the\n * built-in PluginCard wherever a family plugin lands in the official bundle\n * seat.\n */\n icon?: ReactNode\n /** The card's form state: availability, writability, and how the last write went. */\n state: CardShell\n /** Write every pending draft now: a text field's Enter or blur. */\n onSave: () => void\n /** Drop every pending draft: a text field's Escape. */\n onDiscard: () => void\n /**\n * Id applied to the card's title element, so a header control (an immediate\n * toggle in `headerAction`) can name itself through `aria-labelledby`\n * instead of repeating the title as a string.\n */\n titleId?: string\n /**\n * Render the header only, with no body region. A card whose whole setting is\n * the header control (a switch whose explanation is the description) has no\n * controls to lay out below it, and an empty body would draw a divider line\n * with nothing under it.\n */\n headerOnly?: boolean\n /**\n * Render the controls expanded on arrival (still collapsible). Defaults to\n * true: promoted first-level sections show their settings immediately.\n */\n defaultOpen?: boolean\n /**\n * Render without the collapse affordance: a static header and an always\n * visible body. Used by first-level settings sections whose nav entry\n * already provides the selection.\n */\n alwaysOpen?: boolean\n /**\n * Hide the line under the body that reports a refused write: a card whose\n * body applies its own changes (an embedded external settings section)\n * reports its own failures.\n */\n hideFooter?: boolean\n /**\n * Optional control rendered at the header's trailing edge, before the\n * chevron. A card whose setting is one immediate flip (it\n * applies outside the card's form) puts its ToggleSwitch here, so the control\n * is reachable without opening the card and matches a plugin card's shape.\n */\n headerAction?: ReactNode\n /** Render children even when the settings namespace is not exposed by the host. */\n renderChildrenWhenNotExposed?: boolean\n /** Hide the 'not exposed' warning banner when the settings namespace is not exposed. */\n hideNotExposedNotice?: boolean\n /**\n * Compact chrome for a topic card rendered inside another card's body: a\n * smaller title, a tighter header and body inset, and a one-line description\n * whose full text stays on the header's own title. Defaults to the\n * first-level chrome, which is unchanged.\n */\n density?: 'nested'\n /** The plugin's controls. */\n children: ReactNode\n}\n\n/** Length of the body's disclosure motion; it matches `--settings-card-motion` on the card root. */\nconst BODY_MOTION_MS = 180\n\n/**\n * Lifecycle of one card body. `collapsed` is the mounted-but-closed frame the\n * enter leg starts from, `entering` and `closing` are the two moving legs, and\n * `shown` is the settled open body, which releases its clipping box.\n */\ntype BodyPhase = 'hidden' | 'collapsed' | 'entering' | 'shown' | 'closing'\n\n/**\n * Render one plugin settings card.\n * @param props - the plugin's copy keys, its form state, and its controls.\n * @returns the card, or nothing while the namespace is still loading.\n */\nexport function PluginSettingsCard<TKey extends string = string>(props: PluginSettingsCardProps<TKey>) {\n const [open, setOpen] = useState(props.defaultOpen ?? true)\n const { state, alwaysOpen } = props\n const expanded = alwaysOpen === true || open\n const [bodyPhase, setBodyPhase] = useState<BodyPhase>(expanded ? 'shown' : 'hidden')\n const bodyRef = useRef<HTMLDivElement | null>(null)\n // Enter and leave run the same pair: a body that should open is mounted\n // closed for one frame so its transition has a state to leave, and a closing\n // one stays mounted until its leg has run.\n useLayoutEffect(() => {\n if (expanded) {\n if (bodyPhase === 'hidden') setBodyPhase('collapsed')\n else if (bodyPhase === 'collapsed') {\n const node = bodyRef.current\n if (node !== null) void node.offsetHeight\n setBodyPhase('entering')\n } else if (bodyPhase === 'closing') setBodyPhase('entering')\n return\n }\n if (bodyPhase === 'collapsed') setBodyPhase('hidden')\n else if (bodyPhase === 'entering' || bodyPhase === 'shown') setBodyPhase('closing')\n }, [expanded, bodyPhase])\n useEffect(() => {\n if (bodyPhase !== 'entering' && bodyPhase !== 'closing') return\n const timer = setTimeout(() => {\n setBodyPhase(bodyPhase === 'entering' ? 'shown' : 'hidden')\n }, BODY_MOTION_MS)\n return () => { clearTimeout(timer) }\n }, [bodyPhase])\n if (!state.available) return null\n const title = props.t(props.titleKey)\n const description = props.t(props.descriptionKey)\n const descriptionTitle = props.descriptionTitleKey === undefined ? description : props.t(props.descriptionTitleKey)\n const baseClass = expanded ? `${css.cardOpen} ${css.card}` : css.card\n const cardClass = props.density === 'nested' ? `${baseClass} ${css.cardNested}` : baseClass\n /** The body region both legs share; a hidden phase renders nothing at all. */\n const bodyRegion = (content: ReactNode) => bodyPhase === 'hidden'\n ? null\n : (\n <div className={css.disclosure} data-state={bodyPhase} ref={bodyRef}>\n <div className={css.body}>{content}</div>\n </div>\n )\n // With alwaysOpen the nav entry already provides the selection, so the\n // header is a static title row instead of a disclosure button.\n const header = alwaysOpen === true\n ? (\n <div className={css.headerStatic}>\n {props.icon !== undefined ? <span className={css.mark} aria-hidden=\"true\">{props.icon}</span> : null}\n <span className={css.headText}>\n <span className={css.name} id={props.titleId} title={title}>{title}</span>\n <span className={css.description} title={descriptionTitle}>{props.descriptionNode ?? description}</span>\n </span>\n {props.headerAction !== undefined ? <span className={css.headerAction}>{props.headerAction}</span> : null}\n </div>\n )\n : (\n <button\n type=\"button\"\n className={css.header}\n aria-expanded={open}\n aria-label={`${props.t(open ? 'settings.collapse' : 'settings.expand')}: ${title}`}\n onClick={() => { setOpen(!open) }}\n >\n {props.icon !== undefined ? <span className={css.mark} aria-hidden=\"true\">{props.icon}</span> : null}\n <span className={css.headText}>\n <span className={css.name} id={props.titleId} title={title}>{title}</span>\n <span className={css.description} title={descriptionTitle}>{props.descriptionNode ?? description}</span>\n </span>\n {props.headerAction !== undefined ? <span className={css.headerAction}>{props.headerAction}</span> : null}\n <svg\n width=\"14\"\n height=\"14\"\n viewBox=\"0 0 14 14\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n className={open ? `${css.chevron} ${css.chevronOpen}` : css.chevron}\n >\n <path\n d=\"M11.8486 5.5L11.4238 5.92383L8.69727 8.65137C8.44157 8.90706 8.21562 9.13382 8.01172 9.29785C7.79912 9.46883 7.55595 9.61756 7.25 9.66602C7.08435 9.69222 6.91565 9.69222 6.75 9.66602C6.44405 9.61756 6.20088 9.46883 5.98828 9.29785C5.78438 9.13382 5.55843 8.90706 5.30273 8.65137L2.57617 5.92383L2.15137 5.5L3 4.65137L3.42383 5.07617L6.15137 7.80273C6.42595 8.07732 6.59876 8.24849 6.74023 8.3623C6.87291 8.46904 6.92272 8.47813 6.9375 8.48047C6.97895 8.48703 7.02105 8.48703 7.0625 8.48047C7.07728 8.47813 7.12709 8.46904 7.25977 8.3623C7.40124 8.24849 7.57405 8.07732 7.84863 7.80273L10.5762 5.07617L11 4.65137L11.8486 5.5Z\"\n fill=\"currentColor\"\n />\n </svg>\n </button>\n )\n // The namespace exists but the Host does not serve it to this client (the\n // official settings allowlist omits third-party namespaces): show a card\n // that explains the gap instead of vanishing, so a missing card never\n // reads as a missing plugin.\n if (!state.exposed && props.renderChildrenWhenNotExposed !== true) {\n const showNotice = props.hideNotExposedNotice !== true\n return (\n <li className={cardClass}>\n {header}\n {bodyRegion(showNotice ? <p className={css.notExposed} role=\"status\">{props.t('settings.notExposed')}</p> : null)}\n </li>\n )\n }\n // A header-only card has no body region at all: the divider would otherwise\n // sit above an empty box.\n const bodyVisible = props.headerOnly !== true\n return (\n <li className={cardClass}>\n {header}\n {bodyVisible\n ? bodyRegion(\n <>\n {!state.writable ? <p className={css.readOnly} role=\"status\">{props.t('settings.readOnly')}</p> : null}\n <CardApply.Provider value={{ commit: props.onSave, revert: props.onDiscard }}>\n {props.children}\n </CardApply.Provider>\n {props.hideFooter !== true && state.failed\n ? (\n <p className={css.failed} role=\"status\">\n {props.t('settings.saveFailed')}{state.failedReason ? ' - ' + state.failedReason : ''}\n </p>\n )\n : null}\n </>,\n )\n : null}\n </li>\n )\n}\n\n/** Props every field control needs regardless of its value type. */\nexport interface FieldProps {\n /** Stable id associating the label with its control. */\n id: string\n /** Visible label. */\n label: string\n /** One-line explanation rendered under the control. */\n hint: string\n /**\n * Full sentence behind the visible hint, exposed as the paragraph's native\n * `title` so a card can shorten the line without losing the text. Omitted:\n * the paragraph carries no title attribute at all.\n */\n hintTitle?: string\n /** Draft text this control renders. */\n text: string\n /** True when the field holds a user-layer entry over the inherited value. */\n overridden: boolean\n /** True when the draft is not a value this field accepts. */\n invalid: boolean\n /** Copy for the overridden badge. */\n overriddenLabel: string\n /** Copy for the reset control. */\n resetLabel: string\n /** Copy shown in place of the hint while the draft is invalid. */\n invalidLabel: string\n /** Disables every control (read-only document, or an unavailable namespace). */\n disabled: boolean\n /** Take new draft text; the card writes it as the field's entry rule says. */\n onEdit: (text: string) => void\n /** Clear the field at once so it re-inherits the composition layer. */\n onReset: () => void\n}\n\n/**\n * A typed value field. Its draft is written after a pause in typing, at once on\n * Enter or when focus leaves, and Escape puts the stored value back. `numeric`\n * only hints the keypad: which drafts a field accepts is decided by its spec.\n * A field given a `range` also offers the coarse slider bubble: dragging fills\n * the draft live and releasing writes it.\n */\nexport function ValueField(props: FieldProps & {\n /** Hints a numeric keypad without narrowing what the control accepts. */\n numeric?: boolean\n /** Placeholder shown while the draft is empty. */\n placeholder?: string\n /** Bounds of a numeric field, for the coarse slider; the spec still judges every draft. */\n range?: { min: number, max: number, step: number }\n}) {\n const apply = useContext(CardApply)\n const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {\n if (apply === null || (event.key !== 'Enter' && event.key !== 'Escape')) return\n event.preventDefault()\n if (event.key === 'Enter') apply.commit()\n else apply.revert()\n event.currentTarget.blur()\n }\n const input = (\n <input\n id={props.id}\n className={props.invalid ? css.inputInvalid : css.input}\n type=\"text\"\n {...props.numeric === true ? { inputMode: 'numeric' as const } : {}}\n {...props.invalid ? { 'aria-invalid': true } : {}}\n value={props.text}\n placeholder={props.placeholder ?? ''}\n disabled={props.disabled}\n onChange={(event) => { props.onEdit(event.target.value) }}\n onKeyDown={onKeyDown}\n onBlur={() => { apply?.commit() }}\n />\n )\n const { range } = props\n const typed = Number(props.text)\n return (\n <div className={css.field}>\n <div className={css.head}>\n <label className={css.label} htmlFor={props.id}>{props.label}</label>\n {props.overridden\n ? (\n <span className={css.badges}>\n <span className={css.badge}>{props.overriddenLabel}</span>\n <button\n type=\"button\"\n className={css.reset}\n disabled={props.disabled}\n onClick={props.onReset}\n >\n {props.resetLabel}\n </button>\n </span>\n )\n : null}\n </div>\n {range === undefined\n ? input\n : (\n <RangeBubble\n min={range.min}\n max={range.max}\n step={range.step}\n value={props.text.trim() === '' || Number.isNaN(typed) ? range.min : typed}\n label={`${props.label} ${range.min}–${range.max}`}\n disabled={props.disabled}\n onInput={(value) => { props.onEdit(String(value)) }}\n onCommit={(value) => {\n props.onEdit(String(value))\n apply?.commit()\n }}\n >\n {input}\n </RangeBubble>\n )}\n <p className={props.invalid ? css.invalid : css.hint} title={props.hintTitle}>\n {props.invalid ? props.invalidLabel : props.hint}\n </p>\n </div>\n )\n}\n\nconst NON_SKIN_BODY_MARKERS = new Set(['dshSkinCenter', 'dshSidebarCollapsed'])\n// 检测使用使用皮肤,用了皮肤退回原生select样式,防止样式冲突。默认外观下使用优化后的select样式。\nfunction isSkinActive(): boolean {\n const datasetList = Object.keys(document.body.dataset)\n const isActive = datasetList.some(key => key.startsWith('dsh') && !NON_SKIN_BODY_MARKERS.has(key))\n return isActive\n}\n\ninterface SelectOption {\n value: string\n label: string\n}\n\nconst SELECT_CLOSE_MS = 100\n\n/**\n * The shared dual-mode select control. While an appearance skin is active it\n * renders the legacy native `<select>` untouched, so element-level skin\n * selectors keep working; under the default appearance it renders a\n * self-drawn `role=\"listbox\"` popup whose open/close is transition-animated.\n * Cards reach it through BooleanField/ChoiceField; editors outside a card\n * (the side-card prefs) bind it directly through onEdit.\n * 双模式下拉框:皮肤激活时用原生 select,默认外观用自绘动画弹层。\n */\nexport function SelectField(props: {\n id: string\n options: ReadonlyArray<SelectOption>\n value: string\n disabled: boolean\n invalid: boolean\n onEdit: (text: string) => void\n}) {\n const { id, options, value } = props\n const [open, setOpen] = useState(false)\n const [closing, setClosing] = useState(false)\n const [phase, setPhase] = useState<'initial' | 'open'>('initial')\n const [activeIndex, setActiveIndex] = useState(0)\n const closeTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)\n const wrapRef = useRef<HTMLDivElement | null>(null)\n const popupRef = useRef<HTMLDivElement | null>(null)\n\n const currentIndex = () => {\n const index = options.findIndex(option => option.value === value)\n return index >= 0 ? index : 0\n }\n\n const close = useCallback(() => {\n if (closeTimer.current !== undefined) clearTimeout(closeTimer.current)\n setClosing(true)\n closeTimer.current = setTimeout(() => {\n setClosing(false)\n setOpen(false)\n }, SELECT_CLOSE_MS)\n }, [])\n\n const openPopup = () => {\n if (closeTimer.current !== undefined) clearTimeout(closeTimer.current)\n setActiveIndex(currentIndex())\n setPhase('initial')\n setClosing(false)\n setOpen(true)\n }\n\n const commit = (index: number) => {\n const option = options[index]\n if (option) props.onEdit(option.value)\n close()\n }\n\n const onTriggerClick = () => {\n if (props.disabled) return\n if (open && !closing) close()\n else openPopup()\n }\n\n const onKeyDown = (event: KeyboardEvent<HTMLButtonElement>) => {\n if (props.disabled) return\n const count = options.length\n switch (event.key) {\n case 'ArrowDown':\n case 'ArrowUp':\n case 'Enter':\n case ' ':\n event.preventDefault()\n if (!open) {\n openPopup()\n } else if (!closing) {\n if (event.key === 'ArrowDown') setActiveIndex(index => (index + 1) % count)\n else if (event.key === 'ArrowUp') setActiveIndex(index => (index - 1 + count) % count)\n else commit(activeIndex)\n }\n break\n case 'Escape':\n if (open) {\n event.preventDefault()\n event.stopPropagation()\n close()\n }\n break\n case 'Tab':\n if (open) close()\n break\n }\n }\n\n useEffect(() => () => {\n if (closeTimer.current !== undefined) clearTimeout(closeTimer.current)\n }, [])\n useLayoutEffect(() => {\n if (open && !closing && phase === 'initial') {\n void popupRef.current?.offsetHeight\n setPhase('open')\n }\n }, [open, closing, phase])\n\n useEffect(() => {\n if (!open) return\n const onPointerDown = (event: PointerEvent) => {\n const target = event.target\n if (target instanceof Node && !wrapRef.current?.contains(target)) close()\n }\n document.addEventListener('pointerdown', onPointerDown)\n return () => document.removeEventListener('pointerdown', onPointerDown)\n }, [open, close])\n\n useEffect(() => {\n if (props.disabled && open) close()\n }, [props.disabled, open, close])\n\n // 使用了皮肤则退回原生select样式防止样式冲突。\n if (isSkinActive()) {\n return (\n <select\n id={id}\n className={css.select}\n value={value}\n disabled={props.disabled}\n onChange={(event) => { props.onEdit(event.target.value) }}\n >\n {options.map(option => (\n <option key={option.value} value={option.value}>{option.label}</option>\n ))}\n </select>\n )\n }\n\n const label = options.find(option => option.value === value)?.label ?? ''\n const popupClass = closing\n ? `${css.selectPopup} ${css.selectPopupClose}`\n : phase === 'open'\n ? `${css.selectPopup} ${css.selectPopupOpen}`\n : css.selectPopup\n return (\n <div className={css.selectWrap} ref={wrapRef}>\n <button\n type=\"button\"\n id={id}\n className={`${css.select} ${css.selectButton}`}\n disabled={props.disabled}\n aria-haspopup=\"listbox\"\n aria-expanded={open}\n aria-activedescendant={open ? `${id}-o${activeIndex}` : undefined}\n aria-invalid={props.invalid || undefined}\n onClick={onTriggerClick}\n onKeyDown={onKeyDown}\n >\n <span className={css.selectLabel}>{label}</span>\n <svg\n width=\"14\"\n height=\"14\"\n viewBox=\"0 0 14 14\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n className={open ? `${css.selectChevron} ${css.selectChevronOpen}` : css.selectChevron}\n aria-hidden=\"true\"\n >\n <path\n d=\"M11.8486 5.5L11.4238 5.92383L8.69727 8.65137C8.44157 8.90706 8.21562 9.13382 8.01172 9.29785C7.79912 9.46883 7.55595 9.61756 7.25 9.66602C7.08435 9.69222 6.91565 9.69222 6.75 9.66602C6.44405 9.61756 6.20088 9.46883 5.98828 9.29785C5.78438 9.13382 5.55843 8.90706 5.30273 8.65137L2.57617 5.92383L2.15137 5.5L3 4.65137L3.42383 5.07617L6.15137 7.80273C6.42595 8.07732 6.59876 8.24849 6.74023 8.3623C6.87291 8.46904 6.92272 8.47813 6.9375 8.48047C6.97895 8.48703 7.02105 8.48703 7.0625 8.48047C7.07728 8.47813 7.12709 8.46904 7.25977 8.3623C7.40124 8.24849 7.57405 8.07732 7.84863 7.80273L10.5762 5.07617L11 4.65137L11.8486 5.5Z\"\n fill=\"currentColor\"\n />\n </svg>\n </button>\n {open\n ? (\n <div className={popupClass} role=\"listbox\" ref={popupRef}>\n {options.map((option, index) => (\n <div\n key={option.value}\n id={`${id}-o${index}`}\n role=\"option\"\n aria-selected={option.value === value}\n className={`${css.selectOption}${option.value === value ? ` ${css.selectOptionSelected}` : ''}${index === activeIndex && !closing ? ` ${css.selectOptionActive}` : ''}`}\n onClick={() => { commit(index) }}\n >\n {option.label}\n </div>\n ))}\n </div>\n )\n : null}\n </div>\n )\n}\n\n/**\n * A visible segmented group for a small set of mutually exclusive values.\n * Every option stays on screen, so inherit/on/off and short enum fields take\n * one click without opening a popup. The pressed option carries the group's\n * sliding highlight and `aria-pressed`; the group takes the field label as its\n * accessible name.\n */\nexport function SegmentField(props: {\n id: string\n label: string\n options: ReadonlyArray<SelectOption>\n value: string\n disabled: boolean\n invalid: boolean\n onEdit: (text: string) => void\n}) {\n return (\n <SegmentGroup\n id={props.id}\n role=\"group\"\n aria-label={props.label}\n aria-invalid={props.invalid || undefined}\n >\n {props.options.map((option, index) => {\n const active = option.value === props.value\n return (\n <button\n key={option.value}\n type=\"button\"\n className={css.segment}\n aria-pressed={active}\n disabled={props.disabled}\n data-active={active ? '' : undefined}\n data-segment-index={index}\n onClick={() => {\n if (!active) props.onEdit(option.value)\n }}\n >\n {option.label}\n </button>\n )\n })}\n </SegmentGroup>\n )\n}\n\n/** How a small single-choice field presents its options. */\nexport type FieldPresentation = 'select' | 'segment'\n\n/** A boolean field: 继承 / 开 / 关. */\nexport function BooleanField(props: FieldProps & {\n /** Copy for the inherit option. */\n inheritLabel: string\n /** Copy for the on option. */\n onLabel: string\n /** Copy for the off option. */\n offLabel: string\n /** Defaults to the visible segments: the three answers always fit on one row. */\n presentation?: FieldPresentation\n}) {\n const segmented = props.presentation !== 'select'\n return (\n <div className={css.field}>\n <div className={css.head}>\n {segmented\n ? <span className={css.label}>{props.label}</span>\n : <label className={css.label} htmlFor={props.id}>{props.label}</label>}\n {props.overridden\n ? (\n <span className={css.badges}>\n <span className={css.badge}>{props.overriddenLabel}</span>\n <button\n type=\"button\"\n className={css.reset}\n disabled={props.disabled}\n onClick={props.onReset}\n >\n {props.resetLabel}\n </button>\n </span>\n )\n : null}\n </div>\n {segmented\n ? (\n <SegmentField\n id={props.id}\n label={props.label}\n options={[\n { value: '', label: props.inheritLabel },\n { value: 'true', label: props.onLabel },\n { value: 'false', label: props.offLabel },\n ]}\n value={props.text}\n disabled={props.disabled}\n invalid={props.invalid}\n onEdit={props.onEdit}\n />\n )\n : (\n <SelectField\n id={props.id}\n options={[\n { value: '', label: props.inheritLabel },\n { value: 'true', label: props.onLabel },\n { value: 'false', label: props.offLabel },\n ]}\n value={props.text}\n disabled={props.disabled}\n invalid={props.invalid}\n onEdit={props.onEdit}\n />\n )}\n <p className={css.hint} title={props.hintTitle}>{props.hint}</p>\n </div>\n )\n}\n\n/** An enumerated field, selecting or segmenting its small choice set. */\nexport function ChoiceField(props: FieldProps & {\n /** Copy for the inherit option (draft text is the empty string). */\n inheritLabel: string\n /** Choices rendered in order; `value` is the draft/stored text. */\n choices: ReadonlyArray<{ value: string; label: string }>\n /**\n * Visible segmented options for a short fixed set; defaults to the compact\n * select, which also suits a list whose length follows the deployment.\n */\n presentation?: FieldPresentation\n}) {\n const segmented = props.presentation === 'segment'\n const options = [{ value: '', label: props.inheritLabel }, ...props.choices]\n return (\n <div className={css.field}>\n <div className={css.head}>\n {segmented\n ? <span className={css.label}>{props.label}</span>\n : <label className={css.label} htmlFor={props.id}>{props.label}</label>}\n {props.overridden\n ? (\n <span className={css.badges}>\n <span className={css.badge}>{props.overriddenLabel}</span>\n <button\n type=\"button\"\n className={css.reset}\n disabled={props.disabled}\n onClick={props.onReset}\n >\n {props.resetLabel}\n </button>\n </span>\n )\n : null}\n </div>\n {segmented\n ? (\n <SegmentField\n id={props.id}\n label={props.label}\n options={options}\n value={props.text}\n disabled={props.disabled}\n invalid={props.invalid}\n onEdit={props.onEdit}\n />\n )\n : (\n <SelectField\n id={props.id}\n options={options}\n value={props.text}\n disabled={props.disabled}\n invalid={props.invalid}\n onEdit={props.onEdit}\n />\n )}\n <p className={props.invalid ? css.invalid : css.hint} title={props.hintTitle}>\n {props.invalid ? props.invalidLabel : props.hint}\n </p>\n </div>\n )\n}\n\n/**\n * A boolean toggle drawn as a switch track, for a setting that is only on or\n * off and applies on flip. It is a real button with\n * `role=\"switch\"` and `aria-checked`, so keyboard and assistive activation\n * arrive as a click and the state is announced instead of inferred from a\n * checkbox tick.\n *\n * The thumb bounces across only once the reader has pressed this switch: the\n * press writes the mark that arms the bounce, so a page opening, a TAB\n * switching back or a value arriving from elsewhere draws every thumb at rest.\n */\nexport function ToggleSwitch(props: {\n /** Id of the element naming the switch (the card's title). */\n labelledBy?: string\n /** Accessible name when no element labels it. */\n ariaLabel?: string\n /** Current state. */\n checked: boolean\n /** Disables the switch while a write is in flight or the Host refuses writes. */\n disabled?: boolean\n /** Called with the requested next state. */\n onChange: (next: boolean) => void\n}) {\n const [moved, setMoved] = useState(false)\n return (\n <button\n type=\"button\"\n className={css.toggle}\n role=\"switch\"\n aria-checked={props.checked}\n aria-labelledby={props.labelledBy}\n aria-label={props.labelledBy === undefined ? props.ariaLabel : undefined}\n disabled={props.disabled}\n data-moved={moved ? '' : undefined}\n onClick={() => {\n setMoved(true)\n props.onChange(!props.checked)\n }}\n >\n <span className={css.toggleTrack}><span className={css.toggleThumb} /></span>\n </button>\n )\n}\n","/** Lightweight, static pet thumbnails built from the registry's existing assets. */\n\nimport type { PetDefinition } from '../registry.ts'\nimport sectionCss from './settings-section.module.css'\n\n/** Registry data needed by a thumbnail; older hosts may serve only id/name. */\nexport type PetPreviewDefinition = Pick<PetDefinition, 'id' | 'displayName'>\n & Partial<Pick<PetDefinition, 'renderer' | 'cell' | 'columns' | 'atlasRows' | 'atlasUrl' | 'frames2d'>>\n\nconst PREVIEW_LIMIT = 72\nconst DEFAULT_CELL = { width: 192, height: 208 }\n\n/**\n * Render the atlas's first sprite cell or a frames2d idle frame. Live2d and\n * incomplete legacy responses degrade to a text mark instead of a broken image.\n */\nexport function PetPreview(props: { pet: PetPreviewDefinition }) {\n const { pet } = props\n const renderer = pet.renderer ?? 'sprite2d'\n if (renderer === 'sprite2d' && pet.atlasUrl !== undefined) {\n const cell = pet.cell ?? DEFAULT_CELL\n const scale = Math.min(PREVIEW_LIMIT / cell.width, PREVIEW_LIMIT / cell.height)\n const width = Math.max(1, Math.round(cell.width * scale))\n const height = Math.max(1, Math.round(cell.height * scale))\n const columns = pet.columns ?? 8\n const rows = pet.atlasRows ?? 9\n return (\n <span className={sectionCss.previewFrame} aria-hidden=\"true\">\n <span\n className={sectionCss.previewAtlas}\n style={{\n width,\n height,\n backgroundImage: `url(\"${pet.atlasUrl}\")`,\n backgroundSize: `${columns * width}px ${rows * height}px`,\n }}\n />\n </span>\n )\n }\n const frame = renderer === 'frames2d'\n ? pet.frames2d?.tracks.idle?.frames[0] ?? pet.atlasUrl\n : undefined\n return (\n <span className={sectionCss.previewFrame} aria-hidden=\"true\">\n {frame === undefined\n ? <span className={sectionCss.previewFallback}>{pet.displayName.slice(0, 1)}</span>\n : <img className={sectionCss.previewImage} src={frame} alt=\"\" draggable={false} />}\n </span>\n )\n}\n","/**\n * Form model behind the plugin settings card. Every control applies itself:\n * a pick (a segment, a select option, a reset) writes the moment it is made,\n * and typed text writes once typing pauses or the reader leaves the field.\n * Between the edit and the write the edit is held here as a draft, so what is\n * on screen is exactly what the write will store; a write the Host refuses\n * puts a pick back to the stored value and keeps typed text for correcting.\n * Family-shared slice inlined into each plugin's client bundle.\n */\n\nimport type { ConfigForm, ConfigFormSnapshot } from '@deepseek-ai/dsh-client-ui-settings/client'\nimport type { SnapshotStore } from '@deepseek-ai/dsh-client-store'\nimport { createSnapshotStore } from '@deepseek-ai/dsh-client-store'\n\n/** The write one field's draft text performs when it is applied. */\nexport type FieldWrite =\n | { kind: 'set'; value: unknown }\n | { kind: 'clear' }\n\n/** How one field converts between its stored value and its draft text. */\nexport interface FieldSpec {\n /** Field name inside the namespace section. */\n field: string\n /**\n * How the reader enters a value, which decides when it is written: a `pick`\n * is a whole value at once and applies immediately; `type` is text arriving\n * a keystroke at a time and applies once typing pauses or the field is left.\n */\n entry: 'pick' | 'type'\n /**\n * Whether the Host treats this field as a secret and redacts its value from\n * the read-back (role('secret') in the section schema). Redacted secrets are\n * never compared against the draft on save: the Host strips them from every\n * wire view layer, so the settled snapshot carries nothing to read back. A\n * staged secret set is judged by the mutation settling; the rest of its\n * batch, when one exists, is still judged by read-back, and the atomic\n * mutation lands every write or none.\n */\n secret?: boolean\n /** Render a stored value as draft text; the empty string when the section carries none. */\n format: (value: unknown) => string\n /**\n * The write this draft text performs, or undefined when the text is not a\n * value this field accepts — which holds the draft unwritten rather than\n * discarding it.\n */\n parse: (text: string) => FieldWrite | undefined\n}\n\n/** One field as the card renders it. */\nexport interface FieldState {\n /** Draft text the control renders. */\n text: string\n /** Whether the field leaves (or will leave) a user-layer entry. */\n overridden: boolean\n /** Whether the draft is not a value this field accepts, which holds it unwritten. */\n invalid: boolean\n}\n\n/** Form state every plugin settings card shares. */\nexport interface CardShell {\n /** False while the namespace is still loading; the card renders nothing. */\n available: boolean\n /**\n * Whether the namespace is actually served to this client. False when the\n * Host deployment does not expose it (e.g. the owning plugin's settings\n * domain is not mounted): the card renders an explanation\n * instead of its form, so a missing namespace never looks like a missing\n * plugin.\n */\n exposed: boolean\n /** Whether the Host document accepts writes. */\n writable: boolean\n /** Whether the form holds drafts not yet written (typed text waiting for its pause). */\n dirty: boolean\n /** Whether any draft is invalid, which holds it unwritten. */\n invalid: boolean\n /** Whether a write is crossing the wire. */\n saving: boolean\n /** Whether the last write did not land; cleared by the next edit or write. */\n failed: boolean\n /**\n * The rejection code/message the Host returned for the last failed save,\n * surfaced next to the generic failure text. Undefined while no save has\n * failed (or the failure carried no server reason).\n */\n failedReason?: string\n}\n\n/** The write actions the card's slot entry injects. */\nexport interface CardActions {\n /** Take draft text for one field; a pick writes at once, typed text after a pause. */\n edit: (field: string, text: string) => void\n /** Clear one field at once, so it re-inherits the composition layer. */\n resetField: (field: string) => void\n /** Write every pending draft now (a text field's Enter or blur), then re-seed from what the Host accepted. */\n save: () => void\n /** Drop every pending draft, putting each control back to the stored value (a text field's Escape). */\n discard: () => void\n}\n\n/** How long typed text rests before it is written. */\nexport const TYPE_PAUSE_MS = 600\n\n/** One field's staged edit. */\ninterface StagedEdit {\n /** Draft text the control renders. */\n text: string\n /** True when this edit clears the field whatever text it shows. */\n clear: boolean\n}\n\n/** One staged edit resolved into the write a save performs. */\ninterface PlannedWrite {\n /** Field this entry writes. */\n field: string\n /** The durable write this entry performs, inside the save's one atomic mutation. */\n op: BatchedWrite\n /**\n * Read the settled snapshot back and report whether the Host holds this\n * write's effect. Undefined when the draft is not a value the field\n * accepts: there is nothing to write, and the entry blocks the save.\n */\n judge: (() => boolean) | undefined\n}\n\n/** One durable write inside the save's atomic form mutation. */\nexport interface BatchedWrite {\n /** Field this entry writes. */\n field: string\n /** set stores a value; unset drops the leaf. */\n op: 'set' | 'unset'\n /** Value for op set (absent for unset). */\n value?: unknown\n}\n\n/** Constraints a numeric field's accepted drafts must satisfy, mirroring the host schema. */\nexport interface NumberConstraints {\n /** The accepted value must be a whole number. */\n integer?: boolean\n /** The accepted value must be at least this. */\n min?: number\n}\n\n/** A whole- or decimal-number field. An empty draft clears the field; any other draft that is not a finite number within the constraints stays unwritten. */\nexport function numberField(field: string, constraints: NumberConstraints = {}): FieldSpec {\n const { integer = false, min } = constraints\n return {\n field,\n entry: 'type',\n format: value => typeof value === 'number' ? String(value) : '',\n parse: (text) => {\n const trimmed = text.trim()\n if (trimmed === '') return { kind: 'clear' }\n const parsed = Number(trimmed)\n if (!Number.isFinite(parsed)) return undefined\n if (integer && !Number.isInteger(parsed)) return undefined\n if (min !== undefined && parsed < min) return undefined\n return { kind: 'set', value: parsed }\n },\n }\n}\n\n/**\n * A free-text field. An empty draft clears the field. `entry` is `pick` when\n * the text arrives whole from a picker (a preset or a reasoning level).\n */\nexport function textField(field: string, entry: FieldSpec['entry'] = 'type'): FieldSpec {\n return {\n field,\n entry,\n format: value => typeof value === 'string' ? value : '',\n parse: (text) => {\n const trimmed = text.trim()\n return trimmed === '' ? { kind: 'clear' } : { kind: 'set', value: trimmed }\n },\n }\n}\n\n/**\n * A free-text field the Host treats as a secret and redacts from the read-back\n * (role('secret') in the section schema). The card still edits it like text,\n * but a save never compares the redacted value back: the staged set is judged\n * by the mutation settling (see {@link FieldSpec.secret}).\n */\nexport function secretField(field: string): FieldSpec {\n return { ...textField(field), secret: true }\n}\n\n/** A boolean field, edited through true/false draft text. */\nexport function booleanField(field: string): FieldSpec {\n return {\n field,\n entry: 'pick',\n format: value => typeof value === 'boolean' ? String(value) : '',\n parse: (text) => {\n const trimmed = text.trim()\n if (trimmed === '') return { kind: 'clear' }\n if (trimmed === 'true') return { kind: 'set', value: true }\n if (trimmed === 'false') return { kind: 'set', value: false }\n return undefined\n },\n }\n}\n\n/** An enumerated string field; only the listed choices are accepted. An empty draft clears the field. */\nexport function choiceField(field: string, choices: readonly string[]): FieldSpec {\n return {\n field,\n entry: 'pick',\n format: value => typeof value === 'string' && choices.includes(value) ? value : '',\n parse: (text) => {\n if (text === '') return { kind: 'clear' }\n return choices.includes(text) ? { kind: 'set', value: text } : undefined\n },\n }\n}\n\n/**\n * Applies one card's edits to one settings namespace as the reader makes them.\n *\n * The Host is the only authority on whether a value was accepted — its\n * validators own the constraints no schema can express — so the outcome is\n * read back from the section rather than predicted here. A write that did not\n * land puts each pick back to the stored value, the way a switch that could not\n * flip springs back, and keeps typed text so the reader can correct it instead\n * of retyping.\n */\nexport class CardForm<T> {\n private readonly specs: Map<string, FieldSpec>\n private readonly staged = new Map<string, StagedEdit>()\n private readonly listeners = new Set<() => void>()\n /** The form subscription installed in the constructor; released by dispose(). */\n private readonly disposeForm: () => void\n private disposed = false\n /** The pending write of typed text, waiting for typing to pause. */\n private typePause: ReturnType<typeof setTimeout> | undefined\n private saving = false\n /** A save asked for while one was in flight; it runs once the first settles (#1754). */\n private saveQueued = false\n private failed = false\n private failedReason: string | undefined\n\n /** @param scope - the bound configuration form for this card's namespace. */\n constructor(\n private readonly scope: ConfigForm<T>,\n specs: FieldSpec[],\n ) {\n this.specs = new Map(specs.map(spec => [spec.field, spec]))\n this.disposeForm = scope.subscribe(() => { this.publish() })\n }\n\n /**\n * Release the form subscription and every bound store listener. The card\n * must call this on teardown; later calls are no-ops.\n */\n dispose(): void {\n if (this.disposed) return\n this.disposed = true\n clearTimeout(this.typePause)\n this.disposeForm()\n this.listeners.clear()\n }\n\n /** Publish a projection of this form, rebuilt whenever the form or a draft changes. */\n bind<S>(project: () => S): SnapshotStore<S> {\n const store = createSnapshotStore(project())\n this.listeners.add(() => { store.set(project()) })\n return store\n }\n\n /** Read the card-level state: what the Host serves, and what is still waiting to be written. */\n shell(): CardShell {\n const snapshot = this.scope.getSnapshot()\n const plan = this.plan()\n return {\n available: snapshot.status !== 'loading',\n exposed: snapshot.status === 'ready',\n writable: snapshot.writable,\n dirty: plan.length > 0,\n invalid: plan.some(item => item.judge === undefined),\n saving: this.saving,\n failed: this.failed,\n ...this.failedReason === undefined ? {} : { failedReason: this.failedReason },\n }\n }\n\n /** Read one field's state from the effective section and its staged draft. */\n field(field: string): FieldState {\n const spec = this.specOf(field)\n const staged = this.staged.get(field)\n if (staged === undefined) {\n return { text: spec.format(this.sectionValue(field)), overridden: this.stored(field), invalid: false }\n }\n const write = staged.clear ? { kind: 'clear' as const } : spec.parse(staged.text)\n return {\n text: staged.text,\n overridden: write?.kind === 'set',\n invalid: write === undefined,\n }\n }\n\n /** The actions the card's slot registration injects. */\n actions(): CardActions {\n return {\n edit: (field, text) => { this.stage(field, { text, clear: false }) },\n resetField: (field) => {\n this.stage(field, { text: this.specOf(field).format(this.baseValue(field)), clear: true })\n },\n save: () => { this.applyNow() },\n discard: () => {\n clearTimeout(this.typePause)\n if (this.staged.size === 0 && !this.failed) return\n this.staged.clear()\n this.failed = false\n this.failedReason = undefined\n this.publish()\n },\n }\n }\n\n /**\n * Run one write, and re-run it once if another was asked for while this one\n * was still in flight.\n *\n * A write is a Host round trip that also drives the profile reconcile, and\n * the Host runs it inside one exclusive transaction. Answering an edit that\n * arrives mid-flight by returning immediately dropped it with no explanation\n * (#1754). Serializing instead means an edit made while another write is\n * still settling is written against the settled state.\n * @returns settlement after the mutation and the read-back.\n */\n async requestSave(): Promise<void> {\n if (this.saving) {\n this.saveQueued = true\n return\n }\n await this.save()\n if (!this.saveQueued) return\n this.saveQueued = false\n await this.requestSave()\n }\n\n /**\n * Write every valid draft in one atomic form mutation, then re-seed from\n * what the Host accepted. A draft the field does not accept stays on screen,\n * unwritten, without holding the others back.\n *\n * The batch rides one mutate, so cross-field validate hooks (baseURL+model)\n * judge it as a unit: the Host either applies every write or refuses the\n * batch. The form contract answers a refusal or a skipped write with `false`\n * (it recovers with a fresh Host view instead of throwing), so the outcome is\n * judged twice: the answer itself, and then the settled snapshot read back\n * one planned write at a time. One missed write fails the whole batch. A\n * transport that rejects instead (the dsh-web bridge controller on a dead\n * connection) reports through the same failure path with its rejection\n * message. A batch that did not land puts its picks and clears back to the\n * stored value and keeps its typed text, so the reader can correct it.\n * @returns settlement after the mutation and the read-back.\n */\n async save(): Promise<void> {\n const plan = this.plan()\n const valid = plan.filter((item): item is PlannedWrite & { judge: () => boolean } => item.judge !== undefined)\n if (valid.length === 0 || this.saving) return\n // Snapshot the staged entries this write carries, so an edit staged while\n // it is in flight (which replaces the same key) survives: only settle the\n // key when the entry is still the one this write started from.\n const pending = new Map<string, StagedEdit | undefined>()\n for (const item of valid) pending.set(item.field, this.staged.get(item.field))\n this.saving = true\n this.failed = false\n this.failedReason = undefined\n this.publish()\n // One atomic namespace mutation: the form contract takes ordered path\n // operations, so the whole staged batch is validated, persisted, and\n // recovered together — either every write lands or none does.\n const ops: Array<{ op: 'set'; path: string[]; value: string | number | boolean } | { op: 'unset'; path: string[] }> = valid.map(item => item.op.op === 'set'\n ? { op: 'set', path: [item.field], value: (item.op as { value: string | number | boolean }).value }\n : { op: 'unset', path: [item.field] })\n let failedReason: string | undefined\n let accepted = false\n try {\n accepted = await this.scope.mutate(ops)\n } catch (error) {\n failedReason = error instanceof Error ? error.message : String(error)\n }\n // `false` is the contract's refusal/skip answer, and the form still\n // resolves after a refusal (it recovers with a fresh view), so the answer\n // alone is not enough: judge every planned write against the settled\n // snapshot as well. The mutation is atomic, so one missed write fails the\n // whole save and keeps the drafts.\n const landed = accepted && failedReason === undefined && valid.every(item => item.judge())\n for (const [field, before] of pending) {\n if (this.staged.get(field) !== before) continue\n if (landed || before === undefined || before.clear || this.specOf(field).entry === 'pick') this.staged.delete(field)\n }\n this.saving = false\n this.failed = !landed\n // A refused or unlanded batch carries no server reason: the card surfaces\n // its generic failure copy; a rejecting transport (the bridge) adds its\n // message.\n this.failedReason = failedReason\n this.publish()\n }\n\n /**\n * Every staged edit a write would carry. An entry whose draft is not a value\n * its field accepts carries no write: the form is still dirty, and the draft\n * stays on screen rather than being dropped. A staged edit that matches the\n * effective section is not a write at all.\n * @returns the planned writes, in the order the fields were staged.\n */\n private plan(): PlannedWrite[] {\n const plan: PlannedWrite[] = []\n for (const [field, staged] of this.staged) {\n const spec = this.specOf(field)\n if (staged.clear) {\n if (this.stored(field)) plan.push({ field, op: { field, op: 'unset' }, judge: () => this.landedUnset(field) })\n continue\n }\n if (staged.text === spec.format(this.sectionValue(field))) continue\n const write = spec.parse(staged.text)\n if (write === undefined) plan.push({ field, op: { field, op: 'unset' }, judge: undefined })\n else if (write.kind === 'clear') plan.push({ field, op: { field, op: 'unset' }, judge: () => this.landedUnset(field) })\n else plan.push({ field, op: { field, op: 'set', value: write.value }, judge: () => this.landedSet(field, write.value) })\n }\n return plan\n }\n\n /**\n * Read-back judgment for a planned set: the user layer must hold the\n * intended value once the mutation has settled.\n */\n private landedSet(field: string, value: unknown): boolean {\n // A redacted secret never appears in any wire view layer: the Host strips\n // role('secret') fields and reports them through a sidecar the form\n // snapshot does not expose, so there is nothing to compare the draft\n // against. Settling is the only signal the form has; the rest of the\n // batch, when one exists, still carries the atomic verdict by read-back.\n if (this.specOf(field).secret) return true\n return this.userLayer()?.[field] === value\n }\n\n /**\n * Read-back judgment for a planned unset: the field must be gone from the\n * user layer once the mutation has settled.\n */\n private landedUnset(field: string): boolean {\n return !this.stored(field)\n }\n\n /**\n * Take one edit and schedule its write: a pick or a clear is written now,\n * typed text once typing has rested for TYPE_PAUSE_MS.\n */\n private stage(field: string, edit: StagedEdit): void {\n this.staged.set(field, edit)\n this.failed = false\n this.failedReason = undefined\n this.publish()\n if (edit.clear || this.specOf(field).entry === 'pick') {\n this.applyNow()\n return\n }\n clearTimeout(this.typePause)\n this.typePause = setTimeout(() => { this.applyNow() }, TYPE_PAUSE_MS)\n }\n\n /** Write every pending draft now, taking the place of a waiting pause. */\n private applyNow(): void {\n clearTimeout(this.typePause)\n this.typePause = undefined\n if (this.disposed) return\n void this.requestSave()\n }\n\n private specOf(field: string): FieldSpec {\n const spec = this.specs.get(field)\n // Every call site names a field this card declared; a missing one is a\n // wiring mistake that must not degrade into a silently inert control.\n if (spec === undefined) throw new Error(`settings card has no field ${field}`)\n return spec\n }\n\n private snapshotOf(): ConfigFormSnapshot<T> {\n return this.scope.getSnapshot()\n }\n\n private sectionValue(field: string): unknown {\n return (this.snapshotOf().value as Record<string, unknown> | undefined)?.[field]\n }\n\n private baseValue(field: string): unknown {\n return (this.snapshotOf().base as Record<string, unknown> | undefined)?.[field]\n }\n\n private userLayer(): Record<string, unknown> | undefined {\n return this.snapshotOf().user as Record<string, unknown> | undefined\n }\n\n private stored(field: string): boolean {\n const user = this.userLayer()\n return user !== undefined && Object.hasOwn(user, field)\n }\n\n private publish(): void {\n for (const listener of this.listeners) listener()\n }\n}\n","/**\n * The pet settings card: pet selection plus display layout, staged over the\n * 'pet' profile entry's own configuration (a plugin's settings ARE its Cordis\n * Config since 0.1.7, so the Host serves one form per profile entry).\n * Rendered as an always-open first-level settings page; the section wrapper\n * below mounts it as the content of the top-level 'settings.section' nav\n * entry. The petId choices come from the registry endpoint ('/api/pet/pets') —\n * the same list the sprite renders from — so the card carries no per-pet\n * knowledge.\n */\n\nimport { useEffect, type ReactNode } from 'react'\nimport type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { ConfigForm } from '@deepseek-ai/dsh-client-ui-settings/client'\nimport type { SnapshotStore } from '@deepseek-ai/dsh-client-store'\n// Type-only: pulls the settings-surface SlotMap merge (the 'settings.section' entry).\nimport type {} from '@deepseek-ai/dsh-client-ui-settings/client'\nimport type {} from './web-extension-contract.ts'\nimport { PluginSettingsCard, ValueField, BooleanField, ChoiceField, ToggleSwitch } from './PluginSettingsCard.tsx'\nimport { PetPreview, type PetPreviewDefinition } from './PetPreview.tsx'\nimport { CardForm, booleanField, choiceField, numberField, type CardActions, type CardShell, type FieldState as CardFieldState } from './settings-form.ts'\nimport sectionCss from './settings-section.module.css'\n\n/** The pet's settings fields this card edits (the namespace's full schema). */\nexport interface PetSettings {\n /** Master switch for the plugin. */\n enabled?: boolean\n /** Master switch. */\n visible?: boolean\n /** Scale of the rendered pet in px (sprite cell height). */\n size?: number\n /** Horizontal inset from the viewport right edge, px. */\n right?: number\n /** Vertical inset from the viewport bottom edge, px. */\n bottom?: number\n /** Bubble typography multiplier on the automatic size following (#1549). */\n bubbleScale?: number\n /** Selected pet id (a registry entry). */\n petId?: string\n /** Status-decoration master switch (pet-center M5, #567). */\n decorationEnabled?: boolean\n /** Whether the pet's own session/status bubbles render (issue #6). */\n statusBubbles?: string\n}\n\n/** What the pet settings card renders. */\nexport interface PetSettingsCardState extends CardShell {\n /** The aggregate shell has no Host settings form; pet selection uses its own persisted API. */\n petSelectionFallback: boolean\n /** Plugin master switch. */\n enabled: CardFieldState\n /** Master switch. */\n visible: CardFieldState\n /** Pet scale. */\n size: CardFieldState\n /** Right inset. */\n right: CardFieldState\n /** Bottom inset. */\n bottom: CardFieldState\n /** Bubble typography multiplier. */\n bubbleScale: CardFieldState\n /** Selected pet. */\n petId: CardFieldState\n /** Status-decoration master switch. */\n decorationEnabled: CardFieldState\n /** Whether the pet's own session/status bubbles render. */\n statusBubbles: CardFieldState\n /** Pet choices (registry ids + display names), loaded from the host. */\n petChoices: readonly { value: string; label: string }[]\n /** The same registry entries with the visual data their thumbnails need. */\n petPreviews: readonly PetPreviewDefinition[]\n}\n\n/** The registration-side face the card's slot entry injects. */\nexport interface PetSettingsCardFace extends CardActions {\n hooks: {\n /** Card snapshot bound by the renderer as usePetSettingsCard. */\n petSettingsCard: SnapshotStore<PetSettingsCardState>\n }\n /**\n * Ask the card for the pet registry again. The pet API only exists while the\n * plugin is enabled, so opening the master switch has to be able to re-ask\n * instead of leaving the picker empty until the page reloads.\n */\n refreshPets(): void\n}\n\n/**\n * The bubble modes this card can write, in render order. Mirrors the host\n * schema's union (see PetStatusBubbleMode); the browser half never imports the\n * host module for a value, so the accepted set is spelled here as literals.\n */\nconst STATUS_BUBBLE_CHOICES = ['auto', 'off'] as const\n\n/**\n * The spans the coarse sliders cover, spelled as literals for the same reason.\n * Size and bubble scale are the schema's own bounds (src/persist.ts); the\n * insets reach the schema's far end only by typing, so their slider covers the\n * distances a window can show.\n */\nexport const SIZE_RANGE = { min: 32, max: 1024, step: 1 }\nexport const INSET_RANGE = { min: 0, max: 1000, step: 1 }\nexport const BUBBLE_SCALE_RANGE = { min: 0.5, max: 2, step: 0.05 }\n\n/** One registry choice as served by '/api/pet/pets'. */\ntype PetChoice = PetPreviewDefinition\n\n/** Fetch the registry list (the same data the sprite renders from). */\nasync function fetchPetChoices(): Promise<PetChoice[]> {\n // Never from cache: the list is exactly what changes when the plugin is\n // switched on (the API only exists then) or a pet is installed.\n const response = await fetch('/api/pet/pets', { cache: 'no-store' })\n if (!response.ok) throw new Error('pet pets failed: ' + response.status)\n return (await response.json()) as PetChoice[]\n}\n\n/** The persisted state the fallback mirrors: the selection and its visibility. */\ninterface PetState {\n /** Selected registry id. */\n petId: string\n /** Whether the pet is currently rendered. */\n visible: boolean\n}\n\n/** Read the selection and visibility from the same persisted state the pet renders. */\nasync function fetchPetState(): Promise<PetState> {\n const response = await fetch('/api/pet/state')\n if (!response.ok) throw new Error('pet state failed: ' + response.status)\n const body = (await response.json()) as { pet?: { id?: unknown }; display?: { visible?: unknown } }\n if (typeof body.pet?.id !== 'string') throw new Error('pet state has no selected pet')\n // A Host without the display block predates the visibility switch; the pet shows.\n return { petId: body.pet.id, visible: body.display?.visible !== false }\n}\n\n/** Bridges the 'pet' scope onto the card's staged form. */\nexport class PetSettingsCardController {\n private readonly form: CardForm<PetSettings>\n private readonly store: SnapshotStore<PetSettingsCardState>\n // The choice list rides a mutable array shared with the choiceField spec,\n // so loading the registry re-validates and re-formats the petId field\n // without rebuilding the form.\n private readonly petChoices: string[] = []\n private readonly petLabels = new Map<string, string>()\n private petPreviews: PetPreviewDefinition[] = []\n private selectedPetId: string | undefined\n private selectedVisible: boolean | undefined\n private stagedPetId: string | undefined\n private stagedVisible: boolean | undefined\n private savingPet = false\n /** A fallback pick made while a write was in flight. */\n private fallbackQueued = false\n private petSaveFailed = false\n private loaded = false\n /** A registry request is in flight. */\n private loading = false\n private attempts = 0\n private disposed = false\n /** Pending deferred-load or retry timer; cancelled by dispose(). */\n private pendingTimer: number | undefined\n\n /** @param scope - the bound configuration form for the 'pet' entry. */\n constructor(scope: ConfigForm<PetSettings>) {\n this.form = new CardForm(scope, [\n booleanField('enabled'),\n booleanField('decorationEnabled'),\n // The bubble switch is a two-value mode, not a boolean: 'off' is the\n // opt-out, and a future mode (say, one that keeps only the current\n // session's bubble) has to be able to join the same field without\n // breaking every settings document already written.\n choiceField('statusBubbles', STATUS_BUBBLE_CHOICES),\n booleanField('visible'),\n numberField('size'),\n numberField('right'),\n numberField('bottom'),\n numberField('bubbleScale'),\n choiceField('petId', this.petChoices),\n ])\n this.store = this.form.bind(() => this.projection())\n // Client plugins are applied synchronously during shell startup. Defer\n // the first registry request until that pass completes so transport\n // plugins (notably remote-web-ui on a paired non-loopback origin) can\n // install their fetch channel before /api/pet/pets is issued.\n this.pendingTimer = window.setTimeout(() => {\n this.pendingTimer = undefined\n if (this.disposed) return\n void this.loadPets()\n void this.loadPetState()\n }, 0)\n }\n\n /** Resolve the registry choices once (retried a few times on failure). */\n private async loadPets(): Promise<void> {\n if (this.loaded || this.disposed || this.loading) return\n this.loading = true\n try {\n const list = await fetchPetChoices()\n if (this.disposed) return\n this.petChoices.splice(0, this.petChoices.length, ...list.map(choice => choice.id))\n this.petPreviews = list\n for (const choice of list) this.petLabels.set(choice.id, choice.displayName)\n this.loaded = true\n this.store.set(this.projection())\n } catch {\n if (this.disposed) return\n this.attempts += 1\n if (this.attempts < 3) {\n this.pendingTimer = window.setTimeout(() => {\n this.pendingTimer = undefined\n if (this.disposed) return\n void this.loadPets()\n }, 3000)\n }\n } finally {\n this.loading = false\n }\n }\n\n /**\n * Re-read the registry on demand. The pet API is registered only while the\n * plugin is enabled, so the first read can fail while the master switch is\n * off; this lets the card try again the moment the switch opens instead of\n * waiting for a page reload.\n */\n refreshPets(): void {\n if (this.disposed || this.loading) return\n this.loaded = false\n this.attempts = 0\n void this.loadPets()\n }\n\n private async loadPetState(): Promise<void> {\n try {\n const state = await fetchPetState()\n if (this.disposed) return\n this.selectedPetId = state.petId\n this.selectedVisible = state.visible\n this.store.set(this.projection())\n } catch {\n // The Host form remains the authority when it is available. An absent\n // pet API leaves the fallback unavailable rather than inventing state.\n }\n }\n\n private fallback(): boolean {\n const shell = this.form.shell()\n return shell.available && !shell.exposed && this.selectedPetId !== undefined\n }\n\n /**\n * The visibility the fallback switch renders: the staged draft when the user\n * moved it, the persisted value otherwise. There is no user layer to override\n * here, so the field is never marked overridden.\n */\n private fallbackVisible(): CardFieldState {\n const value = this.stagedVisible ?? this.selectedVisible\n return { text: value === undefined ? '' : String(value), overridden: false, invalid: false }\n }\n\n /**\n * Persist the staged selection and visibility through the pet API — the only\n * writer available when the aggregate shell serves this card, since there is\n * no Host settings form to mutate — then confirm the read-back before the\n * drafts are cleared. A refused write puts both picks back to what the pet\n * persisted. A pick made while a write is in flight runs once it settles.\n */\n private async saveFallback(): Promise<void> {\n const petId = this.stagedPetId\n const visible = this.stagedVisible\n if (this.savingPet) {\n this.fallbackQueued = true\n return\n }\n if (petId === undefined && visible === undefined) return\n if (petId !== undefined && !this.petChoices.includes(petId)) return\n this.savingPet = true\n this.petSaveFailed = false\n this.store.set(this.projection())\n try {\n if (petId !== undefined) {\n const response = await fetch('/api/pet/set-pet', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ petId }),\n })\n const result = (await response.json()) as { ok?: boolean; petId?: string }\n if (!response.ok || result.ok !== true || result.petId !== petId) {\n throw new Error('pet selection was not persisted')\n }\n }\n if (visible !== undefined) {\n const response = await fetch('/api/pet/set-visible', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ visible }),\n })\n if (!response.ok) throw new Error('pet visibility was not persisted')\n }\n const persisted = await fetchPetState()\n if (petId !== undefined && persisted.petId !== petId) throw new Error('pet selection was not persisted')\n if (visible !== undefined && persisted.visible !== visible) throw new Error('pet visibility was not persisted')\n this.selectedPetId = persisted.petId\n this.selectedVisible = persisted.visible\n if (this.stagedPetId === petId) this.stagedPetId = undefined\n if (this.stagedVisible === visible) this.stagedVisible = undefined\n } catch {\n this.petSaveFailed = true\n if (this.stagedPetId === petId) this.stagedPetId = undefined\n if (this.stagedVisible === visible) this.stagedVisible = undefined\n } finally {\n this.savingPet = false\n if (!this.disposed) this.store.set(this.projection())\n }\n if (this.fallbackQueued && !this.disposed) {\n this.fallbackQueued = false\n await this.saveFallback()\n }\n }\n\n private projection(): PetSettingsCardState {\n const fallback = this.fallback()\n const shell = this.form.shell()\n const configuredPet = this.form.field('petId')\n return {\n ...shell,\n ...(fallback ? {\n exposed: true,\n writable: true,\n dirty: this.stagedPetId !== undefined && this.stagedPetId !== this.selectedPetId\n || this.stagedVisible !== undefined && this.stagedVisible !== this.selectedVisible,\n invalid: this.stagedPetId !== undefined && !this.petChoices.includes(this.stagedPetId),\n saving: this.savingPet,\n failed: this.petSaveFailed,\n failedReason: undefined,\n } : {}),\n petSelectionFallback: fallback,\n enabled: this.form.field('enabled'),\n decorationEnabled: this.form.field('decorationEnabled'),\n statusBubbles: this.form.field('statusBubbles'),\n visible: fallback ? this.fallbackVisible() : this.form.field('visible'),\n size: this.form.field('size'),\n right: this.form.field('right'),\n bottom: this.form.field('bottom'),\n bubbleScale: this.form.field('bubbleScale'),\n petId: fallback\n ? { text: this.stagedPetId ?? this.selectedPetId ?? '', overridden: false, invalid: this.stagedPetId !== undefined && !this.petChoices.includes(this.stagedPetId) }\n : configuredPet.text === '' && this.selectedPetId !== undefined\n ? { ...configuredPet, text: this.selectedPetId }\n : configuredPet,\n petChoices: this.petChoices.map(id => ({ value: id, label: this.petLabels.get(id) ?? id })),\n petPreviews: this.petPreviews,\n }\n }\n\n /**\n * Build the face the card's slot registration injects.\n * @returns the card's snapshot and its form actions.\n */\n inject(): PetSettingsCardFace {\n const actions = this.form.actions()\n return {\n hooks: { petSettingsCard: this.store },\n // The fallback's two fields are both picks, so each is written through\n // the pet API the moment it is made, as the form writes its own picks.\n edit: (field, value) => {\n if (!this.fallback()) return actions.edit(field, value)\n if (field === 'petId') this.stagedPetId = value === '' ? undefined : value\n else if (field === 'visible') this.stagedVisible = value === '' ? undefined : value === 'true'\n else return\n this.petSaveFailed = false\n this.store.set(this.projection())\n void this.saveFallback()\n },\n resetField: (field) => {\n if (!this.fallback()) return actions.resetField(field)\n if (field === 'petId') this.stagedPetId = undefined\n else if (field === 'visible') this.stagedVisible = undefined\n else return\n this.petSaveFailed = false\n this.store.set(this.projection())\n },\n save: () => { if (this.fallback()) void this.saveFallback(); else actions.save() },\n discard: () => {\n if (!this.fallback()) return actions.discard()\n this.stagedPetId = undefined\n this.stagedVisible = undefined\n this.petSaveFailed = false\n this.store.set(this.projection())\n },\n refreshPets: () => { this.refreshPets() },\n }\n }\n\n /**\n * Release the card's scope subscription, bound stores and pending load\n * timers; the slot disposer calls this on teardown.\n */\n dispose(): void {\n if (this.disposed) return\n this.disposed = true\n if (this.pendingTimer !== undefined) {\n window.clearTimeout(this.pendingTimer)\n this.pendingTimer = undefined\n }\n this.form.dispose()\n }\n}\n\n/** Props the renderer binds for the pet settings card. */\nexport type PetSettingsCardProps =\n PropsLocale<'pet'>\n & InjectFace<PetSettingsCardFace>\n\n/**\n * Render the pet settings card.\n * @param props - locale copy, the card snapshot, and its form actions.\n * @returns the card.\n */\nexport function PetSettingsCard(props: PetSettingsCardProps) {\n const { t } = props\n const state = props.usePetSettingsCard(snapshot => snapshot)\n const disabled = !state.writable\n // The registry is read once, when the plugin starts; the pet API that serves\n // it exists only while the master switch is on. A card that opened empty\n // therefore asks again as soon as the switch is on, instead of leaving the\n // picker blank until the page reloads (the deferred reads had already spent\n // their retries while the API was absent).\n const enabled = state.enabled.text !== 'false'\n const hasChoices = state.petPreviews.length > 0\n const { refreshPets } = props\n useEffect(() => {\n if (enabled && !hasChoices) refreshPets()\n }, [enabled, hasChoices, refreshPets])\n const fieldProps = {\n overriddenLabel: t('settings.overridden'),\n resetLabel: t('settings.reset'),\n invalidLabel: t('settings.invalidNumber'),\n disabled,\n presentation: 'segment' as const,\n }\n // The master switch sits in the header, as the Workshop and Usage pages\n // carry theirs; the fallback has no Host form to write it through.\n const enabledSwitch = state.petSelectionFallback\n ? undefined\n : (\n <ToggleSwitch\n labelledBy=\"settings-pet-title\"\n checked={state.enabled.text !== 'false'}\n disabled={disabled}\n onChange={(next) => { props.edit('enabled', String(next)) }}\n />\n )\n return (\n <PluginSettingsCard\n t={t}\n titleKey=\"settings.title\"\n titleId=\"settings-pet-title\"\n descriptionKey=\"settings.description\"\n descriptionNode={state.petSelectionFallback ? t('settings.petHint') : undefined}\n headerAction={enabledSwitch}\n state={state}\n onSave={props.save}\n onDiscard={props.discard}\n alwaysOpen\n >\n <div className={sectionCss.settingsLayout}>\n <section className={sectionCss.selectionGroup}>\n <div className={sectionCss.groupHeader}>\n <h3 className={sectionCss.groupTitle} id=\"settings-pet-selection-title\">{t('settings.pet')}</h3>\n {state.petId.overridden\n ? (\n <button\n type=\"button\"\n className={sectionCss.textAction}\n disabled={disabled}\n onClick={() => { props.resetField('petId') }}\n >\n {t('settings.reset')}\n </button>\n )\n : null}\n </div>\n <div\n id=\"settings-pet-pet\"\n className={sectionCss.petGrid}\n role=\"group\"\n aria-labelledby=\"settings-pet-selection-title\"\n >\n {state.petPreviews.map(pet => {\n const selected = state.petId.text === pet.id\n return (\n <button\n key={pet.id}\n type=\"button\"\n className={selected ? `${sectionCss.petChoice} ${sectionCss.petChoiceSelected}` : sectionCss.petChoice}\n aria-pressed={selected}\n title={pet.displayName}\n disabled={disabled}\n onClick={() => { props.edit('petId', pet.id) }}\n >\n <PetPreview pet={pet} />\n <span className={sectionCss.petChoiceLabel}>{pet.displayName}</span>\n </button>\n )\n })}\n </div>\n <p className={state.petId.invalid ? sectionCss.invalid : sectionCss.groupHint}>\n {state.petId.invalid ? t('settings.invalidNumber') : t('settings.petHint')}\n </p>\n </section>\n\n <div className={sectionCss.settingsColumn}>\n <section className={sectionCss.settingsGroup}>\n <div className={sectionCss.groupHeader}>\n <h3 className={sectionCss.groupTitle} id=\"settings-pet-display-title\">{t('settings.displayGroup')}</h3>\n </div>\n <div className={sectionCss.fields}>\n <BooleanField\n id=\"settings-pet-visible\"\n label={t('settings.visible')}\n hint={t('settings.visibleHint')}\n inheritLabel={t('settings.inherit')}\n onLabel={t('settings.on')}\n offLabel={t('settings.off')}\n {...fieldProps}\n {...state.visible}\n onEdit={(text) => { props.edit('visible', text) }}\n onReset={() => { props.resetField('visible') }}\n />\n {state.petSelectionFallback ? null : <ValueField\n id=\"settings-pet-size\"\n label={t('settings.size')}\n hint={t('settings.sizeHint')}\n numeric\n range={SIZE_RANGE}\n {...fieldProps}\n {...state.size}\n onEdit={(text) => { props.edit('size', text) }}\n onReset={() => { props.resetField('size') }}\n />}\n {state.petSelectionFallback ? null : <ValueField\n id=\"settings-pet-right\"\n label={t('settings.right')}\n hint={t('settings.rightHint')}\n numeric\n range={INSET_RANGE}\n {...fieldProps}\n {...state.right}\n onEdit={(text) => { props.edit('right', text) }}\n onReset={() => { props.resetField('right') }}\n />}\n {state.petSelectionFallback ? null : <ValueField\n id=\"settings-pet-bottom\"\n label={t('settings.bottom')}\n hint={t('settings.bottomHint')}\n numeric\n range={INSET_RANGE}\n {...fieldProps}\n {...state.bottom}\n onEdit={(text) => { props.edit('bottom', text) }}\n onReset={() => { props.resetField('bottom') }}\n />}\n </div>\n </section>\n\n {state.petSelectionFallback ? null : (\n <section className={sectionCss.settingsGroup}>\n <div className={sectionCss.groupHeader}>\n <h3 className={sectionCss.groupTitle} id=\"settings-pet-behavior-title\">{t('settings.bubbleGroup')}</h3>\n </div>\n <div className={sectionCss.fields}>\n <BooleanField\n id=\"settings-pet-decoration\"\n label={t('settings.decoration')}\n hint={t('settings.decorationHint')}\n inheritLabel={t('settings.inherit')}\n onLabel={t('settings.on')}\n offLabel={t('settings.off')}\n {...fieldProps}\n {...state.decorationEnabled}\n onEdit={(text) => { props.edit('decorationEnabled', text) }}\n onReset={() => { props.resetField('decorationEnabled') }}\n />\n <ChoiceField\n id=\"settings-pet-status-bubbles\"\n label={t('settings.statusBubbles')}\n hint={t('settings.statusBubblesHint')}\n inheritLabel={t('settings.inherit')}\n {...fieldProps}\n {...state.statusBubbles}\n choices={[\n { value: STATUS_BUBBLE_CHOICES[0], label: t('settings.on') },\n { value: STATUS_BUBBLE_CHOICES[1], label: t('settings.off') },\n ]}\n onEdit={(text) => { props.edit('statusBubbles', text) }}\n onReset={() => { props.resetField('statusBubbles') }}\n />\n <ValueField\n id=\"settings-pet-bubble-scale\"\n label={t('settings.bubbleScale')}\n hint={t('settings.bubbleScaleHint')}\n numeric\n range={BUBBLE_SCALE_RANGE}\n {...fieldProps}\n {...state.bubbleScale}\n onEdit={(text) => { props.edit('bubbleScale', text) }}\n onReset={() => { props.resetField('bubbleScale') }}\n />\n </div>\n </section>\n )}\n </div>\n </div>\n </PluginSettingsCard>\n )\n}\n\n/** Props the settings section binds for the pet card page. */\nexport type PetSettingsSectionProps =\n (PropsRuntime<'settings.section'> | PropsRuntime<'web-ui.extension'>)\n & PropsLocale<'pet'>\n & InjectFace<PetSettingsCardFace>\n\n/** Render the pet settings card as a first-level settings page. */\nexport function PetSettingsSection(props: PetSettingsSectionProps): ReactNode {\n const { t, usePetSettingsCard, save, discard, edit, resetField, refreshPets } = props\n return (\n <ul className={sectionCss.sectionList} data-dsh-plugin=\"pet\" data-dsh-part=\"panel\">\n <PetSettingsCard\n t={t}\n usePetSettingsCard={usePetSettingsCard}\n save={save}\n discard={discard}\n edit={edit}\n resetField={resetField}\n refreshPets={refreshPets}\n />\n </ul>\n )\n}\n","/**\n * dsh-pet locale dictionaries (zh/en).\n * @module @linxin666/dsh-pet/client/locales\n */\n\n/** Dictionary namespace this package registers. */\nexport const NS = 'pet'\n\n/** Chinese copy. */\nexport const zh = {\n 'pet.feed': '喂食',\n 'pet.hide': '隐藏',\n 'pet.rename': '改名',\n 'pet.confirm': '确定',\n 'pet.namePlaceholder': '输入新名字',\n 'pet.summon': '召唤{name}',\n 'pet.rank': '亲密度 {rank}',\n 'pet.rank.name.幼鲸': '幼鲸',\n 'pet.rank.name.伙伴': '伙伴',\n 'pet.rank.name.挚友': '挚友',\n 'pet.rank.name.深海羁绊': '深海羁绊',\n 'pet.rank.name.心有灵犀': '心有灵犀',\n 'pet.rank.name.传说羁绊': '传说羁绊',\n 'pet.rank.name.神话羁绊': '神话羁绊',\n 'pet.rank.name.永恒之契': '永恒之契',\n 'pet.rank.name.鲸生共渡': '鲸生共渡',\n 'pet.points': '{points} 点',\n 'pet.treats': '小鱼干 ×{n}',\n 'pet.state.loading': '宠物正在赶来…',\n 'pet.state.error': '宠物迷路了(连接失败)',\n 'pet.renderer.unavailable': '这只宠物需要的渲染器({renderer})在当前版本不可用。',\n 'pet.live2d.core-missing': 'Live2D 核心未安装:请把官方 live2dcubismcore.min.js 放入 $DSH_HOME/pets/.runtime/ 后刷新(步骤见宠物插件 README)。',\n 'pet.live2d.vendor-missing': 'Live2D 组件缺失,请升级宠物插件。',\n 'pet.live2d.load-failed': 'Live2D 模型加载失败,请检查该宠物目录的完整性。',\n 'pet.openSessionHint': '点击跳转到对应会话',\n // 玩法 HUD(miku-pet 泛化:属性条 / 打工 / 睡觉 / 商店;统一小鱼干经济)。\n 'pet.gameplay.menu': '玩法',\n 'pet.gameplay.work': '打工',\n 'pet.gameplay.stopWork': '收工',\n 'pet.gameplay.sleep': '休息',\n 'pet.gameplay.wake': '起床',\n 'pet.gameplay.shop': '商店',\n 'pet.gameplay.skin': '皮肤',\n 'pet.gameplay.skinDefault': '默认',\n 'pet.gameplay.back': '返回',\n 'pet.gameplay.buy': '购买',\n 'pet.gameplay.insufficient': '{currency}不足',\n 'pet.gameplay.prize': '中奖 +{amount} {currency}',\n 'pet.gameplay.working': '打工中',\n 'pet.gameplay.sleeping': '睡觉中',\n 'pet.gameplay.stat.hunger': '饱食',\n 'pet.gameplay.stat.mood': '心情',\n 'pet.gameplay.stat.energy': '精力',\n 'pet.gameplay.stat.affection': '好感',\n 'pet.gameplay.currency.treats': '小鱼干',\n 'pet.moreSessions': '展开其余 {n} 个会话的气泡',\n 'pet.collapseSessions': '收起会话气泡',\n // 一级设置页(settings.section 席位)。\n 'settings.title': '宠物',\n 'settings.description': '选一只宠物,摆在页面的角落里。',\n 'settings.pet': '宠物',\n 'settings.petHint': '名字跟着宠物走,在宠物面板里改。',\n 'settings.displayGroup': '显示',\n 'settings.bubbleGroup': '气泡',\n 'settings.decoration': '状态装饰',\n 'settings.decorationHint': '气泡里带上喷水鲸鱼这类装饰。',\n 'settings.statusBubbles': '状态气泡',\n 'settings.statusBubblesHint': '宠物报告正在思考、正在用哪个工具。',\n 'settings.visible': '显示宠物',\n 'settings.visibleHint': '藏起来后可在输入区召唤回来。',\n 'settings.size': '大小(px)',\n 'settings.sizeHint': '宠物的高度。',\n 'settings.bubbleScale': '气泡字号',\n 'settings.bubbleScaleHint': '字号随宠物缩放,再乘上这个倍数。',\n 'settings.right': '距右侧(px)',\n 'settings.rightHint': '离窗口右边的距离。',\n 'settings.bottom': '距底部(px)',\n 'settings.bottomHint': '离窗口底边的距离。',\n 'settings.inherit': '默认',\n 'settings.on': '开',\n 'settings.off': '关',\n 'settings.overridden': '已修改',\n 'settings.reset': '恢复默认',\n 'settings.notExposed': '这个版本的 DSH 没有开放宠物的设置,可直接编辑 $DSH_HOME/settings.yaml。',\n 'settings.readOnly': '设置只读。',\n 'settings.expand': '展开设置',\n 'settings.collapse': '收起设置',\n 'settings.saveFailed': '没有保存成功,输入的值还留着。',\n 'settings.invalidNumber': '填一个数字,留空用默认值。',\n} as const\n\n/** English copy. */\nexport const en = {\n 'pet.feed': 'Feed',\n 'pet.hide': 'Hide',\n 'pet.rename': 'Rename',\n 'pet.confirm': 'OK',\n 'pet.namePlaceholder': 'Enter a new name',\n 'pet.summon': 'Summon {name}',\n 'pet.rank': 'Affinity {rank}',\n 'pet.rank.name.幼鲸': 'Baby Whale',\n 'pet.rank.name.伙伴': 'Companion',\n 'pet.rank.name.挚友': 'Close Friend',\n 'pet.rank.name.深海羁绊': 'Deep Sea Bond',\n 'pet.rank.name.心有灵犀': 'Kindred Spirit',\n 'pet.rank.name.传说羁绊': 'Legendary Bond',\n 'pet.rank.name.神话羁绊': 'Mythic Bond',\n 'pet.rank.name.永恒之契': 'Eternal Covenant',\n 'pet.rank.name.鲸生共渡': 'Lifelong Companion',\n 'pet.points': '{points} pts',\n 'pet.treats': 'Treats ×{n}',\n 'pet.state.loading': 'The pet is on its way…',\n 'pet.state.error': 'The pet is lost (connection failed)',\n 'pet.renderer.unavailable': 'This pet needs a renderer ({renderer}) that is not available in this build.',\n 'pet.live2d.core-missing': 'Live2D Cubism Core is not installed: place the official live2dcubismcore.min.js under $DSH_HOME/pets/.runtime/ and refresh (see the pet plugin README).',\n 'pet.live2d.vendor-missing': 'The Live2D component is missing; please update the pet plugin.',\n 'pet.live2d.load-failed': 'The Live2D model failed to load; check the pet directory is complete.',\n 'pet.openSessionHint': 'Click to jump to this session',\n // Gameplay HUD (miku-pet generalization: stat bars / work / sleep / shop; unified treats economy).\n 'pet.gameplay.menu': 'Play',\n 'pet.gameplay.work': 'Work',\n 'pet.gameplay.stopWork': 'Stop work',\n 'pet.gameplay.sleep': 'Sleep',\n 'pet.gameplay.wake': 'Wake up',\n 'pet.gameplay.shop': 'Shop',\n 'pet.gameplay.skin': 'Skin',\n 'pet.gameplay.skinDefault': 'Default',\n 'pet.gameplay.back': 'Back',\n 'pet.gameplay.buy': 'Buy',\n 'pet.gameplay.insufficient': 'Not enough {currency}',\n 'pet.gameplay.prize': 'Prize +{amount} {currency}',\n 'pet.gameplay.working': 'Working',\n 'pet.gameplay.sleeping': 'Sleeping',\n 'pet.gameplay.stat.hunger': 'Hunger',\n 'pet.gameplay.stat.mood': 'Mood',\n 'pet.gameplay.stat.energy': 'Energy',\n 'pet.gameplay.stat.affection': 'Affection',\n 'pet.gameplay.currency.treats': 'Treats',\n 'pet.moreSessions': 'Expand {n} more session bubbles',\n 'pet.collapseSessions': 'Collapse session bubbles',\n // First-level settings section (the `settings.section` seat).\n 'settings.title': 'Pet',\n 'settings.description': 'Pick a pet to sit in a corner of the page.',\n 'settings.pet': 'Pet',\n 'settings.petHint': 'Each pet keeps its own name; rename it from the pet panel.',\n 'settings.displayGroup': 'Display',\n 'settings.bubbleGroup': 'Bubbles',\n 'settings.decoration': 'Status decoration',\n 'settings.decorationHint': 'Bubbles carry ornaments like the spouting whale.',\n 'settings.statusBubbles': 'Status bubbles',\n 'settings.statusBubblesHint': 'The pet reports when it is thinking and which tool it is using.',\n 'settings.visible': 'Show the pet',\n 'settings.visibleHint': 'A hidden pet comes back from the input row.',\n 'settings.size': 'Size (px)',\n 'settings.sizeHint': 'How tall the pet stands.',\n 'settings.bubbleScale': 'Bubble text',\n 'settings.bubbleScaleHint': 'Text follows the pet size, times this factor.',\n 'settings.right': 'Right inset (px)',\n 'settings.rightHint': 'Distance from the right edge of the window.',\n 'settings.bottom': 'Bottom inset (px)',\n 'settings.bottomHint': 'Distance from the bottom edge of the window.',\n 'settings.inherit': 'Default',\n 'settings.on': 'On',\n 'settings.off': 'Off',\n 'settings.overridden': 'Changed',\n 'settings.reset': 'Reset to default',\n 'settings.notExposed': 'This DSH version does not open the pet settings here; edit $DSH_HOME/settings.yaml instead.',\n 'settings.readOnly': 'Settings are read-only.',\n 'settings.expand': 'Show settings',\n 'settings.collapse': 'Hide settings',\n 'settings.saveFailed': 'Not saved; what you typed is still there.',\n 'settings.invalidNumber': 'Enter a number, or leave it empty for the default.',\n} as const\n\n/** Key union for this namespace. */\nexport type PetKey = keyof typeof zh\n\n/** The settings-card slice of the pet dictionary. */\nexport type SettingsCardKey = PetKey\n\n/**\n * Active dictionary, picked by the document language at call time. The pet\n * mounts as a global floating surface (not a session-scoped slot), so it has\n * no framework locale seat and resolves its copy the same tiny way the\n * task-board's DOM-injected surface does.\n */\nexport function dictionary(): Record<PetKey, string> {\n const lang = typeof document !== 'undefined' ? document.documentElement.lang : 'zh'\n return lang.toLowerCase().startsWith('en') ? en : zh\n}\n\n/**\n * Translate a key with optional `{name}` template params. Mirrors the slot\n * `Translate` contract `(key, params?) => string` so it can be handed to the\n * same components that used to receive the framework-injected `t` seat. The\n * key is typed loosely (`string`) so the function is assignable to the slot's\n * `TranslateNS<'pet'>` (whose key domain also spans the shared common\n * vocabulary); a missing key degrades to the key itself rather than throwing.\n */\nexport function t(key: string, params?: Record<string, unknown>): string {\n let text: string = (dictionary() as Record<string, string>)[key] ?? key\n if (params !== undefined) {\n for (const [name, value] of Object.entries(params)) {\n text = text.replaceAll(`{${name}}`, String(value))\n }\n }\n return text\n}\n\ndeclare module '@deepseek-ai/dsh-client-ui-slots' {\n interface LocaleNamespaceMap {\n /** dsh-pet UI copy. */\n pet: PetKey\n }\n}\n","/**\n * One settings page's seat in either the Web Extensions parent or the legacy\n * first-level settings navigation.\n *\n * The parent supplies the page contract; a child does not know which slot the\n * parent uses internally. While `webUiExtensions` is live the page is handed\n * to its service, which owns keyed mounting and disposal. Without the parent,\n * the same component registers as its original first-level settings section,\n * so a standalone install keeps a working entry.\n */\n\n/** The parent service face this helper consumes. */\nexport interface WebExtensionPageService {\n readonly sectionId: string\n registerPage(page: WebExtensionPageSeat): () => void\n}\n\n/** Seat-independent page contribution. */\nexport interface WebExtensionPageSeat {\n key: string\n order: number\n locale: string\n label(): string\n inject(): object\n component: unknown\n children?: Record<string, { kind: 'keyed' | 'list'; scope: 'root' }>\n}\n\n/** The slot-registry slice used for the standalone fallback. */\nexport interface WebExtensionPageSlots {\n register(options: never, component: never): unknown\n spec?(key: string): unknown\n entries?(key: string): readonly { component?: unknown; options: Record<string, unknown> }[]\n}\n\n/** The context slice needed by the migration. */\nexport interface WebExtensionPageContext {\n slots: WebExtensionPageSlots\n get?(name: string): unknown\n on?(event: never, listener: never): unknown\n}\n\nconst SETTINGS_SECTION = 'settings.section'\nconst WEB_EXTENSION_SLOT = 'web-ui.extension'\n\nfunction serviceOf(ctx: WebExtensionPageContext): WebExtensionPageService | undefined {\n if (typeof ctx.get !== 'function') return undefined\n try {\n const candidate = ctx.get('webUiExtensions') as Partial<WebExtensionPageService> | undefined\n return candidate !== null\n && typeof candidate === 'object'\n && typeof candidate.sectionId === 'string'\n && typeof candidate.registerPage === 'function'\n ? candidate as WebExtensionPageService\n : undefined\n } catch {\n return undefined\n }\n}\n\nfunction warn(seat: string, error: unknown): void {\n try {\n console.warn(`[dsh-web-settings] page \"${seat}\" could not be mounted`, error)\n } catch {\n // A restricted console must not drop the remaining entry.\n }\n}\n\n/**\n * Keep exactly one reachable page contribution while the parent loads or\n * unloads. The parent service owns integrated mounting; only the fallback uses\n * this plugin's own slot registry. Slot disposal is synchronous, so the latch\n * prevents a move from recursively registering a duplicate.\n */\nexport function installWebExtensionPage(\n ctx: WebExtensionPageContext,\n page: WebExtensionPageSeat,\n): () => void {\n let dispose: (() => void) | undefined\n let current: 'integrated' | 'legacy' | undefined\n let reconciling = false\n let disposed = false\n\n const present = (seat: 'integrated' | 'legacy'): boolean => {\n if (typeof ctx.slots.entries !== 'function') return current === seat\n const slot = seat === 'integrated' ? WEB_EXTENSION_SLOT : SETTINGS_SECTION\n return ctx.slots.entries(slot).some(entry =>\n entry.component === page.component\n && (seat === 'integrated' ? entry.options.key : entry.options.id) === page.key)\n }\n\n const registerSeat = (seat: 'integrated' | 'legacy'): (() => void) => {\n if (seat === 'integrated') {\n const service = serviceOf(ctx)\n if (service === undefined) throw new Error('webUiExtensions service is unavailable')\n return service.registerPage(page)\n }\n return ctx.slots.register({\n name: SETTINGS_SECTION,\n id: page.key,\n order: page.order,\n label: page.label,\n locale: page.locale,\n inject: page.inject as never,\n ...(page.children === undefined ? {} : { children: page.children }),\n } as never, page.component as never) as () => void\n }\n\n const reconcile = (): void => {\n if (disposed || reconciling) return\n const target: 'integrated' | 'legacy' = serviceOf(ctx) === undefined ? 'legacy' : 'integrated'\n if (current === target && present(target)) return\n const slot = target === 'integrated' ? WEB_EXTENSION_SLOT : SETTINGS_SECTION\n if (typeof ctx.slots.spec === 'function' && ctx.slots.spec(slot) === undefined) return\n reconciling = true\n const previous = current\n const disposePrevious = dispose\n current = undefined\n dispose = undefined\n disposePrevious?.()\n try {\n dispose = registerSeat(target)\n current = target\n } catch (error) {\n warn(target, error)\n if (previous !== undefined && previous !== target) {\n try {\n dispose = registerSeat(previous)\n current = previous\n } catch (restoreError) {\n warn(previous, restoreError)\n }\n }\n } finally {\n reconciling = false\n }\n }\n\n if (typeof ctx.on === 'function') {\n try { ctx.on('slots/changed' as never, reconcile as never) } catch { /* the initial entry remains usable */ }\n }\n reconcile()\n return () => {\n if (disposed) return\n disposed = true\n dispose?.()\n dispose = undefined\n current = undefined\n }\n}\n","/**\n * The pet settings page's contribution: the Web Extensions parent mounts it\n * through its page service, while a standalone install keeps the original\n * first-level settings section.\n */\n\nimport type { Context as ClientContext } from '@deepseek-ai/cordis'\n// Type-only: the renderer owns ctx.slots and the locale plugin owns ctx.locale.\nimport type {} from '@deepseek-ai/dsh-client-ui-renderer/client'\nimport type {} from '@deepseek-ai/dsh-client-locale/client'\nimport type {} from './web-extension-contract.ts'\nimport { PetSettingsSection, type PetSettingsCardController } from './PetSettingsCard.tsx'\nimport { NS } from './locales.ts'\nimport { installWebExtensionPage } from './web-extension-page.ts'\n\n/**\n * Register exactly one reachable pet entry and follow the parent across late\n * loading or teardown. The controller belongs to apply(), not a registration,\n * so moving seats never resets staged edits or subscriptions.\n * @returns the page contribution's disposer.\n */\nexport function installPetSettingsRegistration(\n ctx: ClientContext,\n controller: PetSettingsCardController,\n): () => void {\n return installWebExtensionPage(ctx, {\n key: 'pet',\n order: 130,\n locale: NS,\n label: () => ctx.locale.bind(NS)('settings.title'),\n inject: () => controller.inject(),\n component: PetSettingsSection,\n })\n}\n","// Generated by scripts/sync-shared.mjs from shared/client/main-session.ts. Do not edit this copy; edit the shared source and run \"node scripts/sync-shared.mjs\".\n/**\n * Main-view Session derivation for the multi-instance Client Session model.\n *\n * The Client Session Controller carries no global \"current\" selection: view\n * selection belongs to the workspace UI, which owns the main-area reference and\n * publishes it through the catalog's per-source ownership counts\n * (`SessionSummary.retainedBy.mainView`). A plugin that needs the Session the\n * main view shows derives it from that marker instead of the removed\n * `SessionListState.current` field.\n *\n * The marker describes view ownership, not authority. It is the right input for\n * presentation and for deciding which view a navigation targets; it is not a\n * business fallback, because source counts never imply visibility or success.\n * @module dsh-web/shared/main-session\n */\n\n/** The catalog row subset this helper reads (a `SessionSummary` projection). */\nexport interface MainViewOwnedRow<Id extends string = string> {\n /** Catalog row identity. */\n readonly id: Id\n /** Per-source local ownership counts; absent rows are never owned. */\n readonly retainedBy?: Readonly<Partial<Record<string, number>>> | undefined\n}\n\n/**\n * Resolve the Session the main view currently shows.\n *\n * Reads the catalog's rows rather than a per-id retain-info source: ownership\n * counts ride the list snapshot, so this neither allocates observers nor opens\n * history, and a subscription to the list still fires when the selection moves.\n * @param byId - the session catalog's rows (`SessionListState.byId`), when available.\n * @returns the main-view session id, or undefined when the main view shows none.\n */\nexport function mainViewSessionId<Id extends string>(\n byId: Readonly<Record<Id, MainViewOwnedRow<Id> | undefined>> | undefined | null,\n): Id | undefined {\n if (byId === undefined || byId === null) return undefined\n for (const row of Object.values<MainViewOwnedRow<Id> | undefined>(byId)) {\n if (row !== undefined && (row.retainedBy?.mainView ?? 0) > 0) return row.id\n }\n return undefined\n}\n","// Generated by scripts/sync-shared.mjs from shared/client/telemetry.ts. Do not edit this copy; edit the shared source and run \"node scripts/sync-shared.mjs\".\n/**\n * Anonymous install telemetry shared by the DSH Web UI family plugins.\n *\n * Once per UTC day per browser, each wired plugin sends one heartbeat to\n * the dsh-market edge API listing its package name (and version when known).\n * The payload carries no conversation data and no identifiers beyond a random\n * UUID generated in localStorage; the server hashes it with a deployment salt\n * before storage and never persists IP addresses. Sends are fire-and-forget:\n * failures stay silent and simply retry on a later mount or day. The system\n * is documented in docs/telemetry.md.\n */\n\nexport type TelemetryChannel = 'market' | 'npm' | 'unknown'\n\nexport interface TelemetryItem {\n /** npm package name or asset id, e.g. \"@linxin666/dsh-pet\" or \"skin:harbor\". */\n name: string\n /** Installed version when known; omitted otherwise. */\n version?: string\n /** Install channel when determinable (market = Workshop install). */\n channel?: TelemetryChannel\n}\n\nconst VISITOR_KEY = 'dsh-web-ui-telemetry-visitor'\nconst DAY_KEY_PREFIX = 'dsh-web-ui-telemetry-day:'\nconst ENDPOINT = 'https://dsh-market.com/api/telemetry/event'\n\n// Baked into each client bundle by shared/tsdown.client.ts (the package's own\n// package.json version at build time). Undefined in dev/test builds.\ndeclare const __DSH_PKG_VERSION__: string | undefined\n\n/** The building package's version, when the bundle carries it. */\nfunction bakedVersion(): string | undefined {\n try {\n return typeof __DSH_PKG_VERSION__ === 'string' && __DSH_PKG_VERSION__ !== ''\n ? __DSH_PKG_VERSION__\n : undefined\n } catch {\n return undefined\n }\n}\n\n/** Read or lazily create the anonymous visitor id; null when storage is unavailable. */\nfunction visitorId(): string | null {\n try {\n const existing = localStorage.getItem(VISITOR_KEY)\n if (existing && /^[A-Za-z0-9_-]{16,64}$/.test(existing)) return existing\n const fresh = crypto.randomUUID().replaceAll('-', '')\n localStorage.setItem(VISITOR_KEY, fresh)\n return fresh\n } catch {\n // Storage unavailable (privacy mode, sandboxed frame): report nothing.\n return null\n }\n}\n\n/** Drop stale per-day dedup keys so localStorage does not grow forever. */\nfunction pruneDayKeys(today: string): void {\n try {\n for (let index = localStorage.length - 1; index >= 0; index -= 1) {\n const key = localStorage.key(index)\n if (key !== null && key.startsWith(DAY_KEY_PREFIX) && key !== DAY_KEY_PREFIX + today) {\n localStorage.removeItem(key)\n }\n }\n } catch { /* best effort */ }\n}\n\n/**\n * Fire the daily heartbeat for the given items at most once per UTC day per\n * browser. Never throws and never blocks the caller. Items without an explicit\n * version inherit the bundle's baked build version.\n */\nexport function reportDailyHeartbeat(items: readonly TelemetryItem[]): void {\n try {\n if (items.length === 0) return\n const today = new Date().toISOString().slice(0, 10)\n // Automation contexts (CDP-driven QA browsers, fresh isolated profiles)\n // mint a new visitor id per run and would inflate instance counts.\n if (navigator.webdriver) return\n if (localStorage.getItem(DAY_KEY_PREFIX + today) !== null) return\n const visitor = visitorId()\n if (visitor === null) return\n pruneDayKeys(today)\n const payloadItems = items.map((item) => {\n const out: Record<string, string> = { name: item.name }\n const version = item.version ?? bakedVersion()\n if (version !== undefined) out.version = version\n if (item.channel !== undefined) out.channel = item.channel\n return out\n })\n const body = JSON.stringify({ kind: 'heartbeat', visitor, items: payloadItems })\n void fetch(ENDPOINT, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body,\n keepalive: true,\n }).then((response) => {\n // Mark the day only after an accepted send, so offline browsers retry\n // on a later mount instead of going dark until tomorrow.\n if (response.ok) localStorage.setItem(DAY_KEY_PREFIX + today, '1')\n }).catch(() => { /* unreachable endpoint: stay silent */ })\n } catch { /* never break the host UI over telemetry */ }\n}\n","/**\n * dsh-pet browser half — mounts the selected pet as a global floating\n * surface and drives it from the host's same-origin '/api/pet/*' JSON\n * endpoints: fetch the registry list once, poll the host snapshot (~2 s),\n * forward interactions, persist drag positions. The pet is host-global (no\n * session dimension), so it mounts directly onto 'document.body' via a\n * single React root — the [data-dsh-plugin=\"pet\"] container — rather than a\n * session-scoped slot: on the new-conversation screen no session exists, and\n * a dock-mounted pet would vanish there (issue #48). The sprite chrome\n * portals into that same root, so the root owns the whole surface and a\n * root-keyed suppressor can hide it as one unit. When the pet is hidden the\n * entry becomes a fixed-position summon button.\n * @module @linxin666/dsh-pet/client\n */\n\nimport type { Context as ClientContext } from '@deepseek-ai/cordis'\nimport type { ISessions } from '@deepseek-ai/dsh-api-session-controller/client'\nimport type { SessionId } from '@deepseek-ai/dsh-api-remotes/client'\nimport type { ConfigForm, ConfigFormSnapshot } from '@deepseek-ai/dsh-client-ui-settings/client'\n// Type-only: pulls the locale plugin's Context merge (ctx.locale).\nimport type {} from '@deepseek-ai/dsh-client-locale/client'\n// Type-only: pulls the shared configuration forms Context merge (ctx.configForms).\nimport type {} from '@deepseek-ai/dsh-client-ui-settings/client'\nimport type {} from '@deepseek-ai/dsh-client-ui-slots'\n// Type-only: pulls the ctx.slots merge (the renderer owns the slot registry since 0.1.2).\nimport type {} from '@deepseek-ai/dsh-client-ui-renderer/client'\nimport type {} from '@deepseek-ai/dsh-client-ui-conversation/client'\n// Type-only: pulls the workspace plugin's Context merge (ctx.uiWorkspace), the\n// multi-instance navigation face that replaced ISessions.open().\nimport type {} from '@deepseek-ai/dsh-client-ui-workspace/client'\nimport type { PetDisplayConfig } from '../persist.ts'\nimport type { PetGameplayVerbResult, PetInteractResult, PetStateView } from '../service.ts'\nimport type { PetInteraction } from '../affinity.ts'\nimport type { PetDefinition } from '../registry.ts'\nimport { createElement } from 'react'\nimport { createRoot } from 'react-dom/client'\nimport { createPetStore, type PetStoreInstance } from './pet-store.ts'\nimport { createWorkTickGate } from './work-tick-gate.ts'\nimport { PetDockEntry, type PetInjected } from './PetDockEntry.tsx'\nimport { defaultPetRendererRegistry } from './renderers/registry.ts'\nimport { live2dRenderer } from './renderers/live2d.ts'\nimport { frames2dRenderer } from './renderers/frames2d.ts'\nimport { registerPetUiTeardown, takeoverPetUiTeardown } from './ui-teardown.ts'\nimport { PetSettingsCardController, type PetSettings } from './PetSettingsCard.tsx'\nimport { installPetSettingsRegistration } from './settings-registration.ts'\nimport { NS, en, zh } from './locales.ts'\nimport { mainViewSessionId } from './main-session.ts'\nimport { reportDailyHeartbeat } from './telemetry.ts'\n\n/** The host pet API as the browser sees it (same-origin JSON endpoints). */\ninterface PetHttpApi {\n /** Poll the host snapshot; the GUI's current session id rides the query. */\n state(currentSessionId?: string): Promise<PetStateView>\n pets(): Promise<PetDefinition[]>\n interact(kind: PetInteraction): Promise<PetInteractResult>\n setVisible(visible: boolean): Promise<{ ok: true; display: PetDisplayConfig }>\n setConfig(patch: Partial<PetDisplayConfig>): Promise<{ ok: true; display: PetDisplayConfig }>\n setName(name: string): Promise<{ ok: true; name: string } | { ok: false; error: string }>\n setPet(petId: string): Promise<{ ok: true; petId: string } | { ok: false; error: string }>\n panelAction(id: string): Promise<{ ok: boolean; error?: string }>\n setSkin(skin?: string): Promise<{ ok: boolean; error?: string; skin?: string }>\n gameplayTouch(zone?: string): Promise<PetGameplayVerbResult>\n gameplaySetMode(mode: string | null): Promise<PetGameplayVerbResult>\n gameplayWorkTick(): Promise<PetGameplayVerbResult>\n gameplayBuy(item: string): Promise<PetGameplayVerbResult>\n}\n\n/** Same-origin JSON fetch helper (GET without body, POST with JSON body). */\nasync function petFetch<T>(path: string, body?: unknown): Promise<T> {\n const response = await fetch(path, body === undefined\n ? {}\n : {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n })\n if (!response.ok) {\n throw new Error('pet ' + path + ' failed: ' + response.status)\n }\n return (await response.json()) as T\n}\n\n/** The live host API instance (always defined; failures surface per call). */\nconst petApi: PetHttpApi = {\n state: (currentSessionId) => petFetch('/api/pet/state'\n + (currentSessionId === undefined ? '' : '?current=' + encodeURIComponent(currentSessionId))),\n pets: () => petFetch('/api/pet/pets'),\n interact: (kind) => petFetch('/api/pet/interact', { kind }),\n setVisible: (visible) => petFetch('/api/pet/set-visible', { visible }),\n setConfig: (patch) => petFetch('/api/pet/set-config', patch),\n setName: (name) => petFetch('/api/pet/set-name', { name }),\n setPet: (petId) => petFetch('/api/pet/set-pet', { petId }),\n panelAction: (id) => petFetch('/api/pet/panel-action', { id }),\n setSkin: (skin) => petFetch('/api/pet/set-skin', skin === undefined ? {} : { skin }),\n gameplayTouch: (zone) => petFetch('/api/pet/gameplay/touch', zone === undefined ? {} : { zone }),\n gameplaySetMode: (mode) => petFetch('/api/pet/gameplay/mode', { mode }),\n gameplayWorkTick: () => petFetch('/api/pet/gameplay/work-tick', {}),\n gameplayBuy: (item) => petFetch('/api/pet/gameplay/buy', { item }),\n}\n\n/** Poll interval for the host snapshot. */\nconst POLL_MS = 2000\n\n/** Settings namespace of the pet's settings page. It is the profile entry id the Host serves a form for. */\nconst PET_SETTINGS_NS = 'pet'\n\n/** Required services (sessions powers bubble-to-session navigation). */\nexport const inject = ['slots', 'locale', 'connection', 'configForms', 'remote', 'sessions', 'uiWorkspace']\n\n/** Re-exported for consumers that type against the injected face. */\nexport type { PetInjected, PetDockEntryProps } from './PetDockEntry.tsx'\nexport type { PetSpriteProps } from './PetSprite.tsx'\nexport type { PetUiState, PetFeedback } from './pet-store.ts'\nexport type { PetSettingsCardFace, PetSettingsCardState } from './PetSettingsCard.tsx'\nexport type { PetSettingsSectionProps } from './PetSettingsCard.tsx'\nexport type { PetDefinition } from '../registry.ts'\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n /**\n * Optional family binder provided by dsh-web-settings; absent when that\n * group plugin is not installed, so callers fall back to the shared\n * per-entry form.\n */\n webUiSettings?: {\n bind<S>(spec: { namespace: string; decode?: (section: unknown) => S | undefined }): ConfigForm<S>\n }\n }\n}\n\n/**\n * The profile entry ids a pet install is served under, most specific first. The\n * family bundle renames child rows, so a standalone install and an aggregate\n * one answer to different ids for the same 'pet' namespace.\n */\nconst AGGREGATE_ENTRY_ID = 'web-ui-pet'\nconst PET_ENTRY_IDS: readonly string[] = [AGGREGATE_ENTRY_ID, 'ui-pet', PET_SETTINGS_NS]\n\n/** How long the deferred form keeps retrying before it settles on the fallback. */\nexport const BINDER_RETRY_MS = 250\nconst BINDER_ATTEMPTS = 24\n\n/** The snapshot an unresolved (or resolvable-but-unbound) form publishes. */\nfunction pendingSnapshot<T>(status: 'loading' | 'unavailable'): ConfigFormSnapshot<T> {\n return { status, value: undefined, base: undefined, user: undefined, revision: undefined, writable: false }\n}\n\n/**\n * A ConfigForm that late-binds to the family settings binder.\n *\n * The binder service (dsh-web-settings) is not guaranteed to be published by the\n * time this plugin's apply() runs: the aggregate bundle mounts its inlined\n * children — including the binder — inside an async mount that awaits the\n * active-rows fetch, while standalone loader entries like this one apply\n * synchronously in that window. A single early probe then permanently falls\n * back to `configForms.get('pet')`, which is never a served row id under the\n * aggregate (the row is `web-ui-pet`), so the settings card renders \"not\n * exposed\" forever even though the Host serves the namespace.\n *\n * This form resolves through the binder as soon as the service appears and\n * delegates the whole ConfigForm surface to it, re-publishing to its own\n * subscribers on every swap. Until a form is resolved it publishes a loading\n * (then unavailable) snapshot so the card shows a transient state, never a\n * false \"not exposed\". If the binder never appears it retries for a bounded\n * window, then permanently binds the non-bridge fallback by SERVED entry id.\n */\nclass DeferredSettingsForm implements ConfigForm<PetSettings> {\n private ctx: ClientContext\n private current: ConfigForm<PetSettings> | undefined\n private readonly listeners = new Set<() => void>()\n private unsubscribeCurrent: (() => void) | undefined\n private retryTimer: number | undefined\n private attempts = 0\n private disposed = false\n private readonly fallback: ConfigForm<PetSettings>\n private fallbackUnsubscribe: (() => void) | undefined\n\n constructor(ctx: ClientContext) {\n this.ctx = ctx\n this.fallback = ctx.configForms.get<PetSettings>(this.resolveFallbackEntryId())\n // No binder yet: the aggregate publishes it after an async mount, so keep\n // probing. A shared form that can already answer for itself is adopted at\n // once; one still loading has simply not been filled in yet.\n if (!this.resolve() && !this.fallbackSettled()) this.scheduleRetry()\n else if (this.current === undefined) this.adoptFallback()\n }\n\n /**\n * True only once the shared mirror answers for the pet namespace itself.\n *\n * 'ready' is the only state that answers (#1813). A host-persisted row starts\n * out as 'loading' — the mirror has published no view yet — and that is not\n * an answer: adopting it on sight drops the retry window, and under the\n * aggregate, which serves only the renamed 'web-ui-pet' row, the form then\n * settles into 'unavailable' and the page stays \"not exposed\" for good. So\n * 'loading' and 'unavailable' both keep the window open and let the binder be\n * adopted the moment the aggregate publishes it.\n */\n private fallbackSettled(): boolean {\n try {\n return this.fallback.getSnapshot().status === 'ready'\n } catch {\n return false\n }\n }\n\n /**\n * Bind the fallback to a SERVED row id when the mirror can name one; a mirror\n * that cannot is left to report its own unavailable state.\n */\n private resolveFallbackEntryId(): string {\n try {\n const served = this.ctx.configForms.describe().getSnapshot().view?.namespaces.map(view => view.ns)\n if (served && served.length > 0) {\n const hit = PET_ENTRY_IDS.find(id => served.includes(id))\n if (hit !== undefined) return hit\n }\n } catch {\n // fall through to the family namespace; the form reports unavailable.\n }\n return PET_SETTINGS_NS\n }\n\n /**\n * Adopt the family binder the moment it is published.\n * @returns true when a binder was bound, false when none is available yet.\n */\n private resolve(): boolean {\n if (this.disposed) return false\n let binder: { bind?: unknown } | undefined\n try {\n binder = this.ctx.get('webUiSettings') as { bind?: unknown } | undefined\n } catch {\n binder = undefined\n }\n if (binder === undefined || typeof binder.bind !== 'function') return false\n let bound: ConfigForm<PetSettings>\n try {\n bound = (binder as { bind: <T>(spec: { namespace: string }) => ConfigForm<T> })\n .bind<PetSettings>({ namespace: PET_SETTINGS_NS })\n } catch {\n return false\n }\n this.current = bound\n // Mirror the bound form's changes to our own subscribers; a later re-resolve\n // swaps this subscription to the new form.\n this.unsubscribeCurrent?.()\n this.unsubscribeCurrent = bound.subscribe(() => this.publish())\n this.publish()\n return true\n }\n\n /**\n * Adopt the shared per-entry form. It is used immediately unless it cannot\n * answer yet (still loading, or reporting the namespace unavailable), in which\n * case the binder may still be on its way and the retry window takes over\n * (see scheduleRetry).\n */\n private adoptFallback(): void {\n this.current = this.fallback\n this.fallbackUnsubscribe ??= this.fallback.subscribe(() => this.publish())\n this.unsubscribeCurrent = this.fallbackUnsubscribe\n this.publish()\n }\n\n /** Retry the binder lookup a few times across the aggregate's async mount. */\n private scheduleRetry(): void {\n if (this.disposed) return\n if (this.attempts >= BINDER_ATTEMPTS) {\n this.adoptFallback()\n return\n }\n this.attempts += 1\n this.retryTimer = window.setTimeout(() => {\n this.retryTimer = undefined\n if (this.disposed) return\n if (this.resolve()) return\n // The binder still absent: keep waiting only while the shared form cannot\n // answer for itself, otherwise a standalone install stalls for the window.\n if (this.fallbackSettled()) {\n this.attempts = BINDER_ATTEMPTS\n this.adoptFallback()\n return\n }\n this.scheduleRetry()\n }, BINDER_RETRY_MS)\n }\n\n private publish(): void {\n for (const listener of this.listeners) listener()\n }\n\n /** The resolved form, or a placeholder snapshot when still pending. */\n private snapshot(): ConfigFormSnapshot<PetSettings> {\n return this.current?.getSnapshot() ?? pendingSnapshot<PetSettings>(this.attempts >= BINDER_ATTEMPTS ? 'unavailable' : 'loading')\n }\n\n getSnapshot(): ConfigFormSnapshot<PetSettings> {\n return this.snapshot()\n }\n\n subscribe(listener: () => void): () => void {\n this.listeners.add(listener)\n return () => { this.listeners.delete(listener) }\n }\n\n mutate(ops: Parameters<ConfigForm<PetSettings>['mutate']>[0], expectedRevision?: number): Promise<boolean> {\n return this.current?.mutate(ops, expectedRevision) ?? Promise.resolve(false)\n }\n\n set(field: string, value: unknown): Promise<boolean> {\n return this.current?.set(field, value) ?? Promise.resolve(false)\n }\n\n unset(field: string): Promise<boolean> {\n return this.current?.unset(field) ?? Promise.resolve(false)\n }\n\n /** Release the retry timer and mirror subscription; not part of ConfigForm. */\n dispose(): void {\n if (this.disposed) return\n this.disposed = true\n if (this.retryTimer !== undefined) {\n window.clearTimeout(this.retryTimer)\n this.retryTimer = undefined\n }\n this.unsubscribeCurrent?.()\n this.unsubscribeCurrent = undefined\n this.current = undefined\n this.listeners.clear()\n // The shared per-entry form carries no disposer of its own (ConfigForm is a\n // pure read/write surface); only this form's own subscriptions are released.\n this.fallbackUnsubscribe?.()\n this.fallbackUnsubscribe = undefined\n }\n}\n\n/**\n * Client plugin body: register dictionaries, mount the global pet entry and\n * poll loop while the plugin is enabled, and seat the settings card as a\n * first-level settings section.\n * @param ctx - client root context.\n */\n\n/** The page-wide work-tick gate; its window follows the active pet's cadence. */\nconst workTickGate = createWorkTickGate()\n\n/**\n * The work cadence the active pet declares, when its registry entry is known.\n * @param store - the pet store holding the host snapshot and the registry list.\n * @returns the configured `gameplay.work.tickMs`, or undefined when unknown.\n */\nfunction activeWorkTickMs(store: PetStoreInstance): number | undefined {\n const state = store.getSnapshot()\n const definition = state.pets.find((entry) => entry.id === state.snapshot?.pet.id)\n return definition?.gameplay?.work?.tickMs\n}\n\nexport function apply(ctx: ClientContext): void {\n // Anonymous install heartbeat (docs/telemetry.md): one beat per browser per\n // UTC day, package name only, silent failure.\n reportDailyHeartbeat([{ name: '@linxin666/dsh-pet' }])\n\n ctx.effect(() => {\n try {\n return ctx.locale.register(NS, { zh, en })\n } catch {\n return () => {}\n }\n }, 'pet: dictionaries')\n\n // Built-in renderers dispatch through the plugin-wide registry (pet-center\n // M3). Registration is idempotent (id wins), so re-applies stay clean.\n defaultPetRendererRegistry.register(live2dRenderer)\n defaultPetRendererRegistry.register(frames2dRenderer)\n\n const settingsForm = new DeferredSettingsForm(ctx)\n const enabled = (): boolean => {\n const snapshot = settingsForm.getSnapshot()\n return snapshot.status === 'ready'\n ? snapshot.value?.enabled ?? true\n : snapshot.status === 'unavailable'\n }\n\n // One staged form follows the pet page between Web Extensions and the\n // standalone first-level section. Seat migration does not reset drafts.\n const petSettings = new PetSettingsCardController(settingsForm)\n const disposeSettingsRegistration = installPetSettingsRegistration(ctx, petSettings)\n ctx.effect(() => () => {\n disposeSettingsRegistration()\n petSettings.dispose()\n }, 'pet: settings page')\n\n // The global pet entry, its store, and the poll loop live while the plugin\n // is enabled; toggling the setting off hides the pet and stops polling.\n // 'uiDead' marks a terminal teardown (takeover by a later bundle instance\n // or fiber disposal): a taken-over or disposed instance must never remount\n // from a late settings callback (issue #785).\n let disposeUi: (() => void) | undefined\n let clearUiTeardown: (() => void) | undefined\n let uiDead = false\n const killUi = (): void => {\n if (uiDead) return\n uiDead = true\n clearUiTeardown?.()\n clearUiTeardown = undefined\n disposeUi?.()\n disposeUi = undefined\n }\n const syncUi = (): void => {\n if (!uiDead && enabled() && disposeUi === undefined) {\n // ONE store instance for the whole app, owned by this apply body. The\n // pet is host-global (state/display/interactions are /api/pet/*\n // endpoints with no session dimension), so the slot system's per-session\n // store scoping would only reset the pet on session switches and leave\n // it stateless on the new-conversation screen (no session to scope by).\n const petStore: PetStoreInstance = createPetStore().create()\n const setSnapshot = petStore.actions.setSnapshot\n const setPets = petStore.actions.setPets\n const setState = petStore.actions.setState\n const setFeedback = petStore.actions.setFeedback\n\n // Clicking a session bubble jumps the GUI to that session; the\n // catalog's main-view ownership marker tells which session the main view\n // holds (the multi-instance replacement for the removed list.current), so\n // the host can lead the bubble stack with it. A bubble can outlive its\n // disposed session by one poll tick, and navigation rejects unknown ids,\n // so consult the live list first. The pet's type program also loads the\n // host-side dsh-session package through the service types, whose Context\n // merge declares a different 'sessions' face; pin the browser runtime's\n // outward face here.\n const sessions = ctx.sessions as unknown as ISessions\n const currentSessionId = (): string | undefined => mainViewSessionId(sessions.list.getSnapshot().byId)\n\n // The registry list is fetched lazily with retries baked into the poll\n // cycle: until it lands, the dock entry renders nothing and every 2s\n // tick tries again. After it lands, one list feeds both the sprite and\n // the settings card's choices.\n let petsLoaded = false\n // Latest-wins guard: the 2s tick, visibility recovery, and\n // interaction-triggered refreshes can overlap; only the newest\n // response may publish, so a slow older one can never roll the\n // snapshot back.\n let stateSeq = 0\n const pollNow = (): void => {\n if (!petsLoaded) {\n petApi.pets().then((list) => {\n petsLoaded = true\n setPets(list)\n }, () => {\n // Retry on the next poll tick.\n })\n }\n const seq = stateSeq + 1\n stateSeq = seq\n petApi.state(currentSessionId()).then((snapshot) => {\n if (seq !== stateSeq) return\n setSnapshot(snapshot)\n }, () => {\n if (seq !== stateSeq) return\n setState('error', 'pet.state transport error')\n })\n }\n\n const disposePoll = ctx.effect(() => {\n // Poll only while the tab is visible: the host snapshot does not\n // change while the page is hidden, so a background interval would\n // only burn RPCs (browser throttling is an unreliable backstop).\n // Coming back to the tab refreshes the pet immediately instead of\n // waiting out the next 2 s cycle.\n let timer: number | undefined\n const stop = (): void => {\n if (timer !== undefined) {\n window.clearInterval(timer)\n timer = undefined\n }\n }\n const start = (): void => {\n if (timer === undefined && document.visibilityState === 'visible') {\n timer = window.setInterval(pollNow, POLL_MS)\n }\n }\n const onVisibility = (): void => {\n if (document.visibilityState === 'visible') {\n pollNow()\n start()\n } else {\n stop()\n }\n }\n start()\n document.addEventListener('visibilitychange', onVisibility)\n return () => {\n stop()\n document.removeEventListener('visibilitychange', onVisibility)\n }\n }, 'pet: poll')\n\n // A current-session switch should re-order the bubble stack right away,\n // not on the next 2s tick. Poll only while the tab is visible, as the\n // poll loop itself does.\n const disposeSessionWatch = ctx.effect(() => {\n const unsubscribe = sessions.list.subscribe(() => {\n if (document.visibilityState === 'visible') pollNow()\n })\n return unsubscribe\n }, 'pet: current-session watch')\n\n const openSession = (sessionId: string): void => {\n const list = sessions.list.getSnapshot()\n if ((list.byId as any)[sessionId] === undefined) return\n // Navigation belongs to the workspace UI since the multi-instance Client\n // Session model; the Session Controller no longer opens one.\n ctx.uiWorkspace.openSession(sessionId as never)\n }\n\n const injected = (): PetInjected => ({\n store: petStore,\n ensure: pollNow,\n openSession,\n pet: () => {\n petApi.interact('pet').then((result) => {\n setFeedback({\n text: result.reaction,\n kind: 'pet',\n at: Date.now(),\n })\n }, () => {\n // Ignore transport errors on interactions; the next poll resyncs.\n })\n },\n feed: () => {\n petApi.interact('feed').then((result) => {\n setFeedback({\n text: result.reaction,\n kind: 'feed',\n at: Date.now(),\n })\n }, () => {\n // Ignore transport errors on interactions; the next poll resyncs.\n })\n },\n hide: () => {\n petApi.setVisible(false).then(() => {\n pollNow()\n }, () => {\n // Ignore; next poll resyncs.\n })\n },\n summon: () => {\n petApi.setVisible(true).then(() => {\n pollNow()\n }, () => {\n // Ignore; next poll resyncs.\n })\n },\n dragEnd: (right, bottom) => {\n petApi.setConfig({ right, bottom }).then(() => {\n pollNow()\n }, () => {\n // Ignore; next poll resyncs.\n })\n },\n rename: (name) => {\n petApi.setName(name).then((result) => {\n if (result.ok) pollNow()\n }, () => {\n // Ignore; next poll resyncs.\n })\n },\n // A panel action click (issue #6) travels back to the host, which\n // dispatches it to the plugin that registered the action. The plugin's\n // own callback does the work; the browser half only reports the id, and\n // the next poll brings back whatever that callback changed. A click on\n // an action the plugin already disposed answers { ok: false } — the\n // button was one poll tick stale, which is not a pet failure.\n panelAction: (id) => {\n petApi.panelAction(id).then((result) => {\n if (result.ok) pollNow()\n }, () => {\n // Ignore; next poll resyncs.\n })\n },\n feedbackDone: () => {\n setFeedback(null)\n },\n gameplay: {\n touch: (zone) => petApi.gameplayTouch(zone),\n setSkin: (skin) => petApi.setSkin(skin).then((result) => {\n if (result.ok) pollNow()\n return result\n }, () => ({ ok: false, error: 'transport' })),\n \n setMode: async (mode) => {\n if (mode === 'work') workTickGate.reset()\n return petApi.gameplaySetMode(mode)\n },\n workTick: async () => {\n // One adjudication per tick window, page-wide: suppress stale\n // duplicate intervals (HMR) re-playing the result track. The window\n // is the pet's own cadence, so a shorter tickMs is not downgraded.\n if (!workTickGate.allow(activeWorkTickMs(petStore))) {\n return { ok: true } as PetGameplayVerbResult\n }\n return petApi.gameplayWorkTick()\n },\n buy: (item) => petApi.gameplayBuy(item),\n },\n })\n\n // The pet is host-global (its state/display/interactions have no session\n // dimension), and the official rc.6 shell declares no root-scoped slot\n // for a global floating surface — the dock is session-scoped, so a pet\n // mounted there would vanish on the new-conversation screen (issue #48).\n // The entry therefore mounts straight onto document.body via a single\n // React root for the page lifetime: PetSprite portals itself to body\n // when visible, and the hidden-state summon button is fixed-positioned.\n //\n // Cross-instance single-mount guard (issue #785): take over the\n // page-global slot first — the previous bundle instance's fiber may\n // still be draining during a client reload, so unmount its React root\n // and remove its container — then sweep containers left behind by\n // instances that predate the teardown registry, so this mount is the\n // page's only [data-dsh-pet-root].\n takeoverPetUiTeardown()\n for (const stale of Array.from(document.querySelectorAll('div[data-dsh-pet-root]'))) {\n stale.remove()\n }\n const container = document.createElement('div')\n container.dataset.dshPetRoot = ''\n container.dataset.dshPlugin = 'pet'\n document.body.appendChild(container)\n const petRoot = createRoot(container)\n // The sprite chrome portals into THIS root (not document.body): the\n // root then owns the whole surface, so a root-keyed suppressor (the\n // portrait mobile layer, which hides [data-dsh-plugin=\"pet\"]) really\n // hides the sprite instead of missing the portaled float.\n //\n // The floating surface has no session-scoped locale seat, so it must be\n // handed the framework one explicitly. Resolving its copy from the\n // plugin's own zh/en dictionary keyed on <html lang> sent every\n // registered language except English to Chinese: a ru/ja/de page showed a\n // Chinese panel while the settings card beside it was translated. Binding\n // the 'pet' namespace instead follows the active language, the English\n // fallback, and every language pack that registers a dictionary for it\n // (the settings section label already resolves through the same seat).\n const renderPet = (): void => {\n petRoot.render(createElement(PetDockEntry, {\n ...injected(),\n t: ctx.locale.bind(NS),\n // The active locale rides the same mount as the translate seat so a\n // pet-declared English rank name follows the UI language.\n lang: ctx.locale.getLocale().active,\n portalTarget: container,\n }))\n }\n renderPet()\n // Re-render on a language switch instead of waiting for the next poll\n // tick: the declared rank ladder's nameEn applies immediately.\n const unsubscribeLocale = ctx.locale.subscribe(renderPet)\n\n let uiGone = false\n disposeUi = () => {\n if (uiGone) return\n uiGone = true\n clearUiTeardown?.()\n clearUiTeardown = undefined\n unsubscribeLocale()\n petRoot.unmount()\n container.remove()\n disposePoll()\n disposeSessionWatch()\n disposeUi = undefined\n }\n // The slot teardown is the takeover hook a later apply body runs; it\n // marks this instance terminal so a late settings callback from the\n // still-draining instance cannot remount a second pet.\n clearUiTeardown = registerPetUiTeardown(() => {\n uiDead = true\n disposeUi?.()\n })\n } else if (!uiDead && !enabled() && disposeUi !== undefined) {\n disposeUi()\n disposeUi = undefined\n }\n }\n // The settings subscription and the pet UI lifetime follow the fiber\n // (issue #785): disposal drops the subscription and tears the UI down\n // (terminal), so a hot-reloaded or re-injected bundle never leaves the\n // previous React root, container, or poll loop behind on document.body.\n const unsubscribeSettings = settingsForm.subscribe(syncUi)\n ctx.effect(\n () => () => {\n unsubscribeSettings()\n // Release the deferred form's retry timer and its mirror subscription so a\n // disposed fiber can never bind or publish after teardown.\n settingsForm.dispose()\n killUi()\n },\n 'pet: client lifecycle',\n )\n syncUi()\n}\n"],"ignoreList":[2],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAyDA,SAAgB,iBAA8D;GAC5E,OAAO,YAAY;IACjB,aAAyB;KACvB,UAAU;KACV,MAAM,CAAC;KACP,OAAO;KACP,OAAO;KACP,UAAU;IACZ;IACA,SAAS;KACP,cAAc,OAAO,aAAa;MAQhC,IAAI,MAAM,UAAU,WAAW,MAAM,UAAU,QAAQ,aAAa,MAAM,UAAU,QAAQ,GAAG;MAC/F,MAAM,WAAW;MACjB,MAAM,QAAQ;MACd,MAAM,QAAQ;KAChB;KACA,UAAU,OAAO,SAAS;MACxB,MAAM,OAAO;KACf;KACA,WAAW,OAAO,OAAO,UAAU;MACjC,MAAM,QAAQ;MACd,MAAM,QAAQ;KAChB;KACA,cAAc,OAAO,aAAa;MAChC,MAAM,WAAW;KACnB;KACA,kBAAkB,OAAO,SAAS;MAChC,IAAI,MAAM,aAAa,MAAM,MAAM,WAAW;OAAE,GAAG,MAAM;OAAU,UAAU;MAAK;KACpF;IACF;GACF,CAAC;EACH;;;;;;;EAUA,SAAS,aAAa,UAA+B,MAA6B;GAChF,OAAO,aAAa,QAAQ,KAAK,UAAU,QAAQ,MAAM,KAAK,UAAU,IAAI;EAC9E;;;;;;;;;;;;;;;;;EC5FA,MAAa,uBAAuB;;EAGpC,MAAM,mBAAmB;EACzB,MAAM,mBAAmB;;;;;;;EAQzB,SAAgB,iBAAiB,QAAoC;GACnE,IAAI,OAAO,WAAW,YAAY,CAAC,OAAO,SAAS,MAAM,GAAG,OAAO;GACnE,OAAO,KAAK,IAAI,kBAAkB,KAAK,IAAI,kBAAkB,MAAM,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