dsh-bat-think 0.0.0-stage → 1.0.0

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