dsh-bat-think 0.0.0-stage → 1.0.1

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/client.js ADDED
@@ -0,0 +1,1278 @@
1
+ /**
2
+ * Client half of the DSH desktop pet.
3
+ *
4
+ * Renders one entry into the frame-wide `shell.overlay` seat: a draggable pet
5
+ * that breathes, answers clicks, and swaps to its `thinking` frame with a
6
+ * bouncing three-dot bubble while an Agent is running. Every picture comes from
7
+ * `/dsh-bat-think/<file>` (served by index.js out of `assets/`), so replacing the
8
+ * PNGs is all that is needed to change how the pet looks.
9
+ */
10
+ window.__ModuleLoader__.load({
11
+ id: 'dsh-bat-think',
12
+ factory(require) {
13
+ 'use strict'
14
+
15
+ const React = require('react')
16
+ const { useEffect, useMemo, useRef, useState } = React
17
+ const h = React.createElement
18
+
19
+ const ROUTE = '/dsh-bat-think'
20
+ const KEY_POS = 'dsh-bat-think:position'
21
+ const KEY_SIZE = 'dsh-bat-think:size'
22
+ const KEY_COLLAPSED = 'dsh-bat-think:collapsed'
23
+ const KEY_GREETED = 'dsh-bat-think:greeted'
24
+ const KEY_ACCESSORY = 'dsh-bat-think:accessory'
25
+ const KEY_VARIANT = 'dsh-bat-think:variant'
26
+ const BUILD = '1.0.1'
27
+ const KEY_CANVAS_WIDTH = 'dsh-bat-think:canvas-width'
28
+ const MIN_SIZE = 96
29
+ const MAX_SIZE = 320
30
+ const DEFAULT_SIZE = 168
31
+ const DEFAULT_RATIO = 1.42
32
+ const EDGE_RIGHT = 24
33
+ const EDGE_BOTTOM = 16
34
+ const THINK_PAUSE_MS = 3000
35
+ const BUBBLE_MS = 3200
36
+
37
+ /** Used until `pet.json` arrives, and as the fallback for missing sections. */
38
+ const FALLBACK = {
39
+ name: '蝙蝠侠',
40
+ size: DEFAULT_SIZE,
41
+ canvas: { width: 512, height: 512, crop: [92, 76, 316, 359] },
42
+ hotspot: [148, 318, 214, 100],
43
+ variants: {
44
+ helmet: { idle: ['idle.png'], thinking: ['thinking.png'] },
45
+ bare: {
46
+ idle: ['idle-bare.png'],
47
+ thinking: ['thinking-bare.png'],
48
+ eyes: { open: 'eyes/open.png', half: 'eyes/half.png', closed: 'eyes/closed.png' },
49
+ },
50
+ },
51
+ fps: { idle: 3 },
52
+ sayings: ['阿尔弗雷德!', '正在归档……', '我要夜巡了'],
53
+ thinkingAck: '稍等',
54
+ accessories: { helmet: [], bare: [] },
55
+ }
56
+
57
+ // The pet watches the session list so the thought bubble follows the Agent.
58
+ // The service may arrive after this plugin applies, so the store is attached
59
+ // whenever it shows up and every mounted subscriber is re-read.
60
+ const EMPTY_SESSIONS = Object.freeze({ ids: [], byId: {} })
61
+ let bridgeTarget = null
62
+ let bridgeDispose = null
63
+ let modelDirectories = null
64
+ const modelListeners = new Set()
65
+ function setModelDirectories(next) {
66
+ if (modelDirectories === next) return
67
+ modelDirectories = next
68
+ for (const listener of [...modelListeners]) listener(next)
69
+ }
70
+ const bridgeListeners = new Set()
71
+
72
+ function bridgeEmit() {
73
+ for (const listener of [...bridgeListeners]) listener()
74
+ }
75
+
76
+ function attachSessionList(list) {
77
+ if (!list || typeof list.getSnapshot !== 'function' || bridgeTarget === list) return
78
+ if (bridgeDispose) bridgeDispose()
79
+ bridgeTarget = list
80
+ bridgeDispose = typeof list.subscribe === 'function' ? list.subscribe(bridgeEmit) : null
81
+ bridgeEmit()
82
+ }
83
+
84
+ function detachSessionList() {
85
+ if (bridgeDispose) bridgeDispose()
86
+ bridgeDispose = null
87
+ bridgeTarget = null
88
+ bridgeEmit()
89
+ }
90
+
91
+ function subscribeSessions(listener) {
92
+ bridgeListeners.add(listener)
93
+ return () => { bridgeListeners.delete(listener) }
94
+ }
95
+
96
+ function getSessionsSnapshot() {
97
+ return bridgeTarget ? bridgeTarget.getSnapshot() : EMPTY_SESSIONS
98
+ }
99
+
100
+ const STYLE_ID = 'dsh-bat-think-style'
101
+ const CSS = `
102
+ .dsh-bat-think-root {
103
+ position: fixed;
104
+ z-index: 70;
105
+ display: flex;
106
+ flex-direction: column;
107
+ align-items: center;
108
+ pointer-events: auto;
109
+ user-select: none;
110
+ -webkit-user-select: none;
111
+ touch-action: none;
112
+ font-family: inherit;
113
+ }
114
+ .dsh-bat-think-body {
115
+ position: relative;
116
+ width: 100%;
117
+ transform-origin: 50% 100%;
118
+ animation: dsh-bat-think-breathe 4.5s ease-in-out infinite;
119
+ }
120
+ .dsh-bat-think-body.is-bump { animation: dsh-bat-think-hop 0.42s ease-in-out 3; }
121
+ .dsh-bat-think-img {
122
+ display: block;
123
+ width: 100%;
124
+ height: auto;
125
+ cursor: grab;
126
+ filter: drop-shadow(0 10px 16px rgba(0, 0, 0, 0.18));
127
+ -webkit-user-drag: none;
128
+ }
129
+ .dsh-bat-think-img:active { cursor: grabbing; }
130
+ .dsh-bat-think-eyes {
131
+ position: absolute;
132
+ pointer-events: none;
133
+ -webkit-user-drag: none;
134
+ }
135
+ @keyframes dsh-bat-think-breathe {
136
+ 0%, 100% { transform: translateY(0) scale(1); }
137
+ 50% { transform: translateY(-3px) scale(1.02); }
138
+ }
139
+ @keyframes dsh-bat-think-hop {
140
+ 0%, 100% { transform: translateY(0) scale(1); }
141
+ 35% { transform: translateY(-16px) scale(1.03); }
142
+ 65% { transform: translateY(0) scale(0.985); }
143
+ }
144
+ @media (prefers-reduced-motion: reduce) {
145
+ .dsh-bat-think-body, .dsh-bat-think-body.is-bump { animation: none; }
146
+ }
147
+ .dsh-bat-think-bubble {
148
+ position: absolute;
149
+ bottom: calc(100% + 4px);
150
+ left: 50%;
151
+ --dsh-bat-think-shift: translateX(-50%);
152
+ transform: var(--dsh-bat-think-shift);
153
+ width: max-content;
154
+ max-width: min(240px, calc(100vw - 24px));
155
+ padding: 8px 12px;
156
+ border-radius: 14px;
157
+ background: var(--dsw-alias-bg-layer-2, #ffffff);
158
+ color: var(--dsw-alias-label-primary, #1f2328);
159
+ border: 1px solid var(--dsw-alias-border-l1, rgba(0, 0, 0, 0.08));
160
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.14);
161
+ font-size: 13px;
162
+ line-height: 1.45;
163
+ text-align: center;
164
+ pointer-events: none;
165
+ animation: dsh-bat-think-pop 0.18s ease-out;
166
+ }
167
+ .dsh-bat-think-bubble.is-left { left: 0; --dsh-bat-think-shift: none; }
168
+ .dsh-bat-think-bubble.is-right { left: auto; right: 0; --dsh-bat-think-shift: none; }
169
+ .dsh-bat-think-bubble.is-left::after { left: 26px; }
170
+ .dsh-bat-think-bubble.is-right::after { left: auto; right: 26px; }
171
+ .dsh-bat-think-bubble::after {
172
+ content: '';
173
+ position: absolute;
174
+ top: 100%;
175
+ left: 50%;
176
+ width: 10px;
177
+ height: 10px;
178
+ margin-top: -5px;
179
+ transform: translateX(-50%) rotate(45deg);
180
+ background: var(--dsw-alias-bg-layer-2, #ffffff);
181
+ border-right: 1px solid var(--dsw-alias-border-l1, rgba(0, 0, 0, 0.08));
182
+ border-bottom: 1px solid var(--dsw-alias-border-l1, rgba(0, 0, 0, 0.08));
183
+ }
184
+ .dsh-bat-think-think {
185
+ position: absolute;
186
+ bottom: calc(100% + 4px);
187
+ left: 50%;
188
+ --dsh-bat-think-shift: translateX(-50%);
189
+ transform: var(--dsh-bat-think-shift);
190
+ width: max-content;
191
+ display: flex;
192
+ align-items: center;
193
+ gap: 6px;
194
+ padding: 10px 15px;
195
+ border-radius: 16px;
196
+ background: var(--dsw-alias-bg-layer-2, #ffffff);
197
+ border: 1px solid var(--dsw-alias-border-l1, rgba(0, 0, 0, 0.08));
198
+ box-shadow: 0 8px 22px rgba(0, 0, 0, 0.14);
199
+ pointer-events: none;
200
+ animation: dsh-bat-think-pop 0.18s ease-out;
201
+ }
202
+ .dsh-bat-think-think.is-left { left: 0; --dsh-bat-think-shift: none; }
203
+ .dsh-bat-think-think.is-right { left: auto; right: 0; --dsh-bat-think-shift: none; }
204
+ .dsh-bat-think-think.is-left::after { left: 26px; }
205
+ .dsh-bat-think-think.is-right::after { left: auto; right: 26px; }
206
+ .dsh-bat-think-think::after {
207
+ content: '';
208
+ position: absolute;
209
+ top: 100%;
210
+ left: 50%;
211
+ width: 9px;
212
+ height: 9px;
213
+ margin-top: -5px;
214
+ transform: translateX(-50%) rotate(45deg);
215
+ background: var(--dsw-alias-bg-layer-2, #ffffff);
216
+ border-right: 1px solid var(--dsw-alias-border-l1, rgba(0, 0, 0, 0.08));
217
+ border-bottom: 1px solid var(--dsw-alias-border-l1, rgba(0, 0, 0, 0.08));
218
+ }
219
+ .dsh-bat-think-dot {
220
+ width: 7px;
221
+ height: 7px;
222
+ border-radius: 50%;
223
+ background: var(--dsw-alias-label-tertiary, #8a94a6);
224
+ animation: dsh-bat-think-dot-bounce 1.15s ease-in-out infinite;
225
+ }
226
+ .dsh-bat-think-dot:nth-child(2) { animation-delay: 0.16s; }
227
+ .dsh-bat-think-dot:nth-child(3) { animation-delay: 0.32s; }
228
+ @keyframes dsh-bat-think-dot-bounce {
229
+ 0%, 75%, 100% { opacity: 0.35; transform: translateY(0); }
230
+ 35% { opacity: 1; transform: translateY(-3px); }
231
+ }
232
+ @keyframes dsh-bat-think-pop {
233
+ from { opacity: 0; transform: var(--dsh-bat-think-shift) translateY(4px); }
234
+ to { opacity: 1; transform: var(--dsh-bat-think-shift) translateY(0); }
235
+ }
236
+ .dsh-bat-think-tools {
237
+ position: absolute;
238
+ top: -12px;
239
+ right: -8px;
240
+ display: flex;
241
+ gap: 4px;
242
+ opacity: 0;
243
+ pointer-events: none;
244
+ transition: opacity 0.15s ease;
245
+ }
246
+ .dsh-bat-think-root:hover .dsh-bat-think-tools { opacity: 1; pointer-events: auto; }
247
+ .dsh-bat-think-tool {
248
+ width: 22px;
249
+ height: 22px;
250
+ padding: 0;
251
+ display: flex;
252
+ align-items: center;
253
+ justify-content: center;
254
+ border-radius: 50%;
255
+ border: 1px solid var(--dsw-alias-border-l1, rgba(0, 0, 0, 0.1));
256
+ background: var(--dsw-alias-bg-layer-2, #ffffff);
257
+ color: var(--dsw-alias-label-secondary, #5b6470);
258
+ font-size: 13px;
259
+ line-height: 1;
260
+ cursor: pointer;
261
+ }
262
+ .dsh-bat-think-tool:hover { background: var(--dsw-alias-interactive-bg-hover, rgba(0, 0, 0, 0.06)); }
263
+ .dsh-bat-think-laptop {
264
+ position: absolute;
265
+ padding: 0;
266
+ border: 0;
267
+ border-radius: 12px;
268
+ background: transparent;
269
+ cursor: pointer;
270
+ -webkit-appearance: none;
271
+ appearance: none;
272
+ }
273
+ .dsh-bat-think-laptop:hover { background: rgba(255, 255, 255, 0.14); }
274
+ .dsh-bat-think-usage {
275
+ position: absolute;
276
+ bottom: calc(100% + 6px);
277
+ left: 50%;
278
+ --dsh-bat-think-shift: translateX(-50%);
279
+ transform: var(--dsh-bat-think-shift);
280
+ width: 210px;
281
+ max-width: min(240px, calc(100vw - 24px));
282
+ padding: 10px 12px;
283
+ border-radius: 14px;
284
+ background: var(--dsw-alias-bg-layer-2, #ffffff);
285
+ color: var(--dsw-alias-label-primary, #1f2328);
286
+ border: 1px solid var(--dsw-alias-border-l1, rgba(0, 0, 0, 0.08));
287
+ box-shadow: 0 10px 26px rgba(0, 0, 0, 0.16);
288
+ font-size: 12px;
289
+ line-height: 1.5;
290
+ pointer-events: auto;
291
+ animation: dsh-bat-think-pop 0.18s ease-out;
292
+ }
293
+ .dsh-bat-think-usage.is-left { left: 0; --dsh-bat-think-shift: none; }
294
+ .dsh-bat-think-usage.is-right { left: auto; right: 0; --dsh-bat-think-shift: none; }
295
+ .dsh-bat-think-usage-head {
296
+ display: flex;
297
+ align-items: center;
298
+ justify-content: space-between;
299
+ margin-bottom: 4px;
300
+ font-weight: 600;
301
+ }
302
+ .dsh-bat-think-usage-close {
303
+ width: 18px;
304
+ height: 18px;
305
+ padding: 0;
306
+ border: 0;
307
+ border-radius: 50%;
308
+ background: transparent;
309
+ color: var(--dsw-alias-label-tertiary, #8a94a6);
310
+ font-size: 14px;
311
+ line-height: 1;
312
+ cursor: pointer;
313
+ display: flex;
314
+ align-items: center;
315
+ justify-content: center;
316
+ }
317
+ .dsh-bat-think-usage-close:hover { background: var(--dsw-alias-interactive-bg-hover, rgba(0, 0, 0, 0.06)); }
318
+ .dsh-bat-think-usage-row {
319
+ display: flex;
320
+ align-items: baseline;
321
+ justify-content: space-between;
322
+ gap: 8px;
323
+ color: var(--dsw-alias-label-secondary, #5b6470);
324
+ }
325
+ .dsh-bat-think-usage-row b {
326
+ max-width: 132px;
327
+ color: var(--dsw-alias-label-primary, #1f2328);
328
+ font-weight: 600;
329
+ font-variant-numeric: tabular-nums;
330
+ overflow: hidden;
331
+ text-overflow: ellipsis;
332
+ white-space: nowrap;
333
+ }
334
+ .dsh-bat-think-usage-sub {
335
+ display: flex;
336
+ justify-content: space-between;
337
+ gap: 8px;
338
+ margin-top: 6px;
339
+ color: var(--dsw-alias-label-tertiary, #8a94a6);
340
+ font-size: 11px;
341
+ font-variant-numeric: tabular-nums;
342
+ }
343
+ .dsh-bat-think-usage-bar {
344
+ height: 4px;
345
+ margin-top: 3px;
346
+ border-radius: 2px;
347
+ background: var(--dsw-alias-border-l1, rgba(0, 0, 0, 0.08));
348
+ overflow: hidden;
349
+ }
350
+ .dsh-bat-think-usage-bar i {
351
+ display: block;
352
+ height: 100%;
353
+ border-radius: 2px;
354
+ background: var(--dsw-alias-state-business-primary, #4d6bfe);
355
+ }
356
+ .dsh-bat-think-accessory {
357
+ position: absolute;
358
+ background-repeat: no-repeat;
359
+ pointer-events: auto;
360
+ cursor: grab;
361
+ }
362
+ .dsh-bat-think-accessory:active { cursor: grabbing; }
363
+ .dsh-bat-think-accessory:hover { filter: drop-shadow(0 0 5px rgba(255, 255, 255, 0.5)); }
364
+ .dsh-bat-think-chip {
365
+ position: fixed;
366
+ z-index: 70;
367
+ width: 40px;
368
+ height: 40px;
369
+ padding: 0;
370
+ overflow: hidden;
371
+ border-radius: 50%;
372
+ border: 1px solid var(--dsw-alias-border-l1, rgba(0, 0, 0, 0.1));
373
+ background: var(--dsw-alias-bg-layer-2, #ffffff);
374
+ box-shadow: 0 6px 16px rgba(0, 0, 0, 0.16);
375
+ cursor: pointer;
376
+ pointer-events: auto;
377
+ display: flex;
378
+ align-items: center;
379
+ justify-content: center;
380
+ }
381
+ .dsh-bat-think-chip img { width: 40px; height: 40px; object-fit: cover; object-position: 50% 12%; pointer-events: none; }
382
+ .dsh-bat-think-chip:hover { background: var(--dsw-alias-interactive-bg-hover, rgba(0, 0, 0, 0.06)); }
383
+ `
384
+
385
+ function installStyle() {
386
+ if (document.getElementById(STYLE_ID)) return () => {}
387
+ const style = document.createElement('style')
388
+ style.id = STYLE_ID
389
+ style.textContent = CSS
390
+ document.head.appendChild(style)
391
+ return () => style.remove()
392
+ }
393
+
394
+ function readNumber(key, fallback) {
395
+ try {
396
+ const value = Number(localStorage.getItem(key))
397
+ return Number.isFinite(value) && value > 0 ? value : fallback
398
+ } catch {
399
+ return fallback
400
+ }
401
+ }
402
+
403
+ function readPosition() {
404
+ try {
405
+ const raw = localStorage.getItem(KEY_POS)
406
+ if (!raw) return null
407
+ const parsed = JSON.parse(raw)
408
+ if (!parsed || !Number.isFinite(parsed.x) || !Number.isFinite(parsed.y)) return null
409
+ return { x: parsed.x, y: parsed.y }
410
+ } catch {
411
+ return null
412
+ }
413
+ }
414
+
415
+ function writeSetting(key, value) {
416
+ try {
417
+ localStorage.setItem(key, typeof value === 'string' ? value : JSON.stringify(value))
418
+ } catch {
419
+ // Private mode or a locked-down storage keeps the value for this page only.
420
+ }
421
+ }
422
+
423
+ function assetUrl(file) {
424
+ return `${ROUTE}/${String(file).split('/').map(encodeURIComponent).join('/')}`
425
+ }
426
+
427
+ function accessoryUrl(file) {
428
+ return `${ROUTE}/accessories/${String(file).split('/').map(encodeURIComponent).join('/')}`
429
+ }
430
+
431
+ function readAccessory() {
432
+ try {
433
+ const raw = localStorage.getItem(KEY_ACCESSORY)
434
+ if (!raw) return null
435
+ const parsed = JSON.parse(raw)
436
+ if (!parsed || typeof parsed.file !== 'string' || parsed.file === '') return null
437
+ return {
438
+ file: parsed.file,
439
+ dx: Number.isFinite(parsed.dx) ? parsed.dx : 0,
440
+ dy: Number.isFinite(parsed.dy) ? parsed.dy : 0,
441
+ scale: Number.isFinite(parsed.scale) && parsed.scale > 0 ? parsed.scale : 1,
442
+ }
443
+ } catch {
444
+ return null
445
+ }
446
+ }
447
+
448
+ function writeAccessory(value) {
449
+ try {
450
+ if (value) localStorage.setItem(KEY_ACCESSORY, JSON.stringify(value))
451
+ else localStorage.removeItem(KEY_ACCESSORY)
452
+ } catch {}
453
+ }
454
+
455
+ function clampSize(value) {
456
+ const size = Number(value)
457
+ if (!Number.isFinite(size) || size <= 0) return DEFAULT_SIZE
458
+ return Math.max(MIN_SIZE, Math.min(MAX_SIZE, size))
459
+ }
460
+
461
+ function clampPosition(x, y, width, height) {
462
+ const viewportWidth = window.innerWidth || 1024
463
+ const viewportHeight = window.innerHeight || 768
464
+ // Keep the pet mostly on screen while allowing it to sit against an edge.
465
+ const minX = -width * 0.15
466
+ const maxX = viewportWidth - width * 0.85
467
+ const minY = 0
468
+ const maxY = viewportHeight - height * 0.55
469
+ return {
470
+ x: Math.min(Math.max(x, minX), Math.max(minX, maxX)),
471
+ y: Math.min(Math.max(y, minY), Math.max(minY, maxY)),
472
+ }
473
+ }
474
+
475
+ function formatCount(value) {
476
+ return typeof value === 'number' && Number.isFinite(value) ? value.toLocaleString('en-US') : '—'
477
+ }
478
+
479
+ /** The Session the main view is showing, following both snapshot spellings. */
480
+ function mainSessionIdOf(snapshot) {
481
+ if (!snapshot || typeof snapshot !== 'object') return undefined
482
+ if (typeof snapshot.current === 'string' && snapshot.current !== '') return snapshot.current
483
+ const byId = snapshot.byId
484
+ if (!byId || typeof byId !== 'object') return undefined
485
+ for (const row of Object.values(byId)) {
486
+ if (!row || typeof row !== 'object') continue
487
+ const held = row.retainedBy && row.retainedBy.mainView
488
+ if (typeof held === 'number' && held > 0) return row.id
489
+ }
490
+ return undefined
491
+ }
492
+
493
+ function mergeManifest(base, extra) {
494
+ const variants = { ...(base.variants || {}) }
495
+ for (const [name, definition] of Object.entries(extra.variants || {})) {
496
+ variants[name] = { ...(variants[name] || {}), ...definition }
497
+ }
498
+ const accessories = extra.accessories && !Array.isArray(extra.accessories)
499
+ ? { ...(base.accessories || {}), ...extra.accessories }
500
+ : (base.accessories || { helmet: [], bare: [] })
501
+ return {
502
+ ...base,
503
+ ...extra,
504
+ variants,
505
+ accessories,
506
+ fps: { ...(base.fps || {}), ...(extra.fps || {}) },
507
+ sayings: Array.isArray(extra.sayings) && extra.sayings.length > 0
508
+ ? extra.sayings.map(String)
509
+ : base.sayings,
510
+ }
511
+ }
512
+
513
+ function readVariant() {
514
+ try {
515
+ return localStorage.getItem(KEY_VARIANT) === 'bare' ? 'bare' : 'helmet'
516
+ } catch {
517
+ return 'helmet'
518
+ }
519
+ }
520
+
521
+ function Pet() {
522
+ // A single line in the browser console makes a missing registration obvious.
523
+ useEffect(() => { console.info('[dsh-bat-think] mounted at shell.overlay') }, [])
524
+
525
+ const [manifest, setManifest] = useState(FALLBACK)
526
+ const [bubble, setBubble] = useState('')
527
+ const [variant, setVariant] = useState(readVariant)
528
+ const [eyeFrame, setEyeFrame] = useState('open')
529
+ const [position, setPosition] = useState(null)
530
+ const [size, setSize] = useState(() => clampSize(readNumber(KEY_SIZE, DEFAULT_SIZE)))
531
+ const [ratio, setRatio] = useState(DEFAULT_RATIO)
532
+ const [collapsed, setCollapsed] = useState(() => {
533
+ try { return localStorage.getItem(KEY_COLLAPSED) === '1' } catch { return false }
534
+ })
535
+ const [missing, setMissing] = useState(false)
536
+ const [loadAttempt, setLoadAttempt] = useState(0)
537
+ const [failedFile, setFailedFile] = useState('')
538
+ const [failedInfo, setFailedInfo] = useState('')
539
+ const [blobs, setBlobs] = useState({})
540
+ const blobsRef = useRef(blobs)
541
+ blobsRef.current = blobs
542
+ useEffect(() => () => {
543
+ for (const url of Object.values(blobsRef.current)) {
544
+ try { URL.revokeObjectURL(url) } catch {}
545
+ }
546
+ }, [])
547
+ const [frame, setFrame] = useState(0)
548
+ const [bump, setBump] = useState(false)
549
+ const [thinkPaused, setThinkPaused] = useState(false)
550
+ const [usageOpen, setUsageOpen] = useState(false)
551
+ const [accessory, setAccessory] = useState(readAccessory)
552
+ const [accessoryList, setAccessoryList] = useState([])
553
+ const [accMeta, setAccMeta] = useState(null)
554
+
555
+ const sessionState = React.useSyncExternalStore(subscribeSessions, getSessionsSnapshot)
556
+ const thinking = useMemo(() => {
557
+ const ids = sessionState && sessionState.ids
558
+ const byId = sessionState && sessionState.byId
559
+ if (!Array.isArray(ids) || !byId) return false
560
+ return ids.some((id) => byId[id] && byId[id].running === true)
561
+ }, [sessionState])
562
+
563
+ const mainSessionId = useMemo(() => {
564
+ const shown = mainSessionIdOf(sessionState)
565
+ if (shown) return shown
566
+ const ids = sessionState && sessionState.ids
567
+ return Array.isArray(ids) && ids.length > 0 ? ids[0] : undefined
568
+ }, [sessionState])
569
+ const projectionValues = useMemo(() => {
570
+ const row = mainSessionId && sessionState && sessionState.byId ? sessionState.byId[mainSessionId] : undefined
571
+ const block = mainSessionId && sessionState && sessionState.projectionsBySession
572
+ ? sessionState.projectionsBySession[mainSessionId]
573
+ : undefined
574
+ const rowValues = row && row.projectionValues
575
+ const blockValues = block && block.values
576
+ if (!rowValues && !blockValues) return null
577
+ // The list row and the per-session block carry the same projection
578
+ // values; merge them so whichever arrives first is usable.
579
+ return { ...(blockValues || {}), ...(rowValues || {}) }
580
+ }, [sessionState, mainSessionId])
581
+ const usage = projectionValues && projectionValues.tokenUsage
582
+ const pressure = projectionValues && projectionValues.contextPressure
583
+ const usedTokens = pressure ? (pressure.projectedTokens ?? pressure.pressureTokens) : undefined
584
+ const windowTokens = pressure ? pressure.contextWindow : undefined
585
+ const contextPercent = typeof usedTokens === 'number' && typeof windowTokens === 'number' && windowTokens > 0
586
+ ? Math.min(100, Math.round((usedTokens / windowTokens) * 100))
587
+ : null
588
+ const hasUsage = Boolean(usage || pressure)
589
+ const totals = useMemo(() => {
590
+ const byId = (sessionState && sessionState.byId) || {}
591
+ const sum = {
592
+ sessions: 0,
593
+ uncachedInputTokens: 0,
594
+ outputTokens: 0,
595
+ cacheReadTokens: 0,
596
+ cacheWriteTokens: 0,
597
+ }
598
+ for (const row of Object.values(byId)) {
599
+ const value = row && row.projectionValues && row.projectionValues.tokenUsage
600
+ if (!value) continue
601
+ sum.sessions += 1
602
+ sum.uncachedInputTokens += Number(value.uncachedInputTokens) || 0
603
+ sum.outputTokens += Number(value.outputTokens) || 0
604
+ sum.cacheReadTokens += Number(value.cacheReadTokens) || 0
605
+ sum.cacheWriteTokens += Number(value.cacheWriteTokens) || 0
606
+ }
607
+ return sum
608
+ }, [sessionState])
609
+ const [modelService, setModelService] = useState(modelDirectories)
610
+ useEffect(() => {
611
+ const listener = (next) => setModelService(next)
612
+ modelListeners.add(listener)
613
+ setModelService(modelDirectories)
614
+ return () => { modelListeners.delete(listener) }
615
+ }, [])
616
+ const [modelLabel, setModelLabel] = useState('')
617
+ useEffect(() => {
618
+ setModelLabel('')
619
+ if (!mainSessionId || !modelService) return undefined
620
+ let directory
621
+ try {
622
+ directory = modelService.directoryFor(mainSessionId)
623
+ } catch {
624
+ return undefined
625
+ }
626
+ const read = () => {
627
+ try {
628
+ const snapshot = directory.store.getSnapshot()
629
+ const current = snapshot && snapshot.current
630
+ if (!current) return ''
631
+ const groups = snapshot.groups || []
632
+ const group = groups.find((candidate) => candidate && candidate.id === current.provider)
633
+ const model = group && (group.models || []).find((candidate) => candidate && candidate.id === current.model)
634
+ return (model && model.name) || current.model || ''
635
+ } catch {
636
+ return ''
637
+ }
638
+ }
639
+ setModelLabel(read())
640
+ const dispose = directory.store.subscribe(() => setModelLabel(read()))
641
+ return () => { try { dispose() } catch {} }
642
+ }, [mainSessionId, modelService])
643
+
644
+ const variantAccessories = useMemo(() => {
645
+ const prefix = `${variant}/`
646
+ const fromIndex = accessoryList.filter((file) => String(file).startsWith(prefix))
647
+ if (fromIndex.length > 0) return fromIndex
648
+ const map = manifest.accessories && !Array.isArray(manifest.accessories) ? manifest.accessories : {}
649
+ return Array.isArray(map[variant]) ? map[variant].map(String) : []
650
+ }, [accessoryList, manifest, variant])
651
+
652
+ // Accessories are discovered from the folder; `pet.json` lists the same
653
+ // names as a fallback for a Host that has not reloaded yet.
654
+ useEffect(() => {
655
+ let cancelled = false
656
+ fetch(`${ROUTE}/accessories/index.json`, { cache: 'no-cache' })
657
+ .then((response) => (response.ok ? response.json() : null))
658
+ .then((json) => {
659
+ if (cancelled || !json || !Array.isArray(json.files) || json.files.length === 0) return
660
+ setAccessoryList(json.files.map(String))
661
+ })
662
+ .catch(() => {})
663
+ return () => { cancelled = true }
664
+ }, [])
665
+
666
+ useEffect(() => {
667
+ if (variantAccessories.length === 0) return
668
+ setAccessory((current) => {
669
+ if (!current || variantAccessories.includes(current.file)) return current
670
+ writeAccessory(null)
671
+ return null
672
+ })
673
+ }, [variantAccessories])
674
+
675
+ // Bounding box and alpha mask of the current accessory, for placement and
676
+ // for "click the pixels, not the box" removal.
677
+ useEffect(() => {
678
+ const file = accessory ? accessory.file : ''
679
+ setAccMeta(null)
680
+ if (!file) return undefined
681
+ let cancelled = false
682
+ const image = new Image()
683
+ image.onload = () => {
684
+ if (cancelled) return
685
+ const width = image.naturalWidth
686
+ const height = image.naturalHeight
687
+ const canvas = document.createElement('canvas')
688
+ canvas.width = width
689
+ canvas.height = height
690
+ const context = canvas.getContext('2d')
691
+ if (!context) return
692
+ context.drawImage(image, 0, 0)
693
+ let data = null
694
+ let box = { x: 0, y: 0, w: width, h: height }
695
+ try {
696
+ data = context.getImageData(0, 0, width, height)
697
+ let minX = width
698
+ let minY = height
699
+ let maxX = -1
700
+ let maxY = -1
701
+ for (let y = 0; y < height; y += 1) {
702
+ for (let x = 0; x < width; x += 1) {
703
+ if (data.data[(y * width + x) * 4 + 3] > 8) {
704
+ if (x < minX) minX = x
705
+ if (y < minY) minY = y
706
+ if (x > maxX) maxX = x
707
+ if (y > maxY) maxY = y
708
+ }
709
+ }
710
+ }
711
+ if (maxX >= minX) box = { x: minX, y: minY, w: maxX - minX + 1, h: maxY - minY + 1 }
712
+ } catch {
713
+ data = null
714
+ }
715
+ setAccMeta({ width, height, box, data })
716
+ }
717
+ image.onerror = () => { if (!cancelled) setAccMeta(null) }
718
+ image.src = accessoryUrl(file)
719
+ return () => { cancelled = true; image.onload = null; image.onerror = null }
720
+ }, [accessory && accessory.file])
721
+
722
+ const dragRef = useRef(null)
723
+ const alive = useRef(true)
724
+ const bubbleTimer = useRef(0)
725
+ const bumpTimer = useRef(0)
726
+ const thinkTimer = useRef(0)
727
+
728
+ useEffect(() => {
729
+ alive.current = true
730
+ return () => { alive.current = false }
731
+ }, [])
732
+
733
+ // Artwork manifest: the client keeps working with the fallback if it fails.
734
+ useEffect(() => {
735
+ let cancelled = false
736
+ fetch(`${ROUTE}/pet.json`, { cache: 'no-cache' })
737
+ .then((response) => (response.ok ? response.json() : null))
738
+ .then((json) => {
739
+ if (cancelled || !json) return
740
+ const merged = mergeManifest(FALLBACK, json)
741
+ setManifest(merged)
742
+ const cropWidth = merged.canvas && Array.isArray(merged.canvas.crop) ? Number(merged.canvas.crop[2]) : 0
743
+ let stored = 0
744
+ try { stored = Number(localStorage.getItem(KEY_SIZE)) } catch {}
745
+ if (!Number.isFinite(stored) || stored <= 0) {
746
+ setSize(clampSize(json.size))
747
+ } else if (cropWidth > 0) {
748
+ // The shared canvas got wider when the bare variant arrived: scale
749
+ // the saved size once so the pet keeps its on-screen size.
750
+ let previousWidth = readNumber(KEY_CANVAS_WIDTH, 0)
751
+ if (!previousWidth && stored > 0) previousWidth = 247
752
+ if (previousWidth > 0 && Math.abs(previousWidth - cropWidth) > 1) {
753
+ setSize((current) => clampSize(Math.round(current * (cropWidth / previousWidth))))
754
+ }
755
+ }
756
+ if (cropWidth > 0) writeSetting(KEY_CANVAS_WIDTH, String(cropWidth))
757
+ })
758
+ .catch((error) => console.warn('[dsh-bat-think] pet.json could not be loaded', error))
759
+ return () => { cancelled = true }
760
+ }, [])
761
+
762
+ // First position: the saved one, otherwise bottom-right above the composer.
763
+ useEffect(() => {
764
+ const started = readPosition()
765
+ const width = clampSize(readNumber(KEY_SIZE, DEFAULT_SIZE))
766
+ const start = started ?? {
767
+ x: (window.innerWidth || 1024) - width - EDGE_RIGHT,
768
+ y: (window.innerHeight || 768) - width * DEFAULT_RATIO - EDGE_BOTTOM,
769
+ }
770
+ setPosition(clampPosition(start.x, start.y, width, width * DEFAULT_RATIO))
771
+ // eslint-disable-next-line react-hooks/exhaustive-deps
772
+ }, [])
773
+
774
+ // Keep the pet inside the viewport when the window, the size or the
775
+ // artwork's aspect ratio changes.
776
+ useEffect(() => {
777
+ setPosition((current) => (current ? clampPosition(current.x, current.y, size, size * ratio) : current))
778
+ }, [ratio, size])
779
+
780
+ useEffect(() => {
781
+ const onResize = () => {
782
+ setPosition((current) => (current ? clampPosition(current.x, current.y, size, size * ratio) : current))
783
+ }
784
+ window.addEventListener('resize', onResize)
785
+ return () => window.removeEventListener('resize', onResize)
786
+ }, [size, ratio])
787
+
788
+ const frames = useMemo(() => {
789
+ const definition = (manifest.variants && manifest.variants[variant]) || {}
790
+ const list = thinking && Array.isArray(definition.thinking) && definition.thinking.length > 0
791
+ ? definition.thinking
792
+ : definition.idle
793
+ return Array.isArray(list) && list.length > 0 ? list : ['idle.png']
794
+ }, [manifest, thinking, variant])
795
+
796
+ // Warm both frames so switching to the working picture does not flicker.
797
+ useEffect(() => {
798
+ const files = []
799
+ for (const definition of Object.values(manifest.variants || {})) {
800
+ files.push(...(definition.idle || []), ...(definition.thinking || []), ...Object.values(definition.eyes || {}))
801
+ }
802
+ for (const file of files) {
803
+ const image = new Image()
804
+ image.src = `${ROUTE}/${String(file).split('/').map(encodeURIComponent).join('/')}`
805
+ }
806
+ }, [manifest])
807
+
808
+ useEffect(() => {
809
+ setFrame(0)
810
+ if (frames.length < 2) return undefined
811
+ const fps = Number(manifest.fps && manifest.fps[thinking ? 'thinking' : 'idle']) || 4
812
+ const timer = setInterval(() => {
813
+ if (!alive.current) return
814
+ setFrame((index) => (index + 1) % frames.length)
815
+ }, Math.max(90, 1000 / fps))
816
+ return () => clearInterval(timer)
817
+ }, [frames, manifest, thinking])
818
+
819
+ // Blink only in the bare-face variant: the eye layer steps open → half →
820
+ // closed → half → open on a loose timer.
821
+ useEffect(() => {
822
+ if (variant !== 'bare') { setEyeFrame('open'); return undefined }
823
+ const sequence = ['open', 'half', 'closed', 'half', 'open']
824
+ let step = 0
825
+ let timer = 0
826
+ setEyeFrame('open')
827
+ const tick = () => {
828
+ step = (step + 1) % sequence.length
829
+ if (alive.current) setEyeFrame(sequence[step])
830
+ const wait = step === 0 ? 2800 + Math.random() * 3800 : 95
831
+ timer = window.setTimeout(tick, wait)
832
+ }
833
+ timer = window.setTimeout(tick, 2800 + Math.random() * 3800)
834
+ return () => window.clearTimeout(timer)
835
+ }, [variant])
836
+
837
+ const say = (text) => {
838
+ if (!text) return
839
+ setBubble(text)
840
+ window.clearTimeout(bubbleTimer.current)
841
+ bubbleTimer.current = window.setTimeout(() => {
842
+ if (alive.current) setBubble('')
843
+ }, BUBBLE_MS)
844
+ }
845
+
846
+ // Greet once per browser session.
847
+ useEffect(() => {
848
+ if (!position) return
849
+ let greeted = ''
850
+ try { greeted = sessionStorage.getItem(KEY_GREETED) || '' } catch { greeted = '1' }
851
+ if (greeted === '1') return
852
+ const timer = window.setTimeout(() => say('拖我换个位置,点我试试~'), 900)
853
+ try { sessionStorage.setItem(KEY_GREETED, '1') } catch {}
854
+ return () => window.clearTimeout(timer)
855
+ // eslint-disable-next-line react-hooks/exhaustive-deps
856
+ }, [position])
857
+
858
+ useEffect(() => () => {
859
+ window.clearTimeout(bubbleTimer.current)
860
+ window.clearTimeout(bumpTimer.current)
861
+ window.clearTimeout(thinkTimer.current)
862
+ }, [])
863
+
864
+ const adjustSize = (delta) => {
865
+ const next = clampSize(size + delta)
866
+ setSize(next)
867
+ writeSetting(KEY_SIZE, String(next))
868
+ }
869
+
870
+ const toggleCollapsed = (next) => {
871
+ setCollapsed(next)
872
+ try { localStorage.setItem(KEY_COLLAPSED, next ? '1' : '0') } catch {}
873
+ }
874
+
875
+ const stopTool = (event) => {
876
+ event.stopPropagation()
877
+ event.preventDefault()
878
+ }
879
+
880
+ // A press without movement is a click. While the Agent is running the
881
+ // thought bubble gives way to a short "稍等", then comes back.
882
+ const react = () => {
883
+ if (usageOpen) setUsageOpen(false)
884
+ setBump(true)
885
+ window.clearTimeout(bumpTimer.current)
886
+ bumpTimer.current = window.setTimeout(() => {
887
+ if (alive.current) setBump(false)
888
+ }, 1300)
889
+
890
+ if (thinking) {
891
+ setThinkPaused(true)
892
+ window.clearTimeout(thinkTimer.current)
893
+ thinkTimer.current = window.setTimeout(() => {
894
+ if (alive.current) setThinkPaused(false)
895
+ }, THINK_PAUSE_MS)
896
+ say(manifest.thinkingAck || '稍等')
897
+ return
898
+ }
899
+
900
+ const lines = manifest.sayings
901
+ say(lines[Math.floor(Math.random() * lines.length)])
902
+ }
903
+
904
+ useEffect(() => {
905
+ setMissing(false)
906
+ setLoadAttempt(0)
907
+ }, [variant])
908
+
909
+ const toggleVariant = () => {
910
+ const next = variant === 'bare' ? 'helmet' : 'bare'
911
+ setVariant(next)
912
+ try { localStorage.setItem(KEY_VARIANT, next) } catch {}
913
+ setAccessory(null)
914
+ writeAccessory(null)
915
+ setBump(true)
916
+ window.clearTimeout(bumpTimer.current)
917
+ bumpTimer.current = window.setTimeout(() => {
918
+ if (alive.current) setBump(false)
919
+ }, 1300)
920
+ say(next === 'bare' ? '摘下面罩' : '戴上面罩')
921
+ }
922
+
923
+ // Three quick clicks swap the helmet, so a single click waits briefly.
924
+ const clickRef = useRef({ count: 0, last: 0, timer: 0 })
925
+ const onPetClick = () => {
926
+ const now = Date.now()
927
+ const state = clickRef.current
928
+ if (now - state.last > 700) state.count = 0
929
+ state.last = now
930
+ state.count += 1
931
+ window.clearTimeout(state.timer)
932
+ if (state.count >= 3) {
933
+ state.count = 0
934
+ toggleVariant()
935
+ return
936
+ }
937
+ state.timer = window.setTimeout(() => {
938
+ if (alive.current) react()
939
+ }, 300)
940
+ }
941
+
942
+ const rollAccessory = () => {
943
+ const list = variantAccessories
944
+ if (list.length === 0) {
945
+ say('还没有配件,把 PNG 放进 assets/accessories/ 就行')
946
+ return
947
+ }
948
+ const pool = list.length > 1 && accessory ? list.filter((file) => file !== accessory.file) : list
949
+ const file = pool[Math.floor(Math.random() * pool.length)] || list[0]
950
+ const next = { file }
951
+ setAccessory(next)
952
+ writeAccessory(next)
953
+ setBump(true)
954
+ window.clearTimeout(bumpTimer.current)
955
+ bumpTimer.current = window.setTimeout(() => {
956
+ if (alive.current) setBump(false)
957
+ }, 1300)
958
+ }
959
+
960
+ // Clicking the sticker's own pixels takes it off; its empty box pokes the pet.
961
+ const onAccessoryClick = (event) => {
962
+ event.stopPropagation()
963
+ const rect = event.currentTarget.getBoundingClientRect()
964
+ const meta = accMeta
965
+ if (meta && meta.data && rect.width > 0 && rect.height > 0) {
966
+ const x = Math.min(meta.width - 1, Math.max(0, Math.floor(meta.box.x + ((event.clientX - rect.left) / rect.width) * meta.box.w)))
967
+ const y = Math.min(meta.height - 1, Math.max(0, Math.floor(meta.box.y + ((event.clientY - rect.top) / rect.height) * meta.box.h)))
968
+ if (meta.data.data[(y * meta.width + x) * 4 + 3] < 24) {
969
+ react()
970
+ return
971
+ }
972
+ }
973
+ setAccessory(null)
974
+ writeAccessory(null)
975
+ }
976
+
977
+ const onPointerDown = (event) => {
978
+ if (event.button !== 0 || !position) return
979
+ event.preventDefault()
980
+ event.currentTarget.setPointerCapture?.(event.pointerId)
981
+ dragRef.current = {
982
+ id: event.pointerId,
983
+ startX: event.clientX,
984
+ startY: event.clientY,
985
+ originX: position.x,
986
+ originY: position.y,
987
+ moved: false,
988
+ }
989
+ }
990
+
991
+ const onPointerMove = (event) => {
992
+ const drag = dragRef.current
993
+ if (!drag || drag.id !== event.pointerId) return
994
+ const dx = event.clientX - drag.startX
995
+ const dy = event.clientY - drag.startY
996
+ if (!drag.moved && Math.hypot(dx, dy) > 3) drag.moved = true
997
+ if (drag.moved) setPosition(clampPosition(drag.originX + dx, drag.originY + dy, size, size * ratio))
998
+ }
999
+
1000
+ const endDrag = (event) => {
1001
+ const drag = dragRef.current
1002
+ if (!drag || drag.id !== event.pointerId) return
1003
+ dragRef.current = null
1004
+ if (drag.moved) {
1005
+ setPosition((current) => {
1006
+ if (current) writeSetting(KEY_POS, current)
1007
+ return current
1008
+ })
1009
+ } else {
1010
+ onPetClick()
1011
+ }
1012
+ }
1013
+
1014
+ if (!position) return null
1015
+
1016
+ const boxHeight = Math.round(size * ratio)
1017
+
1018
+ if (collapsed) {
1019
+ const chipLeft = Math.min(Math.max(8, position.x + size - 44), Math.max(8, (window.innerWidth || 1024) - 48))
1020
+ const chipTop = Math.min(Math.max(8, position.y + boxHeight - 44), Math.max(8, (window.innerHeight || 768) - 48))
1021
+ return h('button', {
1022
+ type: 'button',
1023
+ className: 'dsh-bat-think-chip',
1024
+ style: { left: `${chipLeft}px`, top: `${chipTop}px` },
1025
+ title: '叫出桌宠',
1026
+ 'aria-label': '叫出桌宠',
1027
+ onClick: () => toggleCollapsed(false),
1028
+ }, h('img', { src: `${ROUTE}/idle.png`, alt: '', draggable: false }))
1029
+ }
1030
+
1031
+ const current = frames[Math.min(frame, frames.length - 1)] || 'idle.png'
1032
+ const directSrc = `${assetUrl(current)}?v=${BUILD}${loadAttempt > 0 ? `&retry=${loadAttempt}` : ''}`
1033
+ const src = blobs[current] || directSrc
1034
+ const showThink = thinking && !thinkPaused && !bubble && !usageOpen
1035
+ const centreX = position.x + size / 2
1036
+ const viewportWidth = window.innerWidth || 1024
1037
+ const bubbleEdge = centreX < 136 ? ' is-left' : centreX > viewportWidth - 136 ? ' is-right' : ''
1038
+
1039
+ // Accessories sit on the same 512 canvas as the artwork: `canvas.crop`
1040
+ // records which part of that canvas the PNG crops, so a sticker lands
1041
+ // exactly where it was drawn.
1042
+ const canvasSpec = manifest.canvas && Array.isArray(manifest.canvas.crop) && manifest.canvas.crop.length === 4
1043
+ ? manifest.canvas
1044
+ : null
1045
+ const crop = canvasSpec ? canvasSpec.crop.map(Number) : [0, 0, 247, 353]
1046
+ const unit = size / (crop[2] || 1)
1047
+ const canvasWidth = canvasSpec ? Number(canvasSpec.width) || 512 : 512
1048
+ const canvasHeight = canvasSpec ? Number(canvasSpec.height) || 512 : 512
1049
+
1050
+ const eyes = variant === 'bare' && manifest.variants && manifest.variants.bare
1051
+ ? manifest.variants.bare.eyes
1052
+ : null
1053
+ const eyeFile = eyes ? (eyes[eyeFrame] || eyes.open || '') : ''
1054
+ const eyesLayer = !missing && eyeFile
1055
+ ? h('img', {
1056
+ className: 'dsh-bat-think-eyes',
1057
+ src: assetUrl(eyeFile),
1058
+ alt: '',
1059
+ draggable: false,
1060
+ style: {
1061
+ left: `${-crop[0] * unit}px`,
1062
+ top: `${-crop[1] * unit}px`,
1063
+ width: `${canvasWidth * unit}px`,
1064
+ height: `${canvasHeight * unit}px`,
1065
+ },
1066
+ })
1067
+ : null
1068
+
1069
+ const hotspotPixels = Array.isArray(manifest.hotspot) && manifest.hotspot.length === 4 ? manifest.hotspot.map(Number) : null
1070
+ const hotspotStyle = hotspotPixels
1071
+ ? {
1072
+ left: `${(hotspotPixels[0] - crop[0]) * unit}px`,
1073
+ top: `${(hotspotPixels[1] - crop[1]) * unit}px`,
1074
+ width: `${hotspotPixels[2] * unit}px`,
1075
+ height: `${hotspotPixels[3] * unit}px`,
1076
+ }
1077
+ : { left: '8%', top: '69%', width: '52%', height: '30%' }
1078
+
1079
+ const accessoryLayer = accessory && accMeta && canvasSpec
1080
+ ? (() => {
1081
+ return h('div', {
1082
+ className: 'dsh-bat-think-accessory',
1083
+ style: {
1084
+ left: `${(accMeta.box.x - crop[0]) * unit}px`,
1085
+ top: `${(accMeta.box.y - crop[1]) * unit}px`,
1086
+ width: `${accMeta.box.w * unit}px`,
1087
+ height: `${accMeta.box.h * unit}px`,
1088
+ backgroundImage: `url("${accessoryUrl(accessory.file)}")`,
1089
+ backgroundSize: `${canvasWidth * unit}px ${canvasHeight * unit}px`,
1090
+ backgroundPosition: `${-accMeta.box.x * unit}px ${-accMeta.box.y * unit}px`,
1091
+ },
1092
+ title: '点图案摘掉',
1093
+ onPointerDown: (event) => event.stopPropagation(),
1094
+ onClick: onAccessoryClick,
1095
+ })
1096
+ })()
1097
+ : null
1098
+
1099
+
1100
+ return h('div', {
1101
+ className: 'dsh-bat-think-root',
1102
+ style: { left: `${position.x}px`, top: `${position.y}px`, width: `${size}px` },
1103
+ role: 'group',
1104
+ 'aria-label': manifest.name || 'Desktop pet',
1105
+ title: manifest.name || 'Desktop pet',
1106
+ onPointerDown,
1107
+ onPointerMove,
1108
+ onPointerUp: endDrag,
1109
+ onPointerCancel: endDrag,
1110
+ onContextMenu: (event) => event.preventDefault(),
1111
+ },
1112
+ showThink
1113
+ ? h('div', { className: `dsh-bat-think-think${bubbleEdge}`, role: 'status', 'aria-label': '思考中' },
1114
+ h('span', { className: 'dsh-bat-think-dot' }),
1115
+ h('span', { className: 'dsh-bat-think-dot' }),
1116
+ h('span', { className: 'dsh-bat-think-dot' }))
1117
+ : null,
1118
+ usageOpen
1119
+ ? h('div', { className: `dsh-bat-think-usage${bubbleEdge}`, role: 'dialog', 'aria-label': 'API 用量' },
1120
+ h('div', { className: 'dsh-bat-think-usage-head' },
1121
+ h('span', null, 'API 用量'),
1122
+ h('button', {
1123
+ type: 'button',
1124
+ className: 'dsh-bat-think-usage-close',
1125
+ title: '关闭',
1126
+ 'aria-label': '关闭用量面板',
1127
+ onPointerDown: stopTool,
1128
+ onClick: () => setUsageOpen(false),
1129
+ }, '×')),
1130
+ modelLabel
1131
+ ? h('div', { className: 'dsh-bat-think-usage-row' }, h('span', null, '模型'), h('b', { title: modelLabel }, modelLabel))
1132
+ : null,
1133
+ hasUsage
1134
+ ? [
1135
+ h('div', { key: 'out', className: 'dsh-bat-think-usage-row' }, h('span', null, '输出'), h('b', null, formatCount(usage && usage.outputTokens))),
1136
+ h('div', { key: 'in', className: 'dsh-bat-think-usage-row' }, h('span', null, '输入'), h('b', null, formatCount(usage && usage.uncachedInputTokens))),
1137
+ h('div', { key: 'cache', className: 'dsh-bat-think-usage-row' }, h('span', null, '缓存读取'), h('b', null, formatCount(usage && usage.cacheReadTokens))),
1138
+ h('div', { key: 'ctx', className: 'dsh-bat-think-usage-sub' }, h('span', null, '上下文'), h('span', null, contextPercent === null ? '—' : `${contextPercent}%`)),
1139
+ ...(contextPercent === null ? [] : [h('div', { key: 'bar', className: 'dsh-bat-think-usage-bar' }, h('i', { style: { width: `${contextPercent}%` } }))]),
1140
+ h('div', { key: 'num', className: 'dsh-bat-think-usage-sub' }, h('span', null, formatCount(usedTokens)), h('span', null, formatCount(windowTokens))),
1141
+ totals.sessions > 0
1142
+ ? h('div', { key: 'all', className: 'dsh-bat-think-usage-sub' },
1143
+ h('span', null, `已加载 ${totals.sessions} 个会话`),
1144
+ h('span', null, formatCount(totals.uncachedInputTokens + totals.cacheReadTokens + totals.outputTokens)))
1145
+ : null,
1146
+ ]
1147
+ : h('div', { className: 'dsh-bat-think-usage-sub' }, '这个会话还没有用量数据'))
1148
+ : null,
1149
+ bubble && !usageOpen ? h('div', { className: `dsh-bat-think-bubble${bubbleEdge}`, role: 'status' }, bubble) : null,
1150
+ missing
1151
+ ? h('div', { className: `dsh-bat-think-bubble${bubbleEdge}` },
1152
+ h('div', null, `立绘没找到:${failedFile || current}(${manifest.variants && manifest.variants[variant] ? variant : '?'})`),
1153
+ failedInfo ? h('div', { style: { fontSize: '10px', opacity: 0.75, wordBreak: 'break-all', marginTop: '4px' } }, failedInfo) : null)
1154
+ : null,
1155
+ h('div', { className: `dsh-bat-think-body${bump ? ' is-bump' : ''}` },
1156
+ missing
1157
+ ? null
1158
+ : h('img', {
1159
+ className: 'dsh-bat-think-img',
1160
+ src,
1161
+ alt: '',
1162
+ draggable: false,
1163
+ style: { width: `${size}px` },
1164
+ onDragStart: (event) => event.preventDefault(),
1165
+ onLoad: (event) => {
1166
+ const element = event.currentTarget
1167
+ if (element.naturalWidth > 0 && element.naturalHeight > 0) {
1168
+ const next = element.naturalHeight / element.naturalWidth
1169
+ setRatio((value) => (Math.abs(value - next) > 0.01 ? next : value))
1170
+ }
1171
+ },
1172
+ onError: () => {
1173
+ // A file swapped on disk can 404 for a moment; try twice, then
1174
+ // try the same bytes through fetch() as a blob URL, and only
1175
+ // then tell the user the artwork is missing.
1176
+ if (loadAttempt < 2) {
1177
+ window.setTimeout(() => {
1178
+ if (alive.current) setLoadAttempt((attempt) => attempt + 1)
1179
+ }, 800)
1180
+ return
1181
+ }
1182
+ if (!blobs[current]) {
1183
+ fetch(assetUrl(current), { cache: 'no-store' })
1184
+ .then((response) => {
1185
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
1186
+ return response.blob()
1187
+ })
1188
+ .then((blob) => {
1189
+ const url = URL.createObjectURL(blob)
1190
+ setBlobs((map) => ({ ...map, [current]: url }))
1191
+ })
1192
+ .catch((error) => {
1193
+ setFailedFile(current)
1194
+ setFailedInfo(`${window.location.origin}${directSrc} · ${error && error.message ? error.message : 'fetch failed'}`)
1195
+ setMissing(true)
1196
+ })
1197
+ return
1198
+ }
1199
+ setFailedFile(current)
1200
+ setFailedInfo(`${window.location.origin}${directSrc}`)
1201
+ setMissing(true)
1202
+ },
1203
+ }),
1204
+ eyesLayer,
1205
+ missing
1206
+ ? null
1207
+ : h('button', {
1208
+ type: 'button',
1209
+ className: 'dsh-bat-think-laptop',
1210
+ style: hotspotStyle,
1211
+ title: 'API 用量',
1212
+ 'aria-label': '查看 API 用量',
1213
+ onPointerDown: stopTool,
1214
+ onClick: (event) => {
1215
+ event.stopPropagation()
1216
+ setUsageOpen((open) => !open)
1217
+ },
1218
+ }),
1219
+ accessoryLayer),
1220
+ usageOpen ? null : h('div', { className: 'dsh-bat-think-tools' },
1221
+ h('button', { type: 'button', className: 'dsh-bat-think-tool', title: '缩小', 'aria-label': '缩小宠物', onPointerDown: stopTool, onClick: () => adjustSize(-16) }, '−'),
1222
+ h('button', { type: 'button', className: 'dsh-bat-think-tool', title: '放大', 'aria-label': '放大宠物', onPointerDown: stopTool, onClick: () => adjustSize(16) }, '+'),
1223
+ h('button', { type: 'button', className: 'dsh-bat-think-tool', title: '随机配件', 'aria-label': '随机配件', onPointerDown: stopTool, onClick: rollAccessory },
1224
+ h('svg', { width: 12, height: 12, viewBox: '0 0 16 16', 'aria-hidden': true },
1225
+ h('rect', { x: 1.6, y: 1.6, width: 12.8, height: 12.8, rx: 3.2, fill: 'none', stroke: 'currentColor', strokeWidth: 1.4 }),
1226
+ ...[[4.9, 4.9], [11.1, 4.9], [8, 8], [4.9, 11.1], [11.1, 11.1]].map(([cx, cy], index) => h('circle', { key: index, cx, cy, r: 1.15, fill: 'currentColor' })))),
1227
+ h('button', { type: 'button', className: 'dsh-bat-think-tool', title: '收起', 'aria-label': '收起桌宠', onPointerDown: stopTool, onClick: () => toggleCollapsed(true) }, '×'),
1228
+ ))
1229
+ }
1230
+
1231
+ return {
1232
+ inject: ['slots'],
1233
+ apply(ctx) {
1234
+ const softGet = typeof ctx.get === 'function' ? ctx.get.bind(ctx) : undefined
1235
+ try {
1236
+ const soft = softGet ? softGet('sessions') : ctx.sessions
1237
+ if (soft && soft.list) attachSessionList(soft.list)
1238
+ } catch {
1239
+ // The service is not up yet; ctx.inject below attaches it later.
1240
+ }
1241
+ try {
1242
+ const models = softGet ? softGet('modelDirectories') : ctx.modelDirectories
1243
+ if (models) setModelDirectories(models)
1244
+ } catch {
1245
+ // Optional: the usage card simply omits the model row without it.
1246
+ }
1247
+ try {
1248
+ ctx.inject(['modelDirectories'], (scoped) => {
1249
+ scoped.effect(() => {
1250
+ setModelDirectories(scoped.modelDirectories || null)
1251
+ return () => setModelDirectories(null)
1252
+ }, 'dsh-bat-think: model directories')
1253
+ })
1254
+ } catch {
1255
+ // No model-selection service in this deployment.
1256
+ }
1257
+ try {
1258
+ ctx.inject(['sessions'], (scoped) => {
1259
+ scoped.effect(() => {
1260
+ const sessions = scoped.sessions
1261
+ if (sessions && sessions.list) attachSessionList(sessions.list)
1262
+ return () => detachSessionList()
1263
+ }, 'dsh-bat-think: session bridge')
1264
+ })
1265
+ } catch {
1266
+ // A deployment without the session service keeps the pet, minus the
1267
+ // thought bubble.
1268
+ }
1269
+ ctx.effect(() => installStyle(), 'dsh-bat-think: styles')
1270
+ ctx.slots.inject('shell.overlay', () => ctx.slots.register({
1271
+ name: 'shell.overlay',
1272
+ id: 'dsh-bat-think',
1273
+ order: 20,
1274
+ }, Pet))
1275
+ },
1276
+ }
1277
+ },
1278
+ })