better-dsh-pet 0.2.6 → 0.3.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.
@@ -1,1349 +1,2792 @@
1
- /**
2
- * better-dsh-pet desktop helper renderer —— 透明窗口里的宠物本体。
3
- *
4
- * 使用纯 DOM + 双 video 缓冲播放 better-dsh-pet 的 WebM 动画;接收主进程转发的
5
- * Companion 消息,根据 DSH 状态切换动画并显示气泡。
6
- */
7
-
8
- // ---------- 配置 ----------
9
- const params = new URLSearchParams(location.search)
10
- const CONFIG = {
11
- enabled: params.get('enabled') !== '0',
12
- scale: Number(params.get('scale') || '1'),
13
- bubbleScale: Number(params.get('bubbleScale') || '1'),
14
- activityLevel: params.get('activityLevel') || 'normal',
15
- reducedMotion: params.get('reducedMotion') === '1',
16
- bubbleMode: params.get('bubbleMode') || 'always',
17
- bubbleStates: (params.get('bubbleStates') || 'SUCCESS,ERROR,WAITING').split(',').filter(Boolean),
18
- webuiUrl: params.get('webuiUrl') || 'http://127.0.0.1:3080/',
19
- workMinutes: Number(params.get('workMinutes') || '25'),
20
- breakMinutes: Number(params.get('breakMinutes') || '5'),
21
- roastEnabled: params.get('roastEnabled') === '1',
22
- walkEnabled: params.get('walkEnabled') !== '0',
23
- enabledActions: [],
24
- actionOrder: [],
25
- petSize: Number(params.get('petSize') || '460'),
26
- moveChance: Number(params.get('moveChance') || '20'),
27
- actionDelayMs: Number(params.get('actionDelayMs') || '0'),
28
- }
29
-
30
- // ---------- 资源根 ----------
31
- const ASSET_BASE = new URL('../../assets/thumb/', location.href).href
32
- const ALARM_URL = new URL('../../assets/alarm.mp3', location.href).href
33
-
34
- // ---------- 动画目录 ----------
35
- const CANVAS_H = 360
36
- const FEET_Y = 330
37
- const HIT_BOX = { x0: 200, y0: 50, x1: 440, y1: 335 }
38
-
39
- const IDLE = '待机呼吸休闲'
40
- const TURN = '东张西望'
41
- const DRAG = '被鼠标拖拽悬空反馈'
42
- const ACTS = [
43
- '被落叶淹没', '被吓一跳', '变鸽子', '插茱萸赏菊', '拆礼物',
44
- '超大伸懒腰', '晨间刷牙', '吃Token', '吃白饭', '吃冰淇淋融化',
45
- '吃大闸蟹', '吃饺子', '吃腊八粥', '吃年糕', '吃青团',
46
- '吃汤圆', '吃糖葫芦', '吃晚餐', '吃午餐', '吃西瓜',
47
- '吃早餐', '吃长寿面', '吃重阳糕', '吃粽子', '抽陀螺',
48
- '穿针乞巧', '吹笛子', '吹气球', '打瞌睡被惊醒', '大口吃零食',
49
- '荡秋千', '动物环绕', '堆雪人', '放风筝', '放河灯',
50
- '放孔明灯', '放烟花', '哈欠连天', '蝴蝶蜜蜂环绕头顶开花', '鲸鱼吐泡泡特效',
51
- '可爱宅舞', '蓝鲸现世', '撸猫', '萌化小幽灵', '女仆屈膝礼仪',
52
- '凭空生花', '扑克魔术', '骑木马', '轻快记录', '轻快摇摆舞',
53
- '三球抛接', '深度思考碎碎念', '是啊,吃什么', '收红包', '涮火锅',
54
- '讨糖南瓜灯', '踢毽子', '偷吃零食被抓住', '玩水枪', '玩游戏气急败坏',
55
- '舞狮头', '下五子棋', '小幅度原地360度旋转展示', '小提琴演奏', '写代码',
56
- '写福字', '摇扇纳凉', '用鲸鱼尾巴拍打地面', '优雅女仆舞', '悠闲哼歌',
57
- '原地蹲下玩玩具汽车', '原地敲击桌面互动', '原地跳跃抓碎头顶物品', '原地小憩沉眠',
58
- '原地重力下蹲压缩', '原地专心玩魔方', '照镜子', '整体换装试色',
59
- '中秋赏月吃月饼', '装点圣诞树',
60
- ]
61
- const ACTION_COPY = {
62
- '东张西望': '大肥鱼东张西望,看看有没有鱼干~',
63
- '悠闲哼歌': '大肥鱼悠闲地哼着小曲~',
64
- '超大伸懒腰': '大肥鱼伸了个大大的懒腰~',
65
- '原地专心玩魔方': '大肥鱼在专心拧魔方呢~',
66
- '原地敲击桌面互动': '大肥鱼在敲桌面求关注~',
67
- '原地重力下蹲压缩': '大肥鱼像弹簧一样蹲下去啦~',
68
- '哈欠连天': '大肥鱼打了个大大的哈欠~',
69
- '原地小憩沉眠': '大肥鱼偷偷打了个盹儿~',
70
- '原地蹲下玩玩具汽车': '大肥鱼蹲在地上玩小汽车~',
71
- '鲸鱼吐泡泡特效': '大肥鱼吐出一串可爱的泡泡~',
72
- '女仆屈膝礼仪': '大肥鱼向你行了个女仆礼~',
73
- '被吓一跳': '大肥鱼被吓得炸毛啦!',
74
- '原地跳跃抓碎头顶物品': '大肥鱼跳起来抓碎了头顶的东西~',
75
- '小幅度原地360度旋转展示': '大肥鱼原地转圈圈展示自己~',
76
- '偷吃零食被抓住': '大肥鱼偷吃零食被抓住啦!',
77
- '玩游戏气急败坏': '大肥鱼玩游戏玩到气急败坏~',
78
- '用鲸鱼尾巴拍打地面': '大肥鱼用尾巴拍地面抗议~',
79
- '打瞌睡被惊醒': '大肥鱼打瞌睡被吓醒了!',
80
- '玩水枪': '大肥鱼拿起水枪滋水玩~',
81
- '小提琴演奏': '大肥鱼拉起了小提琴~',
82
- '蓝鲸现世': '蓝鲸大肥鱼现身啦!',
83
- '吃白饭': '大肥鱼在专心吃白饭~',
84
- '照镜子': '大肥鱼照镜子臭美中~',
85
- '优雅女仆舞': '大肥鱼跳起了优雅的女仆舞~',
86
- '轻快摇摆舞': '大肥鱼轻快地摇摆跳舞~',
87
- '可爱宅舞': '大肥鱼跳起了可爱宅舞~',
88
- '整体换装试色': '大肥鱼在试新衣服的颜色~',
89
- '大口吃零食': '大肥鱼大口大口吃零食~',
90
- '吹气球': '大肥鱼在努力吹气球~',
91
- '动物环绕': '好多小动物围着大肥鱼转~',
92
- '深度思考碎碎念': '大肥鱼陷入深度思考,碎碎念中~',
93
- '轻快记录': '大肥鱼在轻快地记笔记~',
94
- '写代码': '大肥鱼在认真写代码~',
95
- '吃Token': '大肥鱼把 Token 当零食吃掉啦~',
96
- '吃早餐': '大肥鱼在吃早餐~',
97
- '吃午餐': '大肥鱼在吃午餐~',
98
- '吃晚餐': '大肥鱼在吃晚餐~',
99
- '放风筝': '大肥鱼在放风筝~',
100
- '摇扇纳凉': '大肥鱼摇着扇子纳凉~',
101
- '吃冰淇淋融化': '大肥鱼吃冰淇淋,可是化得好快~',
102
- '被落叶淹没': '大肥鱼被落叶埋住啦~',
103
- '中秋赏月吃月饼': '大肥鱼中秋赏月吃月饼~',
104
- '堆雪人': '大肥鱼在堆雪人~',
105
- '螃蟹走路': '大肥鱼横着走路,超嚣张~',
106
- '原地漂浮踏步': '大肥鱼原地踏步漂浮中~',
107
- '原地左转奔跑': '大肥鱼向左奔跑!',
108
- }
109
- const CLICKS = ['点击回应-开心跃动', '点击回应-害羞惊讶', '点击回应-傲娇生气', '点击回应-挠痒咯咯笑', '点击回应-元气挥手']
110
- const CLICK_COPY = {
111
- '点击回应-开心跃动': '大肥鱼被摸得好开心~',
112
- '点击回应-害羞惊讶': '大肥鱼害羞地躲了一下~',
113
- '点击回应-傲娇生气': '大肥鱼傲娇地哼了一声!',
114
- '点击回应-挠痒咯咯笑': '大肥鱼被挠痒痒,咯咯笑~',
115
- '点击回应-元气挥手': '大肥鱼元气满满地挥手~',
116
- }
117
- const EAT_ANIMS = ['吃白饭', '吃早餐', '吃午餐', '吃晚餐', '大口吃零食', '吃Token', '吃冰淇淋融化', '偷吃零食被抓住']
118
- const MOVES = ['螃蟹走路', '原地漂浮踏步', '原地左转奔跑']
119
- // 每个走动动画的“开头不动/结尾不动”时长(秒),按动作实际节奏微调。
120
- const MOVE_TIMING = {
121
- '原地漂浮踏步': { lead: 0.83, tail: 0.83 },
122
- '螃蟹走路': { lead: 1, tail: 2 },
123
- '原地左转奔跑': { lead: 1.67, tail: 5.58 },
124
- }
125
- const STATE_ANIMS = {
126
- IDLE: [IDLE],
127
- THINKING: ['深度思考碎碎念', '原地专心玩魔方', '东张西望'],
128
- WORKING: ['写代码', '轻快记录', '原地敲击桌面互动', '吃Token'],
129
- WAITING: ['东张西望', '悠闲哼歌', '原地敲击桌面互动'],
130
- SUCCESS: ['点击回应-开心跃动', '优雅女仆舞', '轻快摇摆舞', '可爱宅舞', '女仆屈膝礼仪'],
131
- ERROR: ['被吓一跳', '玩游戏气急败坏', '偷吃零食被抓住'],
132
- }
133
-
134
- // ---------- DOM ----------
135
- const rootEl = document.getElementById('pet-root')
136
- const stageEl = document.getElementById('pet-stage')
137
- const videoA = document.querySelectorAll('video')[0]
138
- const videoB = document.querySelectorAll('video')[1]
139
- const hitEl = document.getElementById('pet-hit')
140
- const bubbleEl = document.getElementById('bubble')
141
- const bubbleTitle = document.getElementById('bubble-title')
142
- const bubbleDetail = document.getElementById('bubble-detail')
143
- const menuEl = document.getElementById('menu')
144
-
145
- // ---------- 基础尺寸 ----------
146
- let size = (CONFIG.petSize || 460) * CONFIG.scale
147
- let halfW = size / 2
148
- let halfH = size * 9 / 16 / 2
149
- let bottomPad = (size * 9 / 16 * (CANVAS_H - FEET_Y)) / CANVAS_H
150
- function applySize() {
151
- size = (CONFIG.petSize || 460) * CONFIG.scale
152
- halfW = size / 2
153
- halfH = size * 9 / 16 / 2
154
- bottomPad = (size * 9 / 16 * (CANVAS_H - FEET_Y)) / CANVAS_H
155
- stageEl.style.width = size + 'px'
156
- stageEl.style.height = (size * 9 / 16) + 'px'
157
- stageEl.style.transform = `translateY(${bottomPad}px)`
158
- // 尺寸变化后把位置夹回屏幕内。
159
- petPos.x = Math.min(Math.max(petPos.x, -(HIT_BOX.x0 / 640 * size)), window.innerWidth - (HIT_BOX.x1 / 640 * size))
160
- petPos.y = Math.min(Math.max(petPos.y, 0), window.innerHeight - size * 9 / 16)
161
- applyPetPosition()
162
- }
163
- hitEl.style.left = (HIT_BOX.x0 / 640 * 100) + '%'
164
- hitEl.style.top = (HIT_BOX.y0 / 360 * 100) + '%'
165
- hitEl.style.width = ((HIT_BOX.x1 - HIT_BOX.x0) / 640 * 100) + '%'
166
- hitEl.style.height = ((HIT_BOX.y1 - HIT_BOX.y0) / 360 * 100) + '%'
167
- if (CONFIG.reducedMotion) {
168
- document.documentElement.style.setProperty('--pet-transition', 'none')
169
- }
170
-
171
- // 全屏透明画布内,宠物初始放在右下角;拖拽时只移动这个 DOM,不移动窗口。
172
- let petPos = {
173
- x: window.innerWidth - size - 24,
174
- y: window.innerHeight - size * 9 / 16 - 24,
175
- }
176
- function applyPetPosition() {
177
- rootEl.style.left = petPos.x + 'px'
178
- rootEl.style.top = petPos.y + 'px'
179
- rootEl.style.right = 'auto'
180
- rootEl.style.bottom = 'auto'
181
- rootEl.style.transform = 'none'
182
- }
183
- applyPetPosition()
184
- applySize()
185
-
186
- // ---------- 状态 ----------
187
- let front = 0 // 0 = A, 1 = B
188
- let pending = null
189
- let gen = 0
190
- let anim = IDLE
191
- let animOnce = true
192
- let animLoop = false
193
- let currentMode = 'idle' // idle | state | click | drag | move | pulse
194
- let currentState = 'IDLE'
195
- let resumeState = 'IDLE'
196
- let resumeMessage = ''
197
- let resumeDetail = ''
198
- let overlay = null
199
- let overlayTimer = null
200
- let lastPulseKey = null
201
- let status = { state: 'IDLE', message: '', detail: '', project: '', task: '', progress: null }
202
- let tasks = []
203
- let dragging = false
204
- let dragState = { active: false, dragging: false, sx: 0, sy: 0, offX: 0, offY: 0 }
205
- let justDragged = false
206
- let facing = 'left'
207
- let lastMouse = { x: -1, y: -1 }
208
- let tokenUsage = { inputTokens: 0, outputTokens: 0, totalTokens: 0 }
209
- let balance = null
210
- let roast = null
211
- let lastRoast = null
212
- let manualBubble = null
213
- let manualBubbleTimer = null
214
- let pomodoro = null
215
- let pomodoroTimer = null
216
- let menuPage = 'main'
217
- let lastMenuPos = { x: 0, y: 0 }
218
- let moveRef = null
219
- let moveToken = 0
220
- let movePlan = null
221
- let actionOrderIndex = 0
222
- let idleDelayTimer = null
223
-
224
- // ---------- 工具 ----------
225
- const randomBetween = (min, max) => Math.floor(min + Math.random() * (max - min))
226
- const pick = (pool, exclude) => {
227
- const entries = exclude ? pool.filter((n) => n !== exclude) : pool
228
- return entries[Math.floor(Math.random() * entries.length)]
229
- }
230
-
231
- function assetUrl(name) {
232
- return new URL(encodeURIComponent(name) + '.webm', ASSET_BASE).href
233
- }
234
-
235
- // ---------- 视频切换 ----------
236
- function currentVideo() {
237
- return front === 0 ? videoA : videoB
238
- }
239
-
240
- function otherVideo() {
241
- return front === 0 ? videoB : videoA
242
- }
243
-
244
- function switchTo(next, { once = true, loop = false } = {}) {
245
- if (pending && pending.anim === next && pending.once === once && pending.loop === loop) return
246
- const currentGen = ++gen
247
- pending = { anim: next, once, loop, gen: currentGen }
248
- const target = otherVideo()
249
- const el = target
250
- const old = currentVideo()
251
- // 旧视频可能还没播完就被切走:清掉它的 ended 回调,避免稍后触发
252
- // handleEnded 打断当前正在播放的新动画。
253
- if (old && old !== el) old.onended = null
254
- el.src = assetUrl(next)
255
- el.loop = loop
256
- el.muted = true
257
- el.autoplay = true
258
- el.playsInline = true
259
- el.onended = loop ? null : () => handleEnded()
260
- el.load()
261
- const onReady = () => {
262
- el.removeEventListener('loadeddata', onReady)
263
- if (pending?.gen !== currentGen) return
264
- el.classList.add('is-front')
265
- if (old !== el) {
266
- old.classList.remove('is-front')
267
- old.onended = null
268
- }
269
- front = front === 0 ? 1 : 0
270
- pending = null
271
- el.style.transform = facing === 'right' ? 'scaleX(-1)' : ''
272
- el.play().catch(() => {})
273
- // 走动动画加载完成后,用真实视频时长驱动移动。
274
- if (currentMode === 'move' && movePlan) startMoveDrive()
275
- }
276
- el.addEventListener('loadeddata', onReady)
277
- if (el.readyState >= 2) onReady()
278
- }
279
-
280
- // ---------- 播放控制 ----------
281
- function playIdle() {
282
- clearIdleDelay()
283
- stopMove()
284
- currentMode = 'idle'
285
- // 自定义动作池:设置了 enabledActions 时只从这些动作里选。
286
- const actionPool = CONFIG.enabledActions.length > 0
287
- ? ACTS.filter((name) => CONFIG.enabledActions.includes(name))
288
- : ACTS
289
- const usableActions = actionPool.length > 0 ? actionPool : ACTS
290
- // 自定义播放顺序:非空时按顺序循环播放。
291
- const order = CONFIG.actionOrder.length > 0
292
- ? CONFIG.actionOrder.filter((name) => ACTS.includes(name) || MOVES.includes(name) || name === TURN)
293
- : []
294
- let next = IDLE
295
- let isMove = false
296
- if (order.length > 0) {
297
- next = order[actionOrderIndex % order.length]
298
- actionOrderIndex++
299
- if (MOVES.includes(next) && CONFIG.walkEnabled && tryMove(next)) isMove = true
300
- } else {
301
- // 移动频繁度 = 每次待机决策时尝试走动的概率(可关闭)。
302
- const moveCandidate = pick(MOVES, anim)
303
- if (CONFIG.walkEnabled && Math.random() * 100 < CONFIG.moveChance && tryMove(moveCandidate)) {
304
- next = moveCandidate
305
- isMove = true
306
- } else {
307
- const roll = Math.random()
308
- if (roll < 0.3) {
309
- next = IDLE
310
- } else if (roll < 0.4) {
311
- next = TURN
312
- } else {
313
- next = pick(usableActions, anim)
314
- }
315
- }
316
- }
317
- anim = next
318
- animOnce = true
319
- animLoop = false
320
- switchTo(next, { once: true })
321
- if (isMove) {
322
- currentMode = 'move'
323
- // 移动驱动在视频加载完成后启动(switchTo onReady 里调用),
324
- // 这样可以使用视频真实时长,避免动画还没播完就提前停下。
325
- }
326
- // 随机动作/走动播放时,给出与动作匹配的可爱气泡描述。
327
- if (next !== IDLE) {
328
- const copy = ACTION_COPY[next] || `大肥鱼正在${next}~`
329
- showManualBubble(copy, '大肥鱼的小剧场~', 4200)
330
- }
331
- }
332
-
333
- function playState(state, { pulse = false } = {}) {
334
- clearIdleDelay()
335
- stopMove()
336
- currentMode = pulse ? 'pulse' : 'state'
337
- const pool = STATE_ANIMS[state] || STATE_ANIMS.IDLE
338
- const next = state === 'IDLE' ? IDLE : pick(pool, anim)
339
- anim = next
340
- // 非空闲状态动画循环播放,避免播完一帧后停在原地;空闲状态仍走随机动画链。
341
- animLoop = !pulse && state !== 'IDLE'
342
- animOnce = !animLoop
343
- switchTo(next, { once: !animLoop, loop: animLoop })
344
- }
345
-
346
- function playClick() {
347
- clearIdleDelay()
348
- stopMove()
349
- currentMode = 'click'
350
- const next = pick(CLICKS, anim)
351
- anim = next
352
- animOnce = true
353
- animLoop = false
354
- switchTo(next, { once: true })
355
- showManualBubble(CLICK_COPY[next] || '大肥鱼被戳了一下~', '大肥鱼的小剧场~', 2500)
356
- }
357
-
358
- function playDrag() {
359
- clearIdleDelay()
360
- stopMove()
361
- currentMode = 'drag'
362
- anim = DRAG
363
- animOnce = true
364
- animLoop = false
365
- switchTo(DRAG, { once: true })
366
- }
367
-
368
- // ---------- 走动效果 ----------
369
- function tryMove(moveName) {
370
- if (moveRef !== null || movePlan) return true
371
- const W = window.innerWidth
372
- const H = window.innerHeight
373
- const minX = -(HIT_BOX.x0 / 640 * size)
374
- const maxX = W - (HIT_BOX.x1 / 640 * size)
375
- const minY = 0
376
- const maxY = H - size * 9 / 16
377
-
378
- // “原地漂浮踏步”面朝观众,适合稍微向屏幕下方(朝用户)移动一点。
379
- if (moveName === '原地漂浮踏步') {
380
- const distance = randomBetween(40, 90)
381
- const targetY = petPos.y + distance
382
- if (targetY > maxY) return false
383
- movePlan = { startX: petPos.x, targetX: petPos.x, startY: petPos.y, targetY }
384
- return true
385
- }
386
-
387
- const dir = Math.random() < 0.5 ? -1 : 1
388
- const distance = randomBetween(200, 450)
389
- const targetX = petPos.x + dir * distance
390
- if (targetX < minX || targetX > maxX) return false
391
- // 让角色面朝移动方向,避免“向左跑却镜像成向右”的错乱。
392
- facing = dir > 0 ? 'right' : 'left'
393
- movePlan = { startX: petPos.x, targetX, startY: petPos.y, targetY: petPos.y }
394
- return true
395
- }
396
-
397
- function startMoveDrive() {
398
- if (!movePlan) return
399
- const plan = movePlan
400
- const el = currentVideo()
401
- const duration = Number.isFinite(el?.duration) && el.duration > 0 ? el.duration : 9
402
- // 每个动作的“开头不动/结尾不动”时长不同,按动作单独配置。
403
- const timing = MOVE_TIMING[anim] || { lead: 1.5, tail: 2 }
404
- const lead = timing.lead
405
- const tail = timing.tail
406
- const travelWindow = Math.max(0.1, duration - lead - tail)
407
- const token = ++moveToken
408
- const step = () => {
409
- if (moveToken !== token || !movePlan) return
410
- const t = el.currentTime || 0
411
- let x = plan.startX
412
- let y = plan.startY ?? petPos.y
413
- if (t > lead && t < duration - tail) {
414
- const progress = Math.min(1, Math.max(0, (t - lead) / travelWindow))
415
- x = plan.startX + (plan.targetX - plan.startX) * progress
416
- y = (plan.startY ?? petPos.y) + ((plan.targetY ?? petPos.y) - (plan.startY ?? petPos.y)) * progress
417
- } else if (t >= duration - tail) {
418
- x = plan.targetX
419
- y = plan.targetY ?? petPos.y
420
- }
421
- petPos.x = x
422
- petPos.y = y
423
- applyPetPosition()
424
- if (t < duration - tail) {
425
- moveRef = requestAnimationFrame(step)
426
- } else {
427
- moveRef = null
428
- movePlan = null
429
- }
430
- }
431
- moveRef = requestAnimationFrame(step)
432
- }
433
-
434
- function stopMove() {
435
- movePlan = null
436
- moveToken++
437
- if (moveRef !== null) {
438
- cancelAnimationFrame(moveRef)
439
- moveRef = null
440
- }
441
- }
442
-
443
- function clearIdleDelay() {
444
- if (idleDelayTimer) {
445
- clearTimeout(idleDelayTimer)
446
- idleDelayTimer = null
447
- }
448
- }
449
-
450
- function scheduleNextIdle() {
451
- clearIdleDelay()
452
- if (CONFIG.actionDelayMs > 0) {
453
- // 等待“动作切换间隔”时不要定格在上一动作的最后一帧:
454
- // 先播放循环待机呼吸,等间隔结束再进入下一个随机/自定义动作。
455
- currentMode = 'idle'
456
- anim = IDLE
457
- animOnce = false
458
- animLoop = true
459
- switchTo(IDLE, { loop: true })
460
- idleDelayTimer = setTimeout(() => {
461
- idleDelayTimer = null
462
- playIdle()
463
- }, CONFIG.actionDelayMs)
464
- } else {
465
- playIdle()
466
- }
467
- }
468
-
469
- function handleEnded() {
470
- if (dragging || dragState.active) return
471
- if (overlay && overlay.state) {
472
- // 脉冲动画播完但 TTL 未结束:气泡保留,动画先回到 resume 状态。
473
- if (!overlay.animationDone) {
474
- overlay.animationDone = true
475
- applyResume()
476
- }
477
- return
478
- }
479
- if (currentMode === 'click') {
480
- applyResume()
481
- return
482
- }
483
- if (currentMode === 'move') {
484
- stopMove()
485
- scheduleNextIdle()
486
- return
487
- }
488
- if (currentMode === 'state') {
489
- const state = overlay ? overlay.state : currentState
490
- if (state && state !== 'IDLE') {
491
- playState(state)
492
- return
493
- }
494
- scheduleNextIdle()
495
- return
496
- }
497
- if (anim === TURN) {
498
- facing = facing === 'left' ? 'right' : 'left'
499
- }
500
- scheduleNextIdle()
501
- }
502
-
503
- function applyResume() {
504
- const state = resumeState || currentState || 'IDLE'
505
- currentState = state
506
- // 强制清掉可能卡住的切换状态,确保拖拽结束后一定切回正常动画。
507
- pending = null
508
- if (state === 'IDLE') {
509
- // 任务刚结束/拖拽结束后先回到纯待机,避免随机链立刻播放“思考类”动画。
510
- status = {
511
- ...status,
512
- state: 'IDLE',
513
- message: resumeMessage || '大肥鱼在这儿等新任务哦~',
514
- detail: resumeDetail || '大肥鱼 · 等待下一次任务',
515
- }
516
- currentMode = 'idle'
517
- anim = IDLE
518
- animOnce = true
519
- animLoop = false
520
- switchTo(IDLE, { once: true })
521
- } else {
522
- status = {
523
- ...status,
524
- state,
525
- message: resumeMessage || status.message,
526
- detail: resumeDetail || status.detail,
527
- }
528
- playState(state)
529
- }
530
- updateBubble()
531
- }
532
-
533
- function clearOverlay() {
534
- if (overlayTimer) clearTimeout(overlayTimer)
535
- overlayTimer = null
536
- overlay = null
537
- lastPulseKey = null
538
- }
539
-
540
- // ---------- 消息处理 ----------
541
- function applyStateMessage(message) {
542
- const state = message.state || 'IDLE'
543
- status = {
544
- state,
545
- message: message.message || status.message,
546
- detail: message.detail || status.detail,
547
- project: message.project || status.project,
548
- task: message.task || status.task,
549
- progress: message.progress || status.progress,
550
- }
551
- currentState = state
552
- resumeState = state
553
- resumeMessage = message.message || ''
554
- resumeDetail = message.detail || ''
555
- clearOverlay()
556
- if (state === 'IDLE') playIdle()
557
- else playState(state)
558
- updateBubble()
559
- }
560
-
561
- function applyPulseMessage(message) {
562
- const state = message.state || 'SUCCESS'
563
- resumeState = message.resumeState || currentState || 'IDLE'
564
- resumeMessage = message.resumeMessage || ''
565
- resumeDetail = message.resumeDetail || ''
566
- overlay = {
567
- state,
568
- message: message.message || '',
569
- detail: message.detail || '',
570
- ttlMs: Number(message.ttlMs || 1800),
571
- animationDone: false,
572
- }
573
- lastPulseKey = `${state}:${message.expiresAt || message.ttlMs || 1800}`
574
- currentState = state
575
- if (state === 'SUCCESS') {
576
- window.petBridge.beep()
577
- shakePet()
578
- }
579
- playState(state, { pulse: true })
580
- if (overlayTimer) clearTimeout(overlayTimer)
581
- overlayTimer = setTimeout(() => {
582
- clearOverlay()
583
- applyResume()
584
- }, overlay.ttlMs)
585
- updateBubble()
586
- }
587
-
588
- function applyTaskMessage(message) {
589
- status.task = message.task || status.task
590
- status.progress = message.progress || status.progress
591
- status.project = message.project || status.project
592
- status.message = message.message || status.message
593
- status.detail = message.detail || status.detail
594
- updateBubble()
595
- }
596
-
597
- function applyTasksMessage(message) {
598
- tasks = Array.isArray(message.tasks) ? message.tasks : []
599
- updateBubble()
600
- }
601
-
602
- // ---------- 喂食/互动反馈 ----------
603
- function showManualBubble(message, detail, ttl = 2200) {
604
- if (manualBubbleTimer) clearTimeout(manualBubbleTimer)
605
- manualBubble = { message, detail, expiresAt: Date.now() + ttl }
606
- manualBubbleTimer = setTimeout(() => {
607
- manualBubble = null
608
- manualBubbleTimer = null
609
- updateBubble()
610
- }, ttl)
611
- updateBubble()
612
- }
613
-
614
- function feedPet() {
615
- clearIdleDelay()
616
- const next = pick(EAT_ANIMS, anim)
617
- anim = next
618
- animOnce = true
619
- animLoop = false
620
- currentMode = 'click' // 复用“一次性动画播完回当前状态”的路径
621
- switchTo(next, { once: true })
622
- showManualBubble('谢谢投喂大肥鱼~', '吃饱了更有力气干活!', 2200)
623
- }
624
-
625
- function shakePet() {
626
- const originX = petPos.x
627
- const originY = petPos.y
628
- const offsets = [[6, 0], [-6, 0], [4, 0], [-4, 0], [2, 0], [-2, 0], [0, 0]]
629
- let index = 0
630
- const timer = setInterval(() => {
631
- if (index >= offsets.length) {
632
- clearInterval(timer)
633
- applyPetPosition()
634
- return
635
- }
636
- const [dx, dy] = offsets[index++]
637
- rootEl.style.left = (originX + dx) + 'px'
638
- rootEl.style.top = (originY + dy) + 'px'
639
- }, 30)
640
- }
641
-
642
- // ---------- 番茄钟 ----------
643
- function formatTime(ms) {
644
- const totalSeconds = Math.max(0, Math.ceil(ms / 1000))
645
- const minutes = Math.floor(totalSeconds / 60)
646
- const seconds = totalSeconds % 60
647
- return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`
648
- }
649
-
650
- function playAlarm() {
651
- try {
652
- const audio = new Audio(ALARM_URL)
653
- audio.volume = 0.8
654
- audio.play().catch(() => {})
655
- } catch {
656
- // 音频不可用时静默失败
657
- }
658
- }
659
-
660
- function startPomodoro(mode, minutes) {
661
- stopPomodoro()
662
- const durationMs = Math.max(1, minutes) * 60 * 1000
663
- pomodoro = { mode, endAt: Date.now() + durationMs, durationMs }
664
- pomodoroTimer = setInterval(updatePomodoro, 1000)
665
- updateBubble()
666
- }
667
-
668
- function stopPomodoro() {
669
- if (pomodoroTimer) clearInterval(pomodoroTimer)
670
- pomodoroTimer = null
671
- pomodoro = null
672
- updateBubble()
673
- }
674
-
675
- function updatePomodoro() {
676
- if (!pomodoro) return
677
- const remaining = pomodoro.endAt - Date.now()
678
- if (remaining <= 0) {
679
- completePomodoro()
680
- return
681
- }
682
- updateBubble()
683
- }
684
-
685
- function completePomodoro() {
686
- const mode = pomodoro?.mode || 'work'
687
- stopPomodoro()
688
- playAlarm()
689
- shakePet()
690
- showManualBubble(
691
- mode === 'work' ? '🍅 大肥鱼番茄钟结束啦!' : '☕ 大肥鱼休息结束啦!',
692
- mode === 'work' ? '快休息一下,摸摸鱼~' : '继续加油,大肥鱼陪你!',
693
- 4000,
694
- )
695
- playClick()
696
- }
697
-
698
- // ---------- 气泡 ----------
699
- function visibleState() {
700
- if (overlay) return overlay.state
701
- if (tasks.length >= 2) return status.state
702
- return status.state || 'IDLE'
703
- }
704
-
705
- function updateBubble() {
706
- const state = visibleState()
707
- const manualActive = manualBubble && manualBubble.expiresAt > Date.now()
708
- const pomodoroActive = pomodoro && pomodoro.endAt > Date.now()
709
- const shouldShow = pomodoroActive || manualActive
710
- ? CONFIG.bubbleMode !== 'hidden'
711
- : CONFIG.bubbleMode === 'always'
712
- || (CONFIG.bubbleMode === 'custom' && CONFIG.bubbleStates.includes(state))
713
- || (CONFIG.bubbleMode === 'custom' && tasks.length >= 2 && tasks.some((t) => CONFIG.bubbleStates.includes(t.state)))
714
- if (CONFIG.bubbleMode === 'hidden' || !shouldShow) {
715
- bubbleEl.classList.remove('visible')
716
- bubbleEl.style.pointerEvents = 'none'
717
- return
718
- }
719
- let title = ''
720
- let detail = ''
721
- if (pomodoroActive) {
722
- const remaining = Math.max(0, pomodoro.endAt - Date.now())
723
- const label = pomodoro.mode === 'work' ? '🍅 番茄钟' : '☕ 休息'
724
- title = `${label} ${formatTime(remaining)}`
725
- detail = pomodoro.mode === 'work' ? '大肥鱼专注中,冲鸭~' : '大肥鱼摸鱼中,放松一下~'
726
- } else if (manualActive) {
727
- title = manualBubble.message
728
- detail = manualBubble.detail || ''
729
- } else if (tasks.length >= 2) {
730
- title = `${tasks.length} 个任务进行中`
731
- detail = tasks.slice(0, 3).map((t) => `${t.state || ''} · ${t.project || t.task || t.message || ''}`).join(';')
732
- } else if (overlay && overlay.message) {
733
- title = overlay.message
734
- detail = overlay.detail || status.detail || ''
735
- } else if (status.message) {
736
- title = status.message
737
- detail = status.detail || ''
738
- } else {
739
- title = '大肥鱼正在摸鱼中~'
740
- detail = ''
741
- }
742
- // 余额显示:优先展示 DeepSeek 账户余额,不再显示 Token。
743
- if (balance && balance.total !== undefined && balance.total !== null) {
744
- const symbol = balance.currency === 'CNY' ? '¥' : balance.currency === 'USD' ? '$' : `${balance.currency} `
745
- const balanceText = `余额 ${symbol}${balance.total}`
746
- detail = detail ? `${detail} · ${balanceText}` : balanceText
747
- }
748
- bubbleTitle.textContent = title
749
- bubbleDetail.textContent = detail
750
- bubbleEl.style.transform = `translateX(-50%) scale(${CONFIG.bubbleScale})`
751
- bubbleEl.style.pointerEvents = 'auto'
752
- bubbleEl.classList.add('visible')
753
- }
754
-
755
- // ---------- 交互 ----------
756
- const DRAG_THRESHOLD = 5
757
-
758
- // 让透明窗口只在宠物/菜单区域接收鼠标,其余区域点击穿透到下层应用。
759
- function updateClickThrough() {
760
- const rect = hitEl.getBoundingClientRect()
761
- let inside = lastMouse.x >= rect.left && lastMouse.x <= rect.right
762
- && lastMouse.y >= rect.top && lastMouse.y <= rect.bottom
763
- // 气泡可见时也允许点击(用于点击刷新余额)。
764
- if (bubbleEl.classList.contains('visible')) {
765
- const b = bubbleEl.getBoundingClientRect()
766
- inside = inside || (lastMouse.x >= b.left && lastMouse.x <= b.right
767
- && lastMouse.y >= b.top && lastMouse.y <= b.bottom)
768
- }
769
- const menuVisible = menuEl.classList.contains('visible')
770
- const ignore = !inside && !dragging && !dragState.active && !menuVisible
771
- window.petBridge.setIgnoreMouse(ignore)
772
- }
773
-
774
- document.addEventListener('mousemove', (e) => {
775
- lastMouse = { x: e.clientX, y: e.clientY }
776
- updateClickThrough()
777
- })
778
-
779
- function startDrag(e) {
780
- clearIdleDelay()
781
- stopMove()
782
- e.currentTarget.classList.add('dragging')
783
- try { e.currentTarget.setPointerCapture(e.pointerId) } catch { /* 忽略捕获失败 */ }
784
- dragState = {
785
- active: true,
786
- dragging: false,
787
- pointerId: e.pointerId,
788
- sx: e.screenX,
789
- sy: e.screenY,
790
- lastX: e.screenX,
791
- lastY: e.screenY,
792
- }
793
- window.petBridge.setIgnoreMouse(false)
794
- }
795
-
796
- function moveDrag(e) {
797
- const d = dragState
798
- if (!d.active) return
799
- const totalDx = e.screenX - d.sx
800
- const totalDy = e.screenY - d.sy
801
- if (!d.dragging) {
802
- if (Math.hypot(totalDx, totalDy) < DRAG_THRESHOLD) return
803
- d.dragging = true
804
- dragging = true
805
- playDrag()
806
- showManualBubble('大肥鱼被拎起来啦!', '快放我下来~', 3000)
807
- }
808
- // 在全屏透明画布内移动宠物 DOM,避免移动窗口导致的指针事件问题。
809
- const dx = e.movementX || 0
810
- const dy = e.movementY || 0
811
- if (dx || dy) {
812
- // 按角色实际命中区域贴边,而不是按整个透明舞台贴边,
813
- // 这样宠物可以真正拖到屏幕最左/最右。
814
- const hitLeft = HIT_BOX.x0 / 640 * size
815
- const hitRight = HIT_BOX.x1 / 640 * size
816
- const minX = -hitLeft
817
- const maxX = window.innerWidth - hitRight
818
- petPos.x = Math.min(Math.max(petPos.x + dx, minX), maxX)
819
- petPos.y = Math.min(Math.max(petPos.y + dy, 0), window.innerHeight - size * 9 / 16)
820
- applyPetPosition()
821
- }
822
- }
823
-
824
- function endDrag(e) {
825
- const d = dragState
826
- if (!d.active) return
827
- const wasDragging = d.dragging
828
- dragState = { active: false, dragging: false, sx: 0, sy: 0, lastX: 0, lastY: 0 }
829
- dragging = false
830
- window.petBridge.endDrag()
831
- if (e.currentTarget && e.currentTarget.classList) {
832
- e.currentTarget.classList.remove('dragging')
833
- } else {
834
- hitEl.classList.remove('dragging')
835
- }
836
- if (wasDragging) {
837
- justDragged = true
838
- setTimeout(() => { justDragged = false }, 100)
839
- applyResume()
840
- showManualBubble('终于放我下来啦~', '', 2000)
841
- }
842
- updateClickThrough()
843
- }
844
-
845
- hitEl.addEventListener('pointerdown', startDrag)
846
- hitEl.addEventListener('pointermove', moveDrag)
847
- // 即使 pointerup 因为窗口移动没有落在宠物元素上,也要保证拖拽状态被重置。
848
- window.addEventListener('pointerup', endDrag)
849
- window.addEventListener('pointercancel', endDrag)
850
- hitEl.addEventListener('lostpointercapture', endDrag)
851
-
852
- hitEl.addEventListener('click', (e) => {
853
- if (dragState.active || dragging || justDragged) return
854
- playClick()
855
- })
856
-
857
- hitEl.addEventListener('contextmenu', (e) => {
858
- e.preventDefault()
859
- showMenu(e.clientX, e.clientY)
860
- })
861
-
862
- // 点击余额气泡可手动刷新余额。
863
- bubbleEl.addEventListener('click', (e) => {
864
- e.stopPropagation()
865
- window.petBridge.refreshBalance()
866
- showManualBubble('余额刷新中~', '', 1500)
867
- })
868
-
869
- function addMenuButton(label, onClick) {
870
- const button = document.createElement('button')
871
- button.textContent = label
872
- button.addEventListener('click', onClick)
873
- menuEl.appendChild(button)
874
- return button
875
- }
876
-
877
- function showMenu(x, y) {
878
- lastMenuPos = { x, y }
879
- menuEl.innerHTML = ''
880
- if (menuPage === 'pomodoro') {
881
- renderPomodoroSettings()
882
- } else if (menuPage === 'actions') {
883
- renderActionSettings()
884
- } else if (menuPage === 'appearance') {
885
- renderAppearanceSettings()
886
- } else {
887
- renderMainMenu()
888
- }
889
- // 外层菜单不滚动,动作列表等长内容由内部子面板自己滚动,避免出现双滚动条。
890
- menuEl.style.maxHeight = 'none'
891
- menuEl.style.overflowY = 'visible'
892
- menuEl.classList.add('visible')
893
- // 让菜单向右上方展开,避开宠物模型;再根据实际尺寸夹在屏幕内。
894
- const rect = menuEl.getBoundingClientRect()
895
- let left = x + 24
896
- let top = y - rect.height - 12
897
- left = Math.max(4, Math.min(left, window.innerWidth - rect.width - 4))
898
- top = Math.max(4, Math.min(top, window.innerHeight - rect.height - 4))
899
- menuEl.style.left = left + 'px'
900
- menuEl.style.top = top + 'px'
901
- window.petBridge.setIgnoreMouse(false)
902
- }
903
-
904
- function renderMainMenu() {
905
- addMenuButton('喂食', () => {
906
- menuEl.classList.remove('visible')
907
- updateClickThrough()
908
- feedPet()
909
- })
910
- if (CONFIG.enabled) {
911
- addMenuButton('禁用 Better DSH Pet', () => {
912
- CONFIG.enabled = false
913
- window.petBridge.saveConfig({ enabled: false })
914
- menuEl.classList.remove('visible')
915
- updateClickThrough()
916
- })
917
- }
918
- addMenuButton(`开始番茄钟 ${CONFIG.workMinutes}分`, () => {
919
- menuEl.classList.remove('visible')
920
- updateClickThrough()
921
- startPomodoro('work', CONFIG.workMinutes)
922
- })
923
- addMenuButton(`开始短休息 ${CONFIG.breakMinutes}分`, () => {
924
- menuEl.classList.remove('visible')
925
- updateClickThrough()
926
- startPomodoro('break', CONFIG.breakMinutes)
927
- })
928
- if (pomodoro) {
929
- addMenuButton('停止番茄钟', () => {
930
- menuEl.classList.remove('visible')
931
- updateClickThrough()
932
- stopPomodoro()
933
- })
934
- }
935
- addMenuButton('番茄钟设置', () => {
936
- menuPage = 'pomodoro'
937
- showMenu(lastMenuPos.x, lastMenuPos.y)
938
- })
939
- addMenuButton('行为设置', () => {
940
- menuPage = 'appearance'
941
- showMenu(lastMenuPos.x, lastMenuPos.y)
942
- })
943
- // 选择待机动作:鼠标悬停展开,移开自动关闭。
944
- const actionWrap = document.createElement('div')
945
- actionWrap.style.cssText = 'position:static'
946
- const actionBtn = document.createElement('button')
947
- actionBtn.textContent = '选择待机动作'
948
- const actionFlyout = document.createElement('div')
949
- actionFlyout.style.cssText = 'margin-top:4px;background:#fff;border:1px solid #e3e5e8;border-radius:10px;box-shadow:0 8px 24px rgba(0,0,0,.18);padding:8px;max-height:70vh;overflow-y:auto;display:none'
950
- actionBtn.addEventListener('mouseenter', () => {
951
- renderActionFlyoutContent(actionFlyout)
952
- actionFlyout.style.display = 'block'
953
- })
954
- actionWrap.addEventListener('mouseleave', (e) => {
955
- if (!actionFlyout.contains(e.relatedTarget)) actionFlyout.style.display = 'none'
956
- })
957
- actionFlyout.addEventListener('mouseleave', (e) => {
958
- if (!actionWrap.contains(e.relatedTarget)) actionFlyout.style.display = 'none'
959
- })
960
- actionWrap.appendChild(actionBtn)
961
- actionWrap.appendChild(actionFlyout)
962
- menuEl.appendChild(actionWrap)
963
- addMenuButton(CONFIG.roastEnabled ? '关闭自动吐槽' : '开启自动吐槽', () => {
964
- const next = !CONFIG.roastEnabled
965
- CONFIG.roastEnabled = next
966
- window.petBridge.saveConfig({ roastEnabled: next })
967
- menuEl.classList.remove('visible')
968
- updateClickThrough()
969
- })
970
- addMenuButton(CONFIG.walkEnabled ? '关闭行走' : '开启行走', () => {
971
- const next = !CONFIG.walkEnabled
972
- CONFIG.walkEnabled = next
973
- window.petBridge.saveConfig({ walkEnabled: next })
974
- menuEl.classList.remove('visible')
975
- updateClickThrough()
976
- })
977
- addMenuButton('让大肥鱼吐槽一下', () => {
978
- menuEl.classList.remove('visible')
979
- updateClickThrough()
980
- window.petBridge.requestRoast()
981
- })
982
- addMenuButton('打开 DSH 桌面版', () => {
983
- menuEl.classList.remove('visible')
984
- updateClickThrough()
985
- window.petBridge.openDesktop()
986
- })
987
- addMenuButton('本次隐藏', () => {
988
- menuEl.classList.remove('visible')
989
- updateClickThrough()
990
- window.petBridge.hide()
991
- })
992
- addMenuButton('本次关闭', () => {
993
- menuEl.classList.remove('visible')
994
- updateClickThrough()
995
- window.petBridge.close('user')
996
- })
997
- }
998
-
999
- function renderPomodoroSettings() {
1000
- addMenuButton('← 返回主菜单', () => {
1001
- menuPage = 'main'
1002
- showMenu(lastMenuPos.x, lastMenuPos.y)
1003
- })
1004
- const workInput = document.createElement('input')
1005
- workInput.type = 'number'
1006
- workInput.min = 1
1007
- workInput.max = 120
1008
- workInput.value = String(CONFIG.workMinutes)
1009
- workInput.style.width = '80px'
1010
-
1011
- const breakInput = document.createElement('input')
1012
- breakInput.type = 'number'
1013
- breakInput.min = 1
1014
- breakInput.max = 60
1015
- breakInput.value = String(CONFIG.breakMinutes)
1016
- breakInput.style.width = '80px'
1017
-
1018
- const workRow = document.createElement('div')
1019
- workRow.style.cssText = 'display:flex;justify-content:space-between;align-items:center;gap:8px;padding:4px 0'
1020
- workRow.append('工作时长(分)', workInput)
1021
-
1022
- const breakRow = document.createElement('div')
1023
- breakRow.style.cssText = 'display:flex;justify-content:space-between;align-items:center;gap:8px;padding:4px 0'
1024
- breakRow.append('休息时长(分)', breakInput)
1025
-
1026
- menuEl.append(workRow, breakRow)
1027
-
1028
- addMenuButton('保存', () => {
1029
- const work = Math.min(120, Math.max(1, Number(workInput.value) || 25))
1030
- const rest = Math.min(60, Math.max(1, Number(breakInput.value) || 5))
1031
- CONFIG.workMinutes = work
1032
- CONFIG.breakMinutes = rest
1033
- window.petBridge.saveConfig({ workMinutes: work, breakMinutes: rest })
1034
- menuPage = 'main'
1035
- menuEl.classList.remove('visible')
1036
- updateClickThrough()
1037
- updateBubble()
1038
- })
1039
- addMenuButton('返回', () => {
1040
- menuPage = 'main'
1041
- showMenu(lastMenuPos.x, lastMenuPos.y)
1042
- })
1043
- }
1044
-
1045
- function renderAppearanceSettings() {
1046
- addMenuButton('← 返回主菜单', () => {
1047
- menuPage = 'main'
1048
- showMenu(lastMenuPos.x, lastMenuPos.y)
1049
- })
1050
-
1051
- const sizeInput = document.createElement('input')
1052
- sizeInput.type = 'number'
1053
- sizeInput.min = 100
1054
- sizeInput.max = 1000
1055
- sizeInput.step = 10
1056
- sizeInput.value = String(CONFIG.petSize)
1057
- sizeInput.style.width = '80px'
1058
-
1059
- const moveInput = document.createElement('input')
1060
- moveInput.type = 'range'
1061
- moveInput.min = 0
1062
- moveInput.max = 100
1063
- moveInput.step = 1
1064
- moveInput.value = String(CONFIG.moveChance)
1065
- moveInput.style.width = '120px'
1066
-
1067
- const delayInput = document.createElement('input')
1068
- delayInput.type = 'range'
1069
- delayInput.min = 0
1070
- delayInput.max = 5000
1071
- delayInput.step = 100
1072
- delayInput.value = String(CONFIG.actionDelayMs)
1073
- delayInput.style.width = '120px'
1074
-
1075
- const row = (label, input, hint) => {
1076
- const div = document.createElement('div')
1077
- div.style.cssText = 'display:flex;justify-content:space-between;align-items:center;gap:8px;padding:4px 0;font-size:12px'
1078
- const left = document.createElement('span')
1079
- left.textContent = label
1080
- div.append(left, input)
1081
- if (hint) {
1082
- const small = document.createElement('small')
1083
- small.textContent = hint
1084
- small.style.cssText = 'display:block;opacity:.65;font-size:11px'
1085
- div.appendChild(small)
1086
- }
1087
- return div
1088
- }
1089
-
1090
- menuEl.append(
1091
- row('宠物宽度(px)', sizeInput, '重启后生效'),
1092
- row(`移动频繁度 ${moveInput.value}%`, moveInput),
1093
- row(`动作切换间隔 ${delayInput.value}ms`, delayInput),
1094
- )
1095
- moveInput.addEventListener('input', () => {
1096
- const label = moveInput.parentElement
1097
- label.firstChild.textContent = `移动频繁度 ${moveInput.value}%`
1098
- })
1099
- delayInput.addEventListener('input', () => {
1100
- const label = delayInput.parentElement
1101
- label.firstChild.textContent = `动作切换间隔 ${delayInput.value}ms`
1102
- })
1103
-
1104
- addMenuButton('保存', () => {
1105
- CONFIG.petSize = Math.min(1000, Math.max(100, Math.round(Number(sizeInput.value) / 10) * 10 || 460))
1106
- CONFIG.moveChance = Math.min(100, Math.max(0, Number(moveInput.value) || 0))
1107
- CONFIG.actionDelayMs = Math.min(5000, Math.max(0, Number(delayInput.value) || 0))
1108
- window.petBridge.saveConfig({
1109
- petSize: CONFIG.petSize,
1110
- moveChance: CONFIG.moveChance,
1111
- actionDelayMs: CONFIG.actionDelayMs,
1112
- })
1113
- menuPage = 'main'
1114
- menuEl.classList.remove('visible')
1115
- updateClickThrough()
1116
- })
1117
- addMenuButton('返回', () => {
1118
- menuPage = 'main'
1119
- showMenu(lastMenuPos.x, lastMenuPos.y)
1120
- })
1121
- }
1122
-
1123
- function renderActionSettings() {
1124
- // 空数组 = 全部动作,所以 UI 里初始化为全选。
1125
- addMenuButton('← 返回主菜单', () => {
1126
- menuPage = 'main'
1127
- showMenu(lastMenuPos.x, lastMenuPos.y)
1128
- })
1129
- const working = CONFIG.enabledActions.length > 0 ? CONFIG.enabledActions.slice() : ACTS.slice()
1130
- const list = document.createElement('div')
1131
- list.style.cssText = 'max-height:70vh;overflow-y:auto;margin:4px 0'
1132
-
1133
- const addToggle = (name) => {
1134
- const label = document.createElement('label')
1135
- label.style.cssText = 'display:flex;align-items:center;gap:6px;padding:2px 0;font-size:12px;cursor:pointer'
1136
- const checkbox = document.createElement('input')
1137
- checkbox.type = 'checkbox'
1138
- checkbox.checked = working.includes(name)
1139
- checkbox.addEventListener('change', () => {
1140
- if (checkbox.checked) {
1141
- if (!working.includes(name)) working.push(name)
1142
- } else {
1143
- const index = working.indexOf(name)
1144
- if (index >= 0) working.splice(index, 1)
1145
- }
1146
- })
1147
- label.append(checkbox, name)
1148
- list.appendChild(label)
1149
- }
1150
-
1151
- ACTS.forEach(addToggle)
1152
- menuEl.append(list)
1153
-
1154
- addMenuButton('全部动作', () => {
1155
- working.length = 0
1156
- working.push(...ACTS)
1157
- for (const input of list.querySelectorAll('input')) input.checked = true
1158
- })
1159
- addMenuButton('保存', () => {
1160
- // 全选时保存空数组 = 全部动作;否则保存勾选子集。
1161
- const next = working.length === ACTS.length ? [] : working.slice()
1162
- CONFIG.enabledActions = next
1163
- window.petBridge.saveConfig({ enabledActions: next })
1164
- menuPage = 'main'
1165
- menuEl.classList.remove('visible')
1166
- updateClickThrough()
1167
- })
1168
- addMenuButton('返回', () => {
1169
- menuPage = 'main'
1170
- showMenu(lastMenuPos.x, lastMenuPos.y)
1171
- })
1172
- }
1173
-
1174
- function renderActionFlyoutContent(panel) {
1175
- panel.innerHTML = ''
1176
- const working = CONFIG.enabledActions.length > 0 ? CONFIG.enabledActions.slice() : ACTS.slice()
1177
- const list = document.createElement('div')
1178
- list.style.cssText = 'max-height:60vh;overflow-y:auto;margin:2px 0'
1179
- ACTS.forEach((name) => {
1180
- const label = document.createElement('label')
1181
- label.style.cssText = 'display:flex;align-items:center;gap:6px;padding:2px 0;font-size:12px;cursor:pointer'
1182
- const checkbox = document.createElement('input')
1183
- checkbox.type = 'checkbox'
1184
- checkbox.checked = working.includes(name)
1185
- checkbox.addEventListener('change', () => {
1186
- if (checkbox.checked) {
1187
- if (!working.includes(name)) working.push(name)
1188
- } else {
1189
- const index = working.indexOf(name)
1190
- if (index >= 0) working.splice(index, 1)
1191
- }
1192
- })
1193
- label.append(checkbox, name)
1194
- list.appendChild(label)
1195
- })
1196
- panel.appendChild(list)
1197
-
1198
- const row = document.createElement('div')
1199
- row.style.cssText = 'display:flex;gap:6px;margin-top:4px'
1200
- const allBtn = document.createElement('button')
1201
- allBtn.textContent = '全部动作'
1202
- allBtn.addEventListener('click', () => {
1203
- working.length = 0
1204
- working.push(...ACTS)
1205
- for (const input of panel.querySelectorAll('input')) input.checked = true
1206
- })
1207
- const saveBtn = document.createElement('button')
1208
- saveBtn.textContent = '保存'
1209
- saveBtn.addEventListener('click', () => {
1210
- const next = working.length === ACTS.length ? [] : working.slice()
1211
- CONFIG.enabledActions = next
1212
- window.petBridge.saveConfig({ enabledActions: next })
1213
- panel.style.display = 'none'
1214
- })
1215
- const closeBtn = document.createElement('button')
1216
- closeBtn.textContent = '关闭'
1217
- closeBtn.addEventListener('click', () => {
1218
- panel.style.display = 'none'
1219
- })
1220
- row.append(allBtn, saveBtn, closeBtn)
1221
- panel.appendChild(row)
1222
- }
1223
-
1224
- document.addEventListener('click', (e) => {
1225
- if (!menuEl.contains(e.target)) {
1226
- menuEl.classList.remove('visible')
1227
- updateClickThrough()
1228
- }
1229
- })
1230
-
1231
- // ---------- 状态订阅 ----------
1232
- function applyStatus(incoming) {
1233
- if (!incoming || typeof incoming !== 'object') return
1234
-
1235
- if (incoming.config) {
1236
- CONFIG.enabled = incoming.config.enabled !== false
1237
- CONFIG.bubbleMode = incoming.config.bubbleMode || CONFIG.bubbleMode
1238
- CONFIG.bubbleStates = Array.isArray(incoming.config.bubbleStates) ? incoming.config.bubbleStates : CONFIG.bubbleStates
1239
- CONFIG.reducedMotion = incoming.config.reducedMotion === true
1240
- CONFIG.activityLevel = incoming.config.activityLevel || CONFIG.activityLevel
1241
- CONFIG.bubbleScale = Number(incoming.config.bubbleScale || CONFIG.bubbleScale)
1242
- CONFIG.workMinutes = Number(incoming.config.workMinutes) || CONFIG.workMinutes
1243
- CONFIG.breakMinutes = Number(incoming.config.breakMinutes) || CONFIG.breakMinutes
1244
- CONFIG.roastEnabled = incoming.config.roastEnabled === true
1245
- CONFIG.walkEnabled = incoming.config.walkEnabled !== false
1246
- CONFIG.enabledActions = Array.isArray(incoming.config.enabledActions) ? incoming.config.enabledActions : []
1247
- CONFIG.actionOrder = Array.isArray(incoming.config.actionOrder) ? incoming.config.actionOrder : []
1248
- CONFIG.petSize = Number(incoming.config.petSize) || CONFIG.petSize
1249
- CONFIG.moveChance = Number(incoming.config.moveChance) ?? CONFIG.moveChance
1250
- CONFIG.actionDelayMs = Number(incoming.config.actionDelayMs) ?? CONFIG.actionDelayMs
1251
- CONFIG.scale = Number(incoming.config.scale) || CONFIG.scale
1252
- applySize()
1253
- }
1254
-
1255
- if (incoming.tokenUsage) {
1256
- tokenUsage = {
1257
- inputTokens: Number(incoming.tokenUsage.inputTokens) || 0,
1258
- outputTokens: Number(incoming.tokenUsage.outputTokens) || 0,
1259
- totalTokens: Number(incoming.tokenUsage.totalTokens) || 0,
1260
- }
1261
- }
1262
-
1263
- if (incoming.balance) {
1264
- balance = {
1265
- currency: incoming.balance.currency || 'CNY',
1266
- total: incoming.balance.total,
1267
- granted: incoming.balance.granted,
1268
- toppedUp: incoming.balance.toppedUp,
1269
- isAvailable: incoming.balance.isAvailable !== false,
1270
- updatedAt: incoming.balance.updatedAt,
1271
- }
1272
- } else if (incoming.balance === null) {
1273
- balance = null
1274
- }
1275
-
1276
- if (incoming.roast && incoming.roast !== lastRoast) {
1277
- roast = incoming.roast
1278
- lastRoast = incoming.roast
1279
- showManualBubble(roast, '大肥鱼吐槽time~', 5000)
1280
- }
1281
-
1282
- if (incoming.pulse) {
1283
- // 同一个脉冲持续轮询时不要反复重播动画。
1284
- const pulseKey = `${incoming.pulse.state}:${incoming.pulse.expiresAt || incoming.pulse.ttlMs || 1800}`
1285
- if (lastPulseKey === pulseKey) {
1286
- if (overlay) {
1287
- overlay.message = incoming.pulse.message || overlay.message
1288
- overlay.detail = incoming.pulse.detail || overlay.detail
1289
- }
1290
- updateBubble()
1291
- return
1292
- }
1293
- applyPulseMessage(incoming.pulse)
1294
- return
1295
- }
1296
-
1297
- if (incoming.tasks && incoming.tasks.length >= 2) {
1298
- tasks = incoming.tasks
1299
- } else if (incoming.tasks) {
1300
- tasks = incoming.tasks
1301
- }
1302
-
1303
- const nextState = incoming.state || 'IDLE'
1304
- if (nextState !== currentState) {
1305
- applyStateMessage({
1306
- state: nextState,
1307
- message: incoming.message,
1308
- detail: incoming.detail,
1309
- project: incoming.project,
1310
- task: incoming.task,
1311
- progress: incoming.progress,
1312
- })
1313
- } else {
1314
- // 状态没变:只更新气泡文案/任务信息,不打断当前动画。
1315
- status = {
1316
- ...status,
1317
- state: nextState,
1318
- message: incoming.message ?? status.message,
1319
- detail: incoming.detail ?? status.detail,
1320
- project: incoming.project ?? status.project,
1321
- task: incoming.task ?? status.task,
1322
- progress: incoming.progress ?? status.progress,
1323
- }
1324
- updateBubble()
1325
- }
1326
- }
1327
-
1328
- window.petBridge.onStatus((status) => {
1329
- applyStatus(status)
1330
- })
1331
-
1332
- // ---------- 启动 ----------
1333
- playIdle()
1334
- updateBubble()
1335
- updateClickThrough()
1336
-
1337
- // 看门狗:万一 video 的 ended 事件或 loop 没有按预期工作,这里兜底,
1338
- // 避免宠物停在最后一帧。
1339
- setInterval(() => {
1340
- if (pending) return
1341
- const el = currentVideo()
1342
- if (!el || !el.ended) return
1343
- if (animLoop) {
1344
- el.currentTime = 0
1345
- el.play().catch(() => {})
1346
- } else if (!dragging && !dragState.active) {
1347
- handleEnded()
1348
- }
1349
- }, 500)
1
+ /**
2
+ * better-dsh-pet desktop helper renderer —— 透明窗口里的宠物本体。
3
+ *
4
+ * 使用纯 DOM + 双 video 缓冲播放 better-dsh-pet 的 WebM 动画;接收主进程转发的
5
+ * Companion 消息,根据 DSH 状态切换动画并显示气泡。
6
+ */
7
+
8
+ // ---------- 配置 ----------
9
+ const params = new URLSearchParams(location.search)
10
+ const CONFIG = {
11
+ enabled: params.get('enabled') !== '0',
12
+ scale: Number(params.get('scale') || '1'),
13
+ bubbleScale: Number(params.get('bubbleScale') || '1'),
14
+ activityLevel: params.get('activityLevel') || 'normal',
15
+ reducedMotion: params.get('reducedMotion') === '1',
16
+ bubbleMode: params.get('bubbleMode') || 'always',
17
+ bubbleStates: (params.get('bubbleStates') || 'SUCCESS,ERROR,WAITING').split(',').filter(Boolean),
18
+ webuiUrl: params.get('webuiUrl') || 'http://127.0.0.1:3080/',
19
+ workMinutes: Number(params.get('workMinutes') || '25'),
20
+ breakMinutes: Number(params.get('breakMinutes') || '5'),
21
+ roastEnabled: params.get('roastEnabled') === '1',
22
+ walkEnabled: params.get('walkEnabled') !== '0',
23
+ enabledActions: [],
24
+ actionOrder: [],
25
+ petSize: Number(params.get('petSize') || '460'),
26
+ moveChance: Number(params.get('moveChance') || '20'),
27
+ actionDelayMs: Number(params.get('actionDelayMs') || '0'),
28
+ playbackRate: Number(params.get('playbackRate') || '1'),
29
+ voiceEnabled: params.get('voiceEnabled') !== '0',
30
+ voiceWakeAutoStart: params.get('voiceWakeAutoStart') === '1',
31
+ voiceSilenceMs: Number(params.get('voiceSilenceMs') || '1200'),
32
+ voiceAutoSend: params.get('voiceAutoSend') !== '0',
33
+ voiceAutoRecord: params.get('voiceAutoRecord') !== '0',
34
+ holidayEnabled: params.get('holidayEnabled') === '1',
35
+ wakeWord: params.get('wakeWord') || '大肥鱼',
36
+ taskCwd: params.get('taskCwd') || '',
37
+ }
38
+
39
+ // ---------- 资源根 ----------
40
+ const ASSET_BASE = new URL('../../assets/thumb/', location.href).href
41
+ const FESTIVAL_GIF_BASE = new URL('../../assets/preview/', location.href).href
42
+ const ALARM_URL = new URL('../../assets/alarm.mp3', location.href).href
43
+
44
+ // ---------- 动画目录 ----------
45
+ const CANVAS_H = 360
46
+ const FEET_Y = 330
47
+ const HIT_BOX = { x0: 200, y0: 50, x1: 440, y1: 335 }
48
+
49
+ const IDLE = '待机呼吸休闲'
50
+ const TURN = '东张西望'
51
+ const DRAG = '被鼠标拖拽悬空反馈'
52
+ const ACTS = [
53
+ '被落叶淹没', '被吓一跳', '变鸽子', '插茱萸赏菊', '拆礼物',
54
+ '超大伸懒腰', '晨间刷牙', '吃Token', '吃白饭', '吃冰淇淋融化',
55
+ '吃大闸蟹', '吃饺子', '吃腊八粥', '吃年糕', '吃青团',
56
+ '吃汤圆', '吃糖葫芦', '吃晚餐', '吃午餐', '吃西瓜',
57
+ '吃早餐', '吃长寿面', '吃重阳糕', '吃粽子', '抽陀螺',
58
+ '穿针乞巧', '吹笛子', '吹气球', '打瞌睡被惊醒', '大口吃零食',
59
+ '荡秋千', '动物环绕', '堆雪人', '放风筝', '放河灯',
60
+ '放孔明灯', '放烟花', '哈欠连天', '蝴蝶蜜蜂环绕头顶开花', '鲸鱼吐泡泡特效',
61
+ '可爱宅舞', '蓝鲸现世', '撸猫', '萌化小幽灵', '女仆屈膝礼仪',
62
+ '凭空生花', '扑克魔术', '骑木马', '轻快记录', '轻快摇摆舞',
63
+ '三球抛接', '深度思考碎碎念', '是啊,吃什么', '收红包', '涮火锅',
64
+ '讨糖南瓜灯', '踢毽子', '偷吃零食被抓住', '玩水枪', '玩游戏气急败坏',
65
+ '舞狮头', '下五子棋', '小幅度原地360度旋转展示', '小提琴演奏', '写代码',
66
+ '写福字', '摇扇纳凉', '用鲸鱼尾巴拍打地面', '优雅女仆舞', '悠闲哼歌',
67
+ '原地蹲下玩玩具汽车', '原地敲击桌面互动', '原地跳跃抓碎头顶物品', '原地小憩沉眠',
68
+ '原地重力下蹲压缩', '原地专心玩魔方', '照镜子', '整体换装试色',
69
+ '中秋赏月吃月饼', '装点圣诞树',
70
+ ]
71
+ const ACTION_COPY = {
72
+ '东张西望': '大肥鱼东张西望,看看有没有鱼干~',
73
+ '悠闲哼歌': '大肥鱼悠闲地哼着小曲~',
74
+ '超大伸懒腰': '大肥鱼伸了个大大的懒腰~',
75
+ '原地专心玩魔方': '大肥鱼在专心拧魔方呢~',
76
+ '原地敲击桌面互动': '大肥鱼在敲桌面求关注~',
77
+ '原地重力下蹲压缩': '大肥鱼像弹簧一样蹲下去啦~',
78
+ '哈欠连天': '大肥鱼打了个大大的哈欠~',
79
+ '原地小憩沉眠': '大肥鱼偷偷打了个盹儿~',
80
+ '原地蹲下玩玩具汽车': '大肥鱼蹲在地上玩小汽车~',
81
+ '鲸鱼吐泡泡特效': '大肥鱼吐出一串可爱的泡泡~',
82
+ '女仆屈膝礼仪': '大肥鱼向你行了个女仆礼~',
83
+ '被吓一跳': '大肥鱼被吓得炸毛啦!',
84
+ '原地跳跃抓碎头顶物品': '大肥鱼跳起来抓碎了头顶的东西~',
85
+ '小幅度原地360度旋转展示': '大肥鱼原地转圈圈展示自己~',
86
+ '偷吃零食被抓住': '大肥鱼偷吃零食被抓住啦!',
87
+ '玩游戏气急败坏': '大肥鱼玩游戏玩到气急败坏~',
88
+ '用鲸鱼尾巴拍打地面': '大肥鱼用尾巴拍地面抗议~',
89
+ '打瞌睡被惊醒': '大肥鱼打瞌睡被吓醒了!',
90
+ '玩水枪': '大肥鱼拿起水枪滋水玩~',
91
+ '小提琴演奏': '大肥鱼拉起了小提琴~',
92
+ '蓝鲸现世': '蓝鲸大肥鱼现身啦!',
93
+ '吃白饭': '大肥鱼在专心吃白饭~',
94
+ '照镜子': '大肥鱼照镜子臭美中~',
95
+ '优雅女仆舞': '大肥鱼跳起了优雅的女仆舞~',
96
+ '轻快摇摆舞': '大肥鱼轻快地摇摆跳舞~',
97
+ '可爱宅舞': '大肥鱼跳起了可爱宅舞~',
98
+ '整体换装试色': '大肥鱼在试新衣服的颜色~',
99
+ '大口吃零食': '大肥鱼大口大口吃零食~',
100
+ '吹气球': '大肥鱼在努力吹气球~',
101
+ '动物环绕': '好多小动物围着大肥鱼转~',
102
+ '深度思考碎碎念': '大肥鱼陷入深度思考,碎碎念中~',
103
+ '轻快记录': '大肥鱼在轻快地记笔记~',
104
+ '写代码': '大肥鱼在认真写代码~',
105
+ '吃Token': '大肥鱼把 Token 当零食吃掉啦~',
106
+ '吃早餐': '大肥鱼在吃早餐~',
107
+ '吃午餐': '大肥鱼在吃午餐~',
108
+ '吃晚餐': '大肥鱼在吃晚餐~',
109
+ '放风筝': '大肥鱼在放风筝~',
110
+ '摇扇纳凉': '大肥鱼摇着扇子纳凉~',
111
+ '吃冰淇淋融化': '大肥鱼吃冰淇淋,可是化得好快~',
112
+ '被落叶淹没': '大肥鱼被落叶埋住啦~',
113
+ '中秋赏月吃月饼': '大肥鱼中秋赏月吃月饼~',
114
+ '堆雪人': '大肥鱼在堆雪人~',
115
+ '螃蟹走路': '大肥鱼横着走路,超嚣张~',
116
+ '原地漂浮踏步': '大肥鱼原地踏步漂浮中~',
117
+ '原地左转奔跑': '大肥鱼向左奔跑!',
118
+ }
119
+ const CLICKS = ['点击回应-开心跃动', '点击回应-害羞惊讶', '点击回应-傲娇生气', '点击回应-挠痒咯咯笑', '点击回应-元气挥手']
120
+ const CLICK_COPY = {
121
+ '点击回应-开心跃动': '大肥鱼被摸得好开心~',
122
+ '点击回应-害羞惊讶': '大肥鱼害羞地躲了一下~',
123
+ '点击回应-傲娇生气': '大肥鱼傲娇地哼了一声!',
124
+ '点击回应-挠痒咯咯笑': '大肥鱼被挠痒痒,咯咯笑~',
125
+ '点击回应-元气挥手': '大肥鱼元气满满地挥手~',
126
+ }
127
+ const EAT_ANIMS = ['吃白饭', '吃早餐', '吃午餐', '吃晚餐', '大口吃零食', '吃Token', '吃冰淇淋融化', '偷吃零食被抓住']
128
+ const MOVES = ['螃蟹走路', '原地漂浮踏步', '原地左转奔跑']
129
+ // 每个走动动画的“开头不动/结尾不动”时长(秒),按动作实际节奏微调。
130
+ const MOVE_TIMING = {
131
+ '原地漂浮踏步': { lead: 0.83, tail: 0.83 },
132
+ '螃蟹走路': { lead: 1, tail: 2 },
133
+ '原地左转奔跑': { lead: 1.67, tail: 5.58 },
134
+ }
135
+ const STATE_ANIMS = {
136
+ IDLE: [IDLE],
137
+ THINKING: ['深度思考碎碎念', '原地专心玩魔方', '东张西望'],
138
+ WORKING: ['写代码', '轻快记录', '原地敲击桌面互动', '吃Token'],
139
+ WAITING: ['东张西望', '悠闲哼歌', '原地敲击桌面互动'],
140
+ SUCCESS: ['点击回应-开心跃动', '优雅女仆舞', '轻快摇摆舞', '可爱宅舞', '女仆屈膝礼仪'],
141
+ ERROR: ['被吓一跳', '玩游戏气急败坏', '偷吃零食被抓住'],
142
+ }
143
+
144
+ // 情绪系统:根据状态和互动累积情绪,影响空闲动作和气泡。
145
+ const EMOTION_ACTION_POOLS = {
146
+ tired: ['原地小憩沉眠', '打瞌睡被惊醒', '哈欠连天', '超大伸懒腰'],
147
+ happy: ['轻快摇摆舞', '可爱宅舞', '优雅女仆舞', '点击回应-开心跃动'],
148
+ anxious: ['东张西望', '被吓一跳', '原地敲击桌面互动', '深度思考碎碎念'],
149
+ bored: ['原地漂浮踏步', '原地专心玩魔方', '三球抛接', '荡秋千'],
150
+ }
151
+ const EMOTION_BUBBLES = {
152
+ tired: ['好累啊,让我趴一会儿…', '眼睛快睁不开了…', '今天也是辛苦的一天呢…'],
153
+ happy: ['今天心情超好!', '嘿嘿,开心!', '想转圈圈~'],
154
+ anxious: ['有点小紧张…', '这个任务没问题吧?', '别急别急,我在想…'],
155
+ bored: ['好无聊啊…', '有没有鱼干吃?', '什么时候有新任务呀…'],
156
+ }
157
+ const EMOTION_BAR_META = [
158
+ { key: 'mood', label: '心情', color: '#ff6b6b', format: (v) => `${v > 0 ? '+' : ''}${Math.round(v)}` },
159
+ { key: 'energy', label: '精力', color: '#4ecdc4', format: (v) => `${Math.round(v)}` },
160
+ { key: 'anxiety', label: '焦虑', color: '#f9ca24', format: (v) => `${Math.round(v)}` },
161
+ { key: 'boredom', label: '无聊', color: '#a29bfe', format: (v) => `${Math.round(v)}` },
162
+ ]
163
+ // 互动/状态对情绪的具体数值(便于后续在 UI 里展示“+12 精力”这类反馈)。
164
+ const EMOTION_DELTAS = {
165
+ click: { mood: 6, energy: 3, anxiety: -3, boredom: -4 },
166
+ feed: { mood: 12, energy: 10, anxiety: -5, boredom: -8 },
167
+ pomodoro: { mood: 18, energy: 8, anxiety: -6, boredom: -10 },
168
+ stateIdle: { mood: -1, energy: -1, anxiety: -2, boredom: 3 },
169
+ stateThinking: { mood: 0, energy: -2, anxiety: 2, boredom: -2 },
170
+ stateWorking: { mood: 1, energy: -3, anxiety: 0, boredom: -3 },
171
+ stateWaiting: { mood: -1, energy: -1, anxiety: 3, boredom: 2 },
172
+ stateSuccess: { mood: 12, energy: 5, anxiety: -8, boredom: -10 },
173
+ stateError: { mood: -10, energy: -4, anxiety: 10, boredom: -4 },
174
+ }
175
+
176
+ const LUNAR_DATE_FORMAT = new Intl.DateTimeFormat('zh-CN-u-ca-chinese', { month: 'numeric', day: 'numeric' })
177
+ const LUNAR_MONTH_NAMES = ['正月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '冬月', '腊月']
178
+ const FESTIVAL_AUTO_PLAY_KEY = 'better-dsh-pet:festival-auto-play'
179
+ const FESTIVAL_DEFS = [
180
+ { id: 'solar-new-year', calendar: 'solar', label: '元旦', greeting: '元旦快乐', detail: '大肥鱼给你送上新年祝福~', month: 1, day: 1, anim: '放烟花' },
181
+ { id: 'lunar-spring-festival', calendar: 'lunar', label: '春节', greeting: '春节快乐', detail: '大肥鱼给你拜年啦~', month: '正月', day: 1, anim: '写福字' },
182
+ { id: 'lunar-lantern', calendar: 'lunar', label: '元宵节', greeting: '元宵节快乐', detail: '记得吃碗热乎乎的汤圆~', month: '正月', day: 15, anim: '吃汤圆' },
183
+ { id: 'solar-labor', calendar: 'solar', label: '劳动节', greeting: '劳动节快乐', detail: '今天也要好好休息一下~', month: 5, day: 1, anim: '轻快记录' },
184
+ { id: 'solar-childrens', calendar: 'solar', label: '儿童节', greeting: '儿童节快乐', detail: '今天可以多一点开心和胡闹~', month: 6, day: 1, anim: '荡秋千' },
185
+ { id: 'lunar-dragon-boat', calendar: 'lunar', label: '端午节', greeting: '端午安康', detail: '记得吃粽子、挂香囊~', month: '五月', day: 5, anim: '吃粽子' },
186
+ { id: 'lunar-qixi', calendar: 'lunar', label: '七夕节', greeting: '七夕快乐', detail: '今天也要甜甜的~', month: '七月', day: 7, anim: '穿针乞巧' },
187
+ { id: 'lunar-mid-autumn', calendar: 'lunar', label: '中秋节', greeting: '中秋快乐', detail: '一起赏月吃月饼吧~', month: '八月', day: 15, anim: '中秋赏月吃月饼', gif: 'zhongqiu-shangyue-chi-yuebing' },
188
+ { id: 'lunar-double-ninth', calendar: 'lunar', label: '重阳节', greeting: '重阳节快乐', detail: '记得登高赏菊~', month: '九月', day: 9, anim: '插茱萸赏菊' },
189
+ { id: 'lunar-laba', calendar: 'lunar', label: '腊八节', greeting: '腊八节快乐', detail: '喝一碗热腊八粥暖暖身~', month: '腊月', day: 8, anim: '吃腊八粥' },
190
+ { id: 'solar-national', calendar: 'solar', label: '国庆节', greeting: '国庆节快乐', detail: '一起热热闹闹庆祝一下~', month: 10, day: 1, anim: '放烟花' },
191
+ { id: 'solar-christmas', calendar: 'solar', label: '圣诞节', greeting: '圣诞快乐', detail: '给你送上节日礼物~', month: 12, day: 25, anim: '装点圣诞树' },
192
+ ]
193
+
194
+ function getSolarDateKey(date = new Date()) {
195
+ return `${date.getMonth() + 1}-${date.getDate()}`
196
+ }
197
+
198
+ function getFestivalAutoPlayDateKey(date = new Date()) {
199
+ return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
200
+ }
201
+
202
+ function parseLunarNumber(value) {
203
+ const text = String(value || '').replace(/[年月日\s]/g, '').replace(/^初/, '')
204
+ if (!text) return 0
205
+ if (/^\d+$/.test(text)) return Number(text)
206
+ if (text === '正') return 1
207
+ if (text === '冬') return 11
208
+ if (text === '腊') return 12
209
+ const digits = { 一: 1, 二: 2, 两: 2, 三: 3, 四: 4, 五: 5, 六: 6, 七: 7, 八: 8, 九: 9 }
210
+ if (text.startsWith('廿')) return 20 + (digits[text.slice(1)] || 0)
211
+ if (text.startsWith('卅')) return 30 + (digits[text.slice(1)] || 0)
212
+ const tenIndex = text.indexOf('十')
213
+ if (tenIndex >= 0) {
214
+ const tens = tenIndex === 0 ? 1 : (digits[text.slice(0, tenIndex)] || 0)
215
+ const ones = digits[text.slice(tenIndex + 1)] || 0
216
+ return tens * 10 + ones
217
+ }
218
+ return digits[text] || 0
219
+ }
220
+
221
+ function normalizeLunarMonth(value) {
222
+ const raw = String(value || '').trim()
223
+ const leap = raw.startsWith('闰')
224
+ const text = leap ? raw.slice(1) : raw
225
+ const number = parseLunarNumber(text)
226
+ const name = LUNAR_MONTH_NAMES[number - 1] || text
227
+ return leap ? `闰${name}` : name
228
+ }
229
+
230
+ function getLunarDateParts(date = new Date()) {
231
+ const parts = {}
232
+ for (const part of LUNAR_DATE_FORMAT.formatToParts(date)) {
233
+ if (part.type !== 'literal') parts[part.type] = part.value
234
+ }
235
+ return {
236
+ month: normalizeLunarMonth(parts.month || ''),
237
+ day: parseLunarNumber(parts.day || 0),
238
+ dayText: parts.day || '',
239
+ }
240
+ }
241
+
242
+ function isLunarNewYearsEve(date = new Date()) {
243
+ const today = getLunarDateParts(date)
244
+ if (today.month !== '腊月') return false
245
+ const tomorrow = new Date(date)
246
+ tomorrow.setDate(tomorrow.getDate() + 1)
247
+ const next = getLunarDateParts(tomorrow)
248
+ return next.month === '正月' && next.day === 1
249
+ }
250
+
251
+ function getFestivalMatches(date = new Date()) {
252
+ const matches = []
253
+ const solarKey = getSolarDateKey(date)
254
+ const lunar = getLunarDateParts(date)
255
+ for (const festival of FESTIVAL_DEFS) {
256
+ if (festival.calendar === 'solar') {
257
+ if (solarKey === `${festival.month}-${festival.day}`) matches.push(festival)
258
+ continue
259
+ }
260
+ if (normalizeLunarMonth(festival.month) === lunar.month && festival.day === lunar.day) matches.push(festival)
261
+ }
262
+ if (isLunarNewYearsEve(date)) {
263
+ matches.unshift({
264
+ id: 'lunar-new-years-eve',
265
+ calendar: 'lunar',
266
+ label: '除夕',
267
+ greeting: '除夕快乐',
268
+ detail: '今晚一起守岁吧~',
269
+ month: '腊月',
270
+ day: 'eve',
271
+ anim: '放烟花',
272
+ })
273
+ }
274
+ return matches
275
+ }
276
+
277
+ function getFestivalById(id) {
278
+ return getFestivalMatches().find((festival) => festival.id === id) || null
279
+ }
280
+
281
+ function getFestivalAssetUrl(name) {
282
+ return new URL(encodeURIComponent(name) + '.gif', FESTIVAL_GIF_BASE).href
283
+ }
284
+
285
+ // ---------- DOM ----------
286
+ const rootEl = document.getElementById('pet-root')
287
+ const stageEl = document.getElementById('pet-stage')
288
+ const videoA = document.querySelectorAll('video')[0]
289
+ const videoB = document.querySelectorAll('video')[1]
290
+ const hitEl = document.getElementById('pet-hit')
291
+ const bubbleEl = document.getElementById('bubble')
292
+ const bubbleTitle = document.getElementById('bubble-title')
293
+ const bubbleDetail = document.getElementById('bubble-detail')
294
+ const menuEl = document.getElementById('menu')
295
+ const settingsPanel = document.getElementById('settings-panel')
296
+ const chatPanel = document.getElementById('chat-panel')
297
+ const festivalImage = document.createElement('img')
298
+ const festivalVideo = document.createElement('video')
299
+
300
+ for (const el of [festivalImage, festivalVideo]) {
301
+ el.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;object-fit:contain;pointer-events:none;opacity:0;transition:opacity .18s ease;z-index:2'
302
+ el.setAttribute('aria-hidden', 'true')
303
+ el.draggable = false
304
+ }
305
+ festivalVideo.muted = true
306
+ festivalVideo.playsInline = true
307
+ festivalVideo.autoplay = true
308
+ festivalVideo.loop = false
309
+ festivalVideo.preload = 'auto'
310
+ stageEl.append(festivalImage, festivalVideo)
311
+
312
+ // ---------- 基础尺寸 ----------
313
+ let size = (CONFIG.petSize || 460) * CONFIG.scale
314
+ let halfW = size / 2
315
+ let halfH = size * 9 / 16 / 2
316
+ let bottomPad = (size * 9 / 16 * (CANVAS_H - FEET_Y)) / CANVAS_H
317
+ function applySize() {
318
+ size = (CONFIG.petSize || 460) * CONFIG.scale
319
+ halfW = size / 2
320
+ halfH = size * 9 / 16 / 2
321
+ bottomPad = (size * 9 / 16 * (CANVAS_H - FEET_Y)) / CANVAS_H
322
+ stageEl.style.width = size + 'px'
323
+ stageEl.style.height = (size * 9 / 16) + 'px'
324
+ stageEl.style.transform = `translateY(${bottomPad}px)`
325
+ // 尺寸变化后把位置夹回屏幕内。
326
+ petPos.x = Math.min(Math.max(petPos.x, -(HIT_BOX.x0 / 640 * size)), window.innerWidth - (HIT_BOX.x1 / 640 * size))
327
+ petPos.y = Math.min(Math.max(petPos.y, 0), window.innerHeight - size * 9 / 16)
328
+ applyPetPosition()
329
+ }
330
+ hitEl.style.left = (HIT_BOX.x0 / 640 * 100) + '%'
331
+ hitEl.style.top = (HIT_BOX.y0 / 360 * 100) + '%'
332
+ hitEl.style.width = ((HIT_BOX.x1 - HIT_BOX.x0) / 640 * 100) + '%'
333
+ hitEl.style.height = ((HIT_BOX.y1 - HIT_BOX.y0) / 360 * 100) + '%'
334
+ if (CONFIG.reducedMotion) {
335
+ document.documentElement.style.setProperty('--pet-transition', 'none')
336
+ }
337
+
338
+ // 全屏透明画布内,宠物初始放在右下角;拖拽时只移动这个 DOM,不移动窗口。
339
+ let petPos = {
340
+ x: window.innerWidth - size - 24,
341
+ y: window.innerHeight - size * 9 / 16 - 24,
342
+ }
343
+ function applyPetPosition() {
344
+ rootEl.style.left = petPos.x + 'px'
345
+ rootEl.style.top = petPos.y + 'px'
346
+ rootEl.style.right = 'auto'
347
+ rootEl.style.bottom = 'auto'
348
+ rootEl.style.transform = 'none'
349
+ }
350
+ applyPetPosition()
351
+ applySize()
352
+
353
+ // ---------- 状态 ----------
354
+ let front = 0 // 0 = A, 1 = B
355
+ let pending = null
356
+ let gen = 0
357
+ let anim = IDLE
358
+ let animOnce = true
359
+ let animLoop = false
360
+ let currentMode = 'idle' // idle | state | click | drag | move | pulse
361
+ let currentState = 'IDLE'
362
+ let resumeState = 'IDLE'
363
+ let resumeMessage = ''
364
+ let resumeDetail = ''
365
+ let overlay = null
366
+ let overlayTimer = null
367
+ let lastPulseKey = null
368
+ let status = { state: 'IDLE', message: '', detail: '', project: '', task: '', progress: null }
369
+ let tasks = []
370
+ let dragging = false
371
+ let dragState = { active: false, dragging: false, sx: 0, sy: 0, offX: 0, offY: 0 }
372
+ let justDragged = false
373
+ let facing = 'left'
374
+ let lastMouse = { x: -1, y: -1 }
375
+ let tokenUsage = { inputTokens: 0, outputTokens: 0, totalTokens: 0 }
376
+ let balance = null
377
+ let roast = null
378
+ let lastRoast = null
379
+ let manualBubble = null
380
+ let manualBubbleTimer = null
381
+ let pomodoro = null
382
+ let pomodoroTimer = null
383
+ let menuPage = 'main'
384
+ let lastMenuPos = { x: 0, y: 0 }
385
+ let moveRef = null
386
+ let moveToken = 0
387
+ let movePlan = null
388
+ let actionOrderIndex = 0
389
+ let idleDelayTimer = null
390
+ // 情绪:mood -100~100(负=低落,正=开心),energy 0~100,anxiety 0~100,boredom 0~100
391
+ const EMOTION_STORAGE_KEY = 'better-dsh-pet:emotion'
392
+ let emotion = { mood: 0, energy: 100, anxiety: 0, boredom: 0 }
393
+ let wakeWordEnabled = false
394
+ let festivalPlayToken = 0
395
+ let festivalActive = false
396
+ let currentFestival = null
397
+ let festivalAutoPlayDone = false
398
+ let lastFestivalPlayToken = null
399
+ let festivalTimer = null
400
+ let settingsFestivalTimer = null
401
+ const FESTIVAL_GIF_DISPLAY_MS = 7000
402
+
403
+ // ---------- 工具 ----------
404
+ const randomBetween = (min, max) => Math.floor(min + Math.random() * (max - min))
405
+ const parseList = (text) => String(text || '').split(/[,,]/).map((s) => s.trim()).filter(Boolean)
406
+ const pick = (pool, exclude) => {
407
+ const entries = exclude ? pool.filter((n) => n !== exclude) : pool
408
+ return entries[Math.floor(Math.random() * entries.length)]
409
+ }
410
+
411
+ const clamp = (value, min, max) => Math.min(max, Math.max(min, value))
412
+
413
+ function loadEmotion() {
414
+ try {
415
+ const raw = localStorage.getItem(EMOTION_STORAGE_KEY)
416
+ if (!raw) return
417
+ const data = JSON.parse(raw)
418
+ const num = (value, fallback) => {
419
+ const n = Number(value)
420
+ return Number.isFinite(n) ? n : fallback
421
+ }
422
+ emotion = {
423
+ mood: clamp(num(data.mood, 0), -100, 100),
424
+ energy: clamp(num(data.energy, 100), 0, 100),
425
+ anxiety: clamp(num(data.anxiety, 0), 0, 100),
426
+ boredom: clamp(num(data.boredom, 0), 0, 100),
427
+ }
428
+ } catch {
429
+ // 读取失败时保持默认情绪。
430
+ }
431
+ }
432
+
433
+ function saveEmotion() {
434
+ try {
435
+ localStorage.setItem(EMOTION_STORAGE_KEY, JSON.stringify(emotion))
436
+ } catch {
437
+ // 存储不可用时静默忽略。
438
+ }
439
+ }
440
+
441
+ function updateEmotion(delta) {
442
+ emotion.mood = clamp(emotion.mood + (delta.mood ?? 0), -100, 100)
443
+ emotion.energy = clamp(emotion.energy + (delta.energy ?? 0), 0, 100)
444
+ emotion.anxiety = clamp(emotion.anxiety + (delta.anxiety ?? 0), 0, 100)
445
+ emotion.boredom = clamp(emotion.boredom + (delta.boredom ?? 0), 0, 100)
446
+ saveEmotion()
447
+ }
448
+
449
+ function dominantEmotion() {
450
+ if (emotion.energy < 25) return 'tired'
451
+ if (emotion.anxiety >= 60) return 'anxious'
452
+ if (emotion.boredom >= 60) return 'bored'
453
+ if (emotion.mood >= 50) return 'happy'
454
+ return 'calm'
455
+ }
456
+
457
+ function applyStateEmotion(state) {
458
+ const key = `state${state}`
459
+ const delta = EMOTION_DELTAS[key]
460
+ if (delta) updateEmotion(delta)
461
+ }
462
+
463
+ function applyInteractionEmotion(kind) {
464
+ const delta = EMOTION_DELTAS[kind]
465
+ if (delta) updateEmotion(delta)
466
+ }
467
+
468
+ function pickEmotionAction(usableActions, exclude) {
469
+ const dominant = dominantEmotion()
470
+ const pool = EMOTION_ACTION_POOLS[dominant]
471
+ if (dominant !== 'calm' && pool && pool.length && Math.random() < 0.5) {
472
+ const candidate = pick(pool, exclude)
473
+ if (candidate && (usableActions.includes(candidate) || CONFIG.enabledActions.length === 0)) {
474
+ return candidate
475
+ }
476
+ }
477
+ return pick(usableActions, exclude)
478
+ }
479
+
480
+ function emotionBubbleIfAny() {
481
+ const dominant = dominantEmotion()
482
+ if (dominant === 'calm') return null
483
+ const texts = EMOTION_BUBBLES[dominant]
484
+ if (!texts || !texts.length || Math.random() >= 0.35) return null
485
+ return pick(texts)
486
+ }
487
+
488
+ function assetUrl(name) {
489
+ return new URL(encodeURIComponent(name) + '.webm', ASSET_BASE).href
490
+ }
491
+
492
+ function stopFestivalPlayback() {
493
+ festivalPlayToken++
494
+ festivalActive = false
495
+ currentFestival = null
496
+ if (festivalTimer) {
497
+ clearTimeout(festivalTimer)
498
+ festivalTimer = null
499
+ }
500
+ festivalImage.classList.remove('is-front')
501
+ festivalVideo.classList.remove('is-front')
502
+ festivalImage.style.opacity = '0'
503
+ festivalVideo.style.opacity = '0'
504
+ festivalVideo.onended = null
505
+ festivalVideo.pause()
506
+ festivalVideo.removeAttribute('src')
507
+ festivalVideo.load()
508
+ festivalImage.removeAttribute('src')
509
+ }
510
+
511
+ function startFestivalPlayback(festival) {
512
+ if (!festival) return false
513
+ const token = ++festivalPlayToken
514
+ festivalActive = true
515
+ currentFestival = festival
516
+ // 统一使用 WebM 动画播放节日祝福(包内不包含 GIF 资源,避免左上角裂图)
517
+ festivalImage.removeAttribute('src')
518
+ festivalImage.style.opacity = '0'
519
+ festivalVideo.src = assetUrl(festival.anim || IDLE)
520
+ festivalVideo.loop = false
521
+ festivalVideo.playbackRate = CONFIG.playbackRate
522
+ festivalVideo.onended = () => {
523
+ if (festivalPlayToken !== token) return
524
+ festivalVideo.classList.remove('is-front')
525
+ festivalVideo.style.opacity = '0'
526
+ festivalVideo.onended = null
527
+ if (festivalActive && currentFestival?.id === festival.id) {
528
+ festivalActive = false
529
+ currentFestival = null
530
+ if (currentMode === 'idle') playIdle()
531
+ else applyResume()
532
+ }
533
+ }
534
+ festivalVideo.classList.add('is-front')
535
+ festivalVideo.style.opacity = '1'
536
+ festivalVideo.load()
537
+ festivalVideo.play().catch(() => {})
538
+ return true
539
+ }
540
+
541
+ function playFestivalGreeting(festival) {
542
+ if (!festival || !CONFIG.holidayEnabled) return false
543
+ stopFestivalPlayback()
544
+ clearIdleDelay()
545
+ stopMove()
546
+ // 直接复用宠物主视频播放节日动画,替换当前画面,而不是在宠物上方叠加
547
+ currentMode = 'festival'
548
+ anim = festival.anim || IDLE
549
+ animOnce = true
550
+ animLoop = false
551
+ switchTo(anim, { once: true })
552
+ const title = festival.greeting || festival.label || '节日快乐'
553
+ const detail = festival.detail || '大肥鱼给你送上祝福~'
554
+ showManualBubble(title, detail, 5000)
555
+ festivalAutoPlayDone = true
556
+ return true
557
+ }
558
+
559
+ function getTodayFestival(date = new Date()) {
560
+ return getFestivalMatches(date).at(0) || null
561
+ }
562
+
563
+ function getActiveFestival() {
564
+ return CONFIG.holidayEnabled ? getTodayFestival() : null
565
+ }
566
+
567
+ function syncFestivalAutoPlay() {
568
+ const festival = getTodayFestival()
569
+ if (!festival) {
570
+ festivalAutoPlayDone = false
571
+ return null
572
+ }
573
+ // 每次启动只自动播放一次:首次由 maybeAutoPlayFestival 播放并置 true,
574
+ // 之后的状态轮询不会重置该标记,避免动画不断从头重播。
575
+ return festival
576
+ }
577
+
578
+ function maybeAutoPlayFestival() {
579
+ if (!CONFIG.holidayEnabled) return false
580
+ const festival = syncFestivalAutoPlay()
581
+ if (!festival || festivalAutoPlayDone || festivalActive) return false
582
+ return playFestivalGreeting(festival, { auto: true })
583
+ }
584
+
585
+ // ---------- 视频切换 ----------
586
+ function currentVideo() {
587
+ return front === 0 ? videoA : videoB
588
+ }
589
+
590
+ function otherVideo() {
591
+ return front === 0 ? videoB : videoA
592
+ }
593
+
594
+ function switchTo(next, { once = true, loop = false } = {}) {
595
+ if (pending && pending.anim === next && pending.once === once && pending.loop === loop) return
596
+ const currentGen = ++gen
597
+ pending = { anim: next, once, loop, gen: currentGen }
598
+ const target = otherVideo()
599
+ const el = target
600
+ const old = currentVideo()
601
+ // 旧视频可能还没播完就被切走:清掉它的 ended 回调,避免稍后触发
602
+ // handleEnded 打断当前正在播放的新动画。
603
+ if (old && old !== el) old.onended = null
604
+ el.src = assetUrl(next)
605
+ el.loop = loop
606
+ el.muted = true
607
+ el.autoplay = true
608
+ el.playsInline = true
609
+ el.playbackRate = CONFIG.playbackRate
610
+ el.onended = loop ? null : () => handleEnded()
611
+ el.load()
612
+ const onReady = () => {
613
+ el.removeEventListener('loadeddata', onReady)
614
+ if (pending?.gen !== currentGen) return
615
+ el.classList.add('is-front')
616
+ if (old !== el) {
617
+ old.classList.remove('is-front')
618
+ old.onended = null
619
+ }
620
+ front = front === 0 ? 1 : 0
621
+ pending = null
622
+ el.style.transform = facing === 'right' ? 'scaleX(-1)' : ''
623
+ el.play().catch(() => {})
624
+ // 走动动画加载完成后,用真实视频时长驱动移动。
625
+ if (currentMode === 'move' && movePlan) startMoveDrive()
626
+ }
627
+ el.addEventListener('loadeddata', onReady)
628
+ if (el.readyState >= 2) onReady()
629
+ }
630
+
631
+ // ---------- 播放控制 ----------
632
+ function playIdle() {
633
+ clearIdleDelay()
634
+ stopMove()
635
+ currentMode = 'idle'
636
+ // 自定义动作池:设置了 enabledActions 时只从这些动作里选。
637
+ const actionPool = CONFIG.enabledActions.length > 0
638
+ ? ACTS.filter((name) => CONFIG.enabledActions.includes(name))
639
+ : ACTS
640
+ const usableActions = actionPool.length > 0 ? actionPool : ACTS
641
+ // 自定义播放顺序:非空时按顺序循环播放。
642
+ const order = CONFIG.actionOrder.length > 0
643
+ ? CONFIG.actionOrder.filter((name) => ACTS.includes(name) || MOVES.includes(name) || name === TURN)
644
+ : []
645
+ let next = IDLE
646
+ let isMove = false
647
+ const canMove = CONFIG.walkEnabled && !CONFIG.reducedMotion
648
+ if (order.length > 0) {
649
+ next = order[actionOrderIndex % order.length]
650
+ actionOrderIndex++
651
+ if (MOVES.includes(next)) {
652
+ if (canMove && tryMove(next)) isMove = true
653
+ else next = IDLE
654
+ }
655
+ } else {
656
+ // 移动频繁度 = 每次待机决策时尝试走动的概率(可关闭)。
657
+ // 活跃程度会缩放这个概率:quiet 更低,lively 更高。
658
+ const activity = CONFIG.activityLevel === 'quiet' ? 0.6 : CONFIG.activityLevel === 'lively' ? 1.4 : 1
659
+ const effectiveMoveChance = Math.min(100, CONFIG.moveChance * activity)
660
+ const moveCandidate = pick(MOVES, anim)
661
+ if (canMove && Math.random() * 100 < effectiveMoveChance && tryMove(moveCandidate)) {
662
+ next = moveCandidate
663
+ isMove = true
664
+ } else {
665
+ const roll = Math.random()
666
+ if (CONFIG.activityLevel === 'quiet') {
667
+ if (roll < 0.5) next = IDLE
668
+ else if (roll < 0.6) next = TURN
669
+ else next = pickEmotionAction(usableActions, anim)
670
+ } else if (CONFIG.activityLevel === 'lively') {
671
+ if (roll < 0.15) next = IDLE
672
+ else if (roll < 0.3) next = TURN
673
+ else next = pickEmotionAction(usableActions, anim)
674
+ } else {
675
+ if (roll < 0.3) next = IDLE
676
+ else if (roll < 0.4) next = TURN
677
+ else next = pickEmotionAction(usableActions, anim)
678
+ }
679
+ }
680
+ }
681
+ anim = next
682
+ animOnce = true
683
+ animLoop = false
684
+ if (isMove) currentMode = 'move'
685
+ switchTo(next, { once: true })
686
+ // 移动驱动在视频加载完成后启动(switchTo onReady 里调用),
687
+ // 这样可以使用视频真实时长,避免动画还没播完就提前停下。
688
+ // 随机动作/走动播放时,给出与动作匹配的可爱气泡描述;情绪强烈时优先说情绪台词。
689
+ if (next !== IDLE) {
690
+ const emotionCopy = emotionBubbleIfAny()
691
+ const copy = emotionCopy || ACTION_COPY[next] || `大肥鱼正在${next}~`
692
+ showManualBubble(copy, emotionCopy ? '大肥鱼的心情~' : '大肥鱼的小剧场~', 4200)
693
+ }
694
+ }
695
+
696
+ function playState(state, { pulse = false } = {}) {
697
+ clearIdleDelay()
698
+ stopMove()
699
+ currentMode = pulse ? 'pulse' : 'state'
700
+ const pool = STATE_ANIMS[state] || STATE_ANIMS.IDLE
701
+ const next = state === 'IDLE' ? IDLE : pick(pool, anim)
702
+ anim = next
703
+ // 非空闲状态动画循环播放,避免播完一帧后停在原地;空闲状态仍走随机动画链。
704
+ animLoop = !pulse && state !== 'IDLE'
705
+ animOnce = !animLoop
706
+ switchTo(next, { once: !animLoop, loop: animLoop })
707
+ }
708
+
709
+ function playClick() {
710
+ clearIdleDelay()
711
+ stopMove()
712
+ currentMode = 'click'
713
+ applyInteractionEmotion('click')
714
+ const next = pick(CLICKS, anim)
715
+ anim = next
716
+ animOnce = true
717
+ animLoop = false
718
+ switchTo(next, { once: true })
719
+ showManualBubble(CLICK_COPY[next] || '大肥鱼被戳了一下~', '大肥鱼的小剧场~', 2500)
720
+ }
721
+
722
+ function playDrag() {
723
+ clearIdleDelay()
724
+ stopMove()
725
+ currentMode = 'drag'
726
+ anim = DRAG
727
+ animOnce = false
728
+ animLoop = true
729
+ // 拖拽可能持续超过单段动画时长,必须循环播放,否则松手前会定格在最后一帧。
730
+ switchTo(DRAG, { loop: true })
731
+ }
732
+
733
+ // ---------- 走动效果 ----------
734
+ function tryMove(moveName) {
735
+ if (moveRef !== null || movePlan) return false
736
+ const W = window.innerWidth
737
+ const H = window.innerHeight
738
+ const minX = -(HIT_BOX.x0 / 640 * size)
739
+ const maxX = W - (HIT_BOX.x1 / 640 * size)
740
+ const minY = 0
741
+ const maxY = H - size * 9 / 16
742
+
743
+ // “原地漂浮踏步”面朝观众,适合稍微向屏幕下方(朝用户)移动一点。
744
+ if (moveName === '原地漂浮踏步') {
745
+ const distance = randomBetween(40, 90)
746
+ const targetY = petPos.y + distance
747
+ if (targetY > maxY) return false
748
+ movePlan = { startX: petPos.x, targetX: petPos.x, startY: petPos.y, targetY }
749
+ return true
750
+ }
751
+
752
+ const dir = Math.random() < 0.5 ? -1 : 1
753
+ const distance = randomBetween(200, 450)
754
+ const targetX = petPos.x + dir * distance
755
+ if (targetX < minX || targetX > maxX) return false
756
+ // 让角色面朝移动方向,避免“向左跑却镜像成向右”的错乱。
757
+ facing = dir > 0 ? 'right' : 'left'
758
+ movePlan = { startX: petPos.x, targetX, startY: petPos.y, targetY: petPos.y }
759
+ return true
760
+ }
761
+
762
+ function startMoveDrive() {
763
+ if (!movePlan) return
764
+ const plan = movePlan
765
+ const el = currentVideo()
766
+ const duration = Number.isFinite(el?.duration) && el.duration > 0 ? el.duration : 9
767
+ // 每个动作的“开头不动/结尾不动”时长不同,按动作单独配置。
768
+ const timing = MOVE_TIMING[anim] || { lead: 1.5, tail: 2 }
769
+ const lead = timing.lead
770
+ const tail = timing.tail
771
+ const travelWindow = Math.max(0.1, duration - lead - tail)
772
+ const token = ++moveToken
773
+ const step = () => {
774
+ if (moveToken !== token || !movePlan) return
775
+ const t = el.currentTime || 0
776
+ let x = plan.startX
777
+ let y = plan.startY ?? petPos.y
778
+ if (t > lead && t < duration - tail) {
779
+ const progress = Math.min(1, Math.max(0, (t - lead) / travelWindow))
780
+ x = plan.startX + (plan.targetX - plan.startX) * progress
781
+ y = (plan.startY ?? petPos.y) + ((plan.targetY ?? petPos.y) - (plan.startY ?? petPos.y)) * progress
782
+ } else if (t >= duration - tail) {
783
+ x = plan.targetX
784
+ y = plan.targetY ?? petPos.y
785
+ }
786
+ petPos.x = x
787
+ petPos.y = y
788
+ applyPetPosition()
789
+ if (t < duration - tail) {
790
+ moveRef = requestAnimationFrame(step)
791
+ } else {
792
+ moveRef = null
793
+ movePlan = null
794
+ }
795
+ }
796
+ moveRef = requestAnimationFrame(step)
797
+ }
798
+
799
+ function stopMove() {
800
+ movePlan = null
801
+ moveToken++
802
+ if (moveRef !== null) {
803
+ cancelAnimationFrame(moveRef)
804
+ moveRef = null
805
+ }
806
+ }
807
+
808
+ function clearIdleDelay() {
809
+ if (idleDelayTimer) {
810
+ clearTimeout(idleDelayTimer)
811
+ idleDelayTimer = null
812
+ }
813
+ }
814
+
815
+ function scheduleNextIdle() {
816
+ clearIdleDelay()
817
+ if (CONFIG.actionDelayMs > 0) {
818
+ // 等待“动作切换间隔”时不要定格在上一动作的最后一帧:
819
+ // 先播放循环待机呼吸,等间隔结束再进入下一个随机/自定义动作。
820
+ currentMode = 'idle'
821
+ anim = IDLE
822
+ animOnce = false
823
+ animLoop = true
824
+ switchTo(IDLE, { loop: true })
825
+ // 让“动作间隔”肉眼可见:等待期间显示一个小气泡。
826
+ showManualBubble('休息一下~', `间隔 ${CONFIG.actionDelayMs}ms`, Math.min(CONFIG.actionDelayMs, 3000))
827
+ idleDelayTimer = setTimeout(() => {
828
+ idleDelayTimer = null
829
+ playIdle()
830
+ }, CONFIG.actionDelayMs)
831
+ } else {
832
+ playIdle()
833
+ }
834
+ }
835
+
836
+ function handleEnded() {
837
+ if (dragging || dragState.active) return
838
+ if (overlay && overlay.state) {
839
+ // 脉冲动画播完但 TTL 未结束:气泡保留,动画先回到 resume 状态。
840
+ if (!overlay.animationDone) {
841
+ overlay.animationDone = true
842
+ applyResume()
843
+ }
844
+ return
845
+ }
846
+ if (currentMode === 'festival') {
847
+ festivalActive = false
848
+ currentFestival = null
849
+ scheduleNextIdle()
850
+ updateBubble()
851
+ return
852
+ }
853
+ if (currentMode === 'click') {
854
+ applyResume()
855
+ return
856
+ }
857
+ if (currentMode === 'move') {
858
+ stopMove()
859
+ scheduleNextIdle()
860
+ return
861
+ }
862
+ if (currentMode === 'state') {
863
+ const state = overlay ? overlay.state : currentState
864
+ if (state && state !== 'IDLE') {
865
+ playState(state)
866
+ return
867
+ }
868
+ scheduleNextIdle()
869
+ return
870
+ }
871
+ if (anim === TURN) {
872
+ facing = facing === 'left' ? 'right' : 'left'
873
+ }
874
+ scheduleNextIdle()
875
+ }
876
+
877
+ function applyResume() {
878
+ const state = resumeState || currentState || 'IDLE'
879
+ currentState = state
880
+ // 强制清掉可能卡住的切换状态,确保拖拽结束后一定切回正常动画。
881
+ pending = null
882
+ if (state === 'IDLE') {
883
+ // 任务刚结束/拖拽结束后先回到纯待机,避免随机链立刻播放“思考类”动画。
884
+ status = {
885
+ ...status,
886
+ state: 'IDLE',
887
+ message: resumeMessage || '大肥鱼在这儿等新任务哦~',
888
+ detail: resumeDetail || '大肥鱼 · 等待下一次任务',
889
+ }
890
+ currentMode = 'idle'
891
+ anim = IDLE
892
+ animOnce = true
893
+ animLoop = false
894
+ switchTo(IDLE, { once: true })
895
+ } else {
896
+ status = {
897
+ ...status,
898
+ state,
899
+ message: resumeMessage || status.message,
900
+ detail: resumeDetail || status.detail,
901
+ }
902
+ playState(state)
903
+ }
904
+ updateBubble()
905
+ }
906
+
907
+ function clearOverlay() {
908
+ if (overlayTimer) clearTimeout(overlayTimer)
909
+ overlayTimer = null
910
+ overlay = null
911
+ lastPulseKey = null
912
+ }
913
+
914
+ // ---------- 消息处理 ----------
915
+ function applyStateMessage(message) {
916
+ const state = message.state || 'IDLE'
917
+ status = {
918
+ state,
919
+ message: message.message || status.message,
920
+ detail: message.detail || status.detail,
921
+ project: message.project || status.project,
922
+ task: message.task || status.task,
923
+ progress: message.progress || status.progress,
924
+ }
925
+ currentState = state
926
+ resumeState = state
927
+ resumeMessage = message.message || ''
928
+ resumeDetail = message.detail || ''
929
+ clearOverlay()
930
+ applyStateEmotion(state)
931
+ if (state === 'IDLE') playIdle()
932
+ else playState(state)
933
+ updateBubble()
934
+ }
935
+
936
+ function applyPulseMessage(message) {
937
+ const state = message.state || 'SUCCESS'
938
+ resumeState = message.resumeState || currentState || 'IDLE'
939
+ resumeMessage = message.resumeMessage || ''
940
+ resumeDetail = message.resumeDetail || ''
941
+ overlay = {
942
+ state,
943
+ message: message.message || '',
944
+ detail: message.detail || '',
945
+ ttlMs: Number(message.ttlMs || 1800),
946
+ animationDone: false,
947
+ }
948
+ lastPulseKey = `${state}:${message.expiresAt || message.ttlMs || 1800}`
949
+ currentState = state
950
+ applyStateEmotion(state)
951
+ if (state === 'SUCCESS') {
952
+ window.petBridge.beep()
953
+ shakePet()
954
+ }
955
+ playState(state, { pulse: true })
956
+ if (overlayTimer) clearTimeout(overlayTimer)
957
+ overlayTimer = setTimeout(() => {
958
+ clearOverlay()
959
+ applyResume()
960
+ }, overlay.ttlMs)
961
+ updateBubble()
962
+ }
963
+
964
+ function applyTaskMessage(message) {
965
+ status.task = message.task || status.task
966
+ status.progress = message.progress || status.progress
967
+ status.project = message.project || status.project
968
+ status.message = message.message || status.message
969
+ status.detail = message.detail || status.detail
970
+ updateBubble()
971
+ }
972
+
973
+ function applyTasksMessage(message) {
974
+ tasks = Array.isArray(message.tasks) ? message.tasks : []
975
+ updateBubble()
976
+ }
977
+
978
+ // ---------- 喂食/互动反馈 ----------
979
+ function showManualBubble(message, detail, ttl = 2200) {
980
+ if (manualBubbleTimer) clearTimeout(manualBubbleTimer)
981
+ manualBubble = { message, detail, expiresAt: Date.now() + ttl }
982
+ manualBubbleTimer = setTimeout(() => {
983
+ manualBubble = null
984
+ manualBubbleTimer = null
985
+ updateBubble()
986
+ }, ttl)
987
+ updateBubble()
988
+ }
989
+
990
+ function feedPet() {
991
+ clearIdleDelay()
992
+ applyInteractionEmotion('feed')
993
+ const next = pick(EAT_ANIMS, anim)
994
+ anim = next
995
+ animOnce = true
996
+ animLoop = false
997
+ currentMode = 'click' // 复用“一次性动画播完回当前状态”的路径
998
+ switchTo(next, { once: true })
999
+ showManualBubble('谢谢投喂大肥鱼~', '吃饱了更有力气干活!', 2200)
1000
+ }
1001
+
1002
+ function shakePet() {
1003
+ if (CONFIG.reducedMotion) return
1004
+ const originX = petPos.x
1005
+ const originY = petPos.y
1006
+ const offsets = [[6, 0], [-6, 0], [4, 0], [-4, 0], [2, 0], [-2, 0], [0, 0]]
1007
+ let index = 0
1008
+ const timer = setInterval(() => {
1009
+ if (index >= offsets.length) {
1010
+ clearInterval(timer)
1011
+ applyPetPosition()
1012
+ return
1013
+ }
1014
+ const [dx, dy] = offsets[index++]
1015
+ rootEl.style.left = (originX + dx) + 'px'
1016
+ rootEl.style.top = (originY + dy) + 'px'
1017
+ }, 30)
1018
+ }
1019
+
1020
+ // ---------- 番茄钟 ----------
1021
+ function formatTime(ms) {
1022
+ const totalSeconds = Math.max(0, Math.ceil(ms / 1000))
1023
+ const minutes = Math.floor(totalSeconds / 60)
1024
+ const seconds = totalSeconds % 60
1025
+ return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`
1026
+ }
1027
+
1028
+ function playAlarm() {
1029
+ try {
1030
+ const audio = new Audio(ALARM_URL)
1031
+ audio.volume = 0.8
1032
+ audio.play().catch(() => {})
1033
+ } catch {
1034
+ // 音频不可用时静默失败
1035
+ }
1036
+ }
1037
+
1038
+ function startPomodoro(mode, minutes) {
1039
+ clearIdleDelay()
1040
+ stopPomodoro()
1041
+ const durationMs = Math.max(1, minutes) * 60 * 1000
1042
+ pomodoro = { mode, endAt: Date.now() + durationMs, durationMs }
1043
+ pomodoroTimer = setInterval(updatePomodoro, 1000)
1044
+ updateBubble()
1045
+ }
1046
+
1047
+ function stopPomodoro() {
1048
+ if (pomodoroTimer) clearInterval(pomodoroTimer)
1049
+ pomodoroTimer = null
1050
+ pomodoro = null
1051
+ updateBubble()
1052
+ }
1053
+
1054
+ function updatePomodoro() {
1055
+ if (!pomodoro) return
1056
+ const remaining = pomodoro.endAt - Date.now()
1057
+ if (remaining <= 0) {
1058
+ completePomodoro()
1059
+ return
1060
+ }
1061
+ updateBubble()
1062
+ }
1063
+
1064
+ function completePomodoro() {
1065
+ const mode = pomodoro?.mode || 'work'
1066
+ stopPomodoro()
1067
+ applyInteractionEmotion('pomodoro')
1068
+ playAlarm()
1069
+ shakePet()
1070
+ showManualBubble(
1071
+ mode === 'work' ? '🍅 大肥鱼番茄钟结束啦!' : '☕ 大肥鱼休息结束啦!',
1072
+ mode === 'work' ? '快休息一下,摸摸鱼~' : '继续加油,大肥鱼陪你!',
1073
+ 4000,
1074
+ )
1075
+ playClick()
1076
+ }
1077
+
1078
+ // ---------- 气泡 ----------
1079
+ function visibleState() {
1080
+ if (overlay) return overlay.state
1081
+ if (tasks.length >= 2) return status.state
1082
+ return status.state || 'IDLE'
1083
+ }
1084
+
1085
+ function updateBubble() {
1086
+ const state = visibleState()
1087
+ const manualActive = manualBubble && manualBubble.expiresAt > Date.now()
1088
+ const pomodoroActive = pomodoro && pomodoro.endAt > Date.now()
1089
+ const shouldShow = pomodoroActive || manualActive
1090
+ ? CONFIG.bubbleMode !== 'hidden'
1091
+ : CONFIG.bubbleMode === 'always'
1092
+ || (CONFIG.bubbleMode === 'custom' && CONFIG.bubbleStates.includes(state))
1093
+ || (CONFIG.bubbleMode === 'custom' && tasks.length >= 2 && tasks.some((t) => CONFIG.bubbleStates.includes(t.state)))
1094
+ if (CONFIG.bubbleMode === 'hidden' || !shouldShow) {
1095
+ bubbleEl.classList.remove('visible')
1096
+ bubbleEl.style.pointerEvents = 'none'
1097
+ return
1098
+ }
1099
+ let title = ''
1100
+ let detail = ''
1101
+ if (pomodoroActive) {
1102
+ const remaining = Math.max(0, pomodoro.endAt - Date.now())
1103
+ const label = pomodoro.mode === 'work' ? '🍅 番茄钟' : '☕ 休息'
1104
+ title = `${label} ${formatTime(remaining)}`
1105
+ detail = pomodoro.mode === 'work' ? '大肥鱼专注中,冲鸭~' : '大肥鱼摸鱼中,放松一下~'
1106
+ } else if (manualActive) {
1107
+ title = manualBubble.message
1108
+ detail = manualBubble.detail || ''
1109
+ } else if (tasks.length >= 2) {
1110
+ title = `${tasks.length} 个任务进行中`
1111
+ detail = tasks.slice(0, 3).map((t) => `${t.state || ''} · ${t.project || t.task || t.message || ''}`).join(';')
1112
+ } else if (overlay && overlay.message) {
1113
+ title = overlay.message
1114
+ detail = overlay.detail || status.detail || ''
1115
+ } else if (status.message) {
1116
+ title = status.message
1117
+ detail = status.detail || ''
1118
+ } else {
1119
+ title = '大肥鱼正在摸鱼中~'
1120
+ detail = ''
1121
+ }
1122
+ // 余额显示:优先展示 DeepSeek 账户余额,不再显示 Token。
1123
+ if (balance && balance.total !== undefined && balance.total !== null) {
1124
+ const symbol = balance.currency === 'CNY' ? '¥' : balance.currency === 'USD' ? '$' : `${balance.currency} `
1125
+ const balanceText = `余额 ${symbol}${balance.total}`
1126
+ detail = detail ? `${detail} · ${balanceText}` : balanceText
1127
+ }
1128
+ bubbleTitle.textContent = title
1129
+ bubbleDetail.textContent = detail
1130
+ bubbleEl.style.transform = `translateX(-50%) scale(${CONFIG.bubbleScale})`
1131
+ bubbleEl.style.pointerEvents = 'auto'
1132
+ bubbleEl.classList.add('visible')
1133
+ }
1134
+
1135
+ // ---------- 交互 ----------
1136
+ const DRAG_THRESHOLD = 5
1137
+
1138
+ // 让透明窗口只在宠物/菜单区域接收鼠标,其余区域点击穿透到下层应用。
1139
+ function updateClickThrough() {
1140
+ const rect = hitEl.getBoundingClientRect()
1141
+ let inside = lastMouse.x >= rect.left && lastMouse.x <= rect.right
1142
+ && lastMouse.y >= rect.top && lastMouse.y <= rect.bottom
1143
+ // 气泡可见时也允许点击(用于点击刷新余额)。
1144
+ if (bubbleEl.classList.contains('visible')) {
1145
+ const b = bubbleEl.getBoundingClientRect()
1146
+ inside = inside || (lastMouse.x >= b.left && lastMouse.x <= b.right
1147
+ && lastMouse.y >= b.top && lastMouse.y <= b.bottom)
1148
+ }
1149
+ const overlayVisible = menuEl.classList.contains('visible')
1150
+ || settingsPanel.classList.contains('visible')
1151
+ || chatPanel.classList.contains('visible')
1152
+ const ignore = !inside && !dragging && !dragState.active && !overlayVisible
1153
+ window.petBridge.setIgnoreMouse(ignore)
1154
+ }
1155
+
1156
+ document.addEventListener('mousemove', (e) => {
1157
+ lastMouse = { x: e.clientX, y: e.clientY }
1158
+ updateClickThrough()
1159
+ })
1160
+
1161
+ function startDrag(e) {
1162
+ clearIdleDelay()
1163
+ stopMove()
1164
+ e.currentTarget.classList.add('dragging')
1165
+ try { e.currentTarget.setPointerCapture(e.pointerId) } catch { /* 忽略捕获失败 */ }
1166
+ dragState = {
1167
+ active: true,
1168
+ dragging: false,
1169
+ pointerId: e.pointerId,
1170
+ sx: e.screenX,
1171
+ sy: e.screenY,
1172
+ lastX: e.screenX,
1173
+ lastY: e.screenY,
1174
+ }
1175
+ window.petBridge.setIgnoreMouse(false)
1176
+ }
1177
+
1178
+ function moveDrag(e) {
1179
+ const d = dragState
1180
+ if (!d.active) return
1181
+ const totalDx = e.screenX - d.sx
1182
+ const totalDy = e.screenY - d.sy
1183
+ if (!d.dragging) {
1184
+ if (Math.hypot(totalDx, totalDy) < DRAG_THRESHOLD) return
1185
+ d.dragging = true
1186
+ dragging = true
1187
+ playDrag()
1188
+ showManualBubble('大肥鱼被拎起来啦!', '快放我下来~', 3000)
1189
+ }
1190
+ // 在全屏透明画布内移动宠物 DOM,避免移动窗口导致的指针事件问题。
1191
+ const dx = e.movementX || 0
1192
+ const dy = e.movementY || 0
1193
+ if (dx || dy) {
1194
+ // 按角色实际命中区域贴边,而不是按整个透明舞台贴边,
1195
+ // 这样宠物可以真正拖到屏幕最左/最右。
1196
+ const hitLeft = HIT_BOX.x0 / 640 * size
1197
+ const hitRight = HIT_BOX.x1 / 640 * size
1198
+ const minX = -hitLeft
1199
+ const maxX = window.innerWidth - hitRight
1200
+ petPos.x = Math.min(Math.max(petPos.x + dx, minX), maxX)
1201
+ petPos.y = Math.min(Math.max(petPos.y + dy, 0), window.innerHeight - size * 9 / 16)
1202
+ applyPetPosition()
1203
+ }
1204
+ }
1205
+
1206
+ function endDrag(e) {
1207
+ const d = dragState
1208
+ if (!d.active) return
1209
+ const wasDragging = d.dragging
1210
+ dragState = { active: false, dragging: false, sx: 0, sy: 0, lastX: 0, lastY: 0 }
1211
+ dragging = false
1212
+ window.petBridge.endDrag()
1213
+ if (e.currentTarget && e.currentTarget.classList) {
1214
+ e.currentTarget.classList.remove('dragging')
1215
+ } else {
1216
+ hitEl.classList.remove('dragging')
1217
+ }
1218
+ if (wasDragging) {
1219
+ justDragged = true
1220
+ setTimeout(() => { justDragged = false }, 100)
1221
+ applyResume()
1222
+ showManualBubble('终于放我下来啦~', '', 2000)
1223
+ }
1224
+ updateClickThrough()
1225
+ }
1226
+
1227
+ hitEl.addEventListener('pointerdown', startDrag)
1228
+ hitEl.addEventListener('pointermove', moveDrag)
1229
+ // 即使 pointerup 因为窗口移动没有落在宠物元素上,也要保证拖拽状态被重置。
1230
+ window.addEventListener('pointerup', endDrag)
1231
+ window.addEventListener('pointercancel', endDrag)
1232
+ hitEl.addEventListener('lostpointercapture', endDrag)
1233
+
1234
+ hitEl.addEventListener('click', (e) => {
1235
+ if (dragState.active || dragging || justDragged) return
1236
+ playClick()
1237
+ })
1238
+
1239
+ hitEl.addEventListener('contextmenu', (e) => {
1240
+ e.preventDefault()
1241
+ showMenu(e.clientX, e.clientY)
1242
+ })
1243
+
1244
+ // 点击余额气泡可手动刷新余额。
1245
+ bubbleEl.addEventListener('click', (e) => {
1246
+ e.stopPropagation()
1247
+ window.petBridge.refreshBalance()
1248
+ showManualBubble('余额刷新中~', '', 1500)
1249
+ })
1250
+
1251
+ function addMenuButton(label, onClick) {
1252
+ const button = document.createElement('button')
1253
+ button.textContent = label
1254
+ button.addEventListener('click', onClick)
1255
+ menuEl.appendChild(button)
1256
+ return button
1257
+ }
1258
+
1259
+ function showMenu(x, y) {
1260
+ clearIdleDelay()
1261
+ lastMenuPos = { x, y }
1262
+ menuEl.innerHTML = ''
1263
+ if (menuPage === 'pomodoro') {
1264
+ renderPomodoroSettings()
1265
+ } else if (menuPage === 'actions') {
1266
+ renderActionSettings()
1267
+ } else if (menuPage === 'appearance') {
1268
+ renderAppearanceSettings()
1269
+ } else if (menuPage === 'settings') {
1270
+ renderSettingsPage()
1271
+ } else if (menuPage === 'features') {
1272
+ renderFeatureSettings()
1273
+ } else {
1274
+ renderMainMenu()
1275
+ }
1276
+ // 设置页内容多,允许菜单内滚动;主菜单保持不滚动。
1277
+ if (menuPage === 'settings') {
1278
+ menuEl.style.maxHeight = '80vh'
1279
+ menuEl.style.overflowY = 'auto'
1280
+ } else {
1281
+ menuEl.style.maxHeight = 'none'
1282
+ menuEl.style.overflowY = 'visible'
1283
+ }
1284
+ menuEl.classList.add('visible')
1285
+ // 让菜单向右上方展开,避开宠物模型;再根据实际尺寸夹在屏幕内。
1286
+ const rect = menuEl.getBoundingClientRect()
1287
+ let left = x + 24
1288
+ let top = y - rect.height - 12
1289
+ left = Math.max(4, Math.min(left, window.innerWidth - rect.width - 4))
1290
+ top = Math.max(4, Math.min(top, window.innerHeight - rect.height - 4))
1291
+ menuEl.style.left = left + 'px'
1292
+ menuEl.style.top = top + 'px'
1293
+ window.petBridge.setIgnoreMouse(false)
1294
+ }
1295
+
1296
+ function renderEmotionBars(container) {
1297
+ const panel = document.createElement('div')
1298
+ panel.style.cssText = 'padding:8px 10px;background:#f7f8fa;border-radius:10px;margin-bottom:6px;display:grid;gap:4px'
1299
+ for (const meta of EMOTION_BAR_META) {
1300
+ const row = document.createElement('div')
1301
+ row.style.cssText = 'display:flex;align-items:center;gap:6px;font-size:11px'
1302
+ const label = document.createElement('span')
1303
+ label.textContent = meta.label
1304
+ label.style.cssText = 'width:28px;color:#555'
1305
+ const barWrap = document.createElement('div')
1306
+ barWrap.style.cssText = 'flex:1;height:8px;background:#e8e8e8;border-radius:4px;overflow:hidden'
1307
+ const bar = document.createElement('div')
1308
+ const raw = emotion[meta.key]
1309
+ const percent = meta.key === 'mood' ? (raw + 100) / 2 : raw
1310
+ bar.style.cssText = `width:${Math.max(0, Math.min(100, percent))}%;height:100%;background:${meta.color};transition:width .3s`
1311
+ barWrap.appendChild(bar)
1312
+ const value = document.createElement('span')
1313
+ value.textContent = meta.format(raw)
1314
+ value.style.cssText = 'width:34px;text-align:right;color:#333'
1315
+ row.append(label, barWrap, value)
1316
+ panel.appendChild(row)
1317
+ }
1318
+ container.appendChild(panel)
1319
+ }
1320
+
1321
+ function renderSettingsPanelContent() {
1322
+ const bubbleStatesText = Array.isArray(CONFIG.bubbleStates) ? CONFIG.bubbleStates.join(', ') : ''
1323
+ const todayFestival = getTodayFestival()
1324
+ const festivalButtonLabel = todayFestival ? `播放${todayFestival.label}` : '今日无节日'
1325
+ const festivalButtonDisabled = !todayFestival || !CONFIG.holidayEnabled
1326
+ settingsPanel.innerHTML = `
1327
+ <h2>🐳 Better DSH Pet 设置</h2>
1328
+ <div class="settings-section">
1329
+ <h3>情绪状态</h3>
1330
+ <div id="settings-emotion-bars"></div>
1331
+ </div>
1332
+ <div class="settings-section">
1333
+ <h3>外观与行为</h3>
1334
+ <div class="field"><label>宠物宽度</label><input type="number" id="set-petSize" min="100" max="1000" step="10" value="${CONFIG.petSize}"></div>
1335
+ <div class="field"><label>移动频繁度</label><input type="range" id="set-moveChance" min="0" max="100" step="1" value="${CONFIG.moveChance}"><span id="set-moveChance-val">${CONFIG.moveChance}%</span></div>
1336
+ <div class="field"><label>动作间隔</label><input type="range" id="set-actionDelayMs" min="0" max="5000" step="100" value="${CONFIG.actionDelayMs}"><span id="set-actionDelayMs-val">${CONFIG.actionDelayMs}ms</span></div>
1337
+ <div class="field"><label>播放速度</label><input type="range" id="set-playbackRate" min="1" max="2" step="0.1" value="${CONFIG.playbackRate}"><span id="set-playbackRate-val">${CONFIG.playbackRate}x</span></div>
1338
+ <div class="field"><label>活跃程度</label><select id="set-activityLevel">
1339
+ <option value="quiet" ${CONFIG.activityLevel === 'quiet' ? 'selected' : ''}>安静</option>
1340
+ <option value="normal" ${CONFIG.activityLevel === 'normal' ? 'selected' : ''}>标准</option>
1341
+ <option value="lively" ${CONFIG.activityLevel === 'lively' ? 'selected' : ''}>活泼</option>
1342
+ </select></div>
1343
+ <div class="field"><label>减少动态</label><span class="checkbox-field"><input type="checkbox" id="set-reducedMotion" ${CONFIG.reducedMotion ? 'checked' : ''}> 开启</span></div>
1344
+ <div class="field"><label>允许行走</label><span class="checkbox-field"><input type="checkbox" id="set-walkEnabled" ${CONFIG.walkEnabled ? 'checked' : ''}> 开启</span></div>
1345
+ </div>
1346
+ <div class="settings-section">
1347
+ <h3>番茄钟</h3>
1348
+ <div class="field"><label>工作时长</label><input type="number" id="set-workMinutes" min="1" max="120" step="1" value="${CONFIG.workMinutes}"></div>
1349
+ <div class="field"><label>休息时长</label><input type="number" id="set-breakMinutes" min="1" max="60" step="1" value="${CONFIG.breakMinutes}"></div>
1350
+ </div>
1351
+ <div class="settings-section">
1352
+ <h3>动作</h3>
1353
+ <div class="field"><label>待机动作</label><textarea id="set-enabledActions" placeholder="留空=全部动作,逗号分隔">${Array.isArray(CONFIG.enabledActions) ? CONFIG.enabledActions.join(', ') : ''}</textarea></div>
1354
+ <div class="field"><label>播放顺序</label><textarea id="set-actionOrder" placeholder="留空=随机,逗号分隔">${Array.isArray(CONFIG.actionOrder) ? CONFIG.actionOrder.join(', ') : ''}</textarea></div>
1355
+ </div>
1356
+ <div class="settings-section">
1357
+ <h3>功能</h3>
1358
+ <div class="field"><label>自动吐槽</label><span class="checkbox-field"><input type="checkbox" id="set-roastEnabled" ${CONFIG.roastEnabled ? 'checked' : ''}> 开启</span></div>
1359
+ <div class="field"><label>节日祝福</label><span class="checkbox-field"><input type="checkbox" id="set-holidayEnabled" ${CONFIG.holidayEnabled ? 'checked' : ''}> 开启</span></div>
1360
+ <div class="field"><label>气泡模式</label><select id="set-bubbleMode">
1361
+ <option value="always" ${CONFIG.bubbleMode === 'always' ? 'selected' : ''}>常驻显示</option>
1362
+ <option value="hidden" ${CONFIG.bubbleMode === 'hidden' ? 'selected' : ''}>完全隐藏</option>
1363
+ <option value="custom" ${CONFIG.bubbleMode === 'custom' ? 'selected' : ''}>自定义</option>
1364
+ </select></div>
1365
+ <div class="field"><label>自定义气泡状态</label><textarea id="set-bubbleStates" placeholder="如 SUCCESS,ERROR,WAITING">${bubbleStatesText}</textarea></div>
1366
+ </div>
1367
+ <div class="settings-section" id="settings-festival-section">
1368
+ <h3>今日节日</h3>
1369
+ <div class="field"><label>节日名称</label><span id="set-festival-label">${todayFestival ? todayFestival.label : '今日无节日'}</span></div>
1370
+ <div class="field"><label>节日祝福</label><button id="set-festival-play" type="button" ${festivalButtonDisabled ? 'disabled' : ''} style="padding:6px 10px;border:1px solid #d8d8d8;border-radius:6px;background:${festivalButtonDisabled ? '#f0f1f4' : '#f5f6f8'};cursor:${festivalButtonDisabled ? 'not-allowed' : 'pointer'}">${festivalButtonLabel}</button></div>
1371
+ </div>
1372
+ <div class="actions">
1373
+ <button id="settings-save">保存</button>
1374
+ <button id="settings-close" class="secondary">关闭</button>
1375
+ </div>
1376
+ `
1377
+ renderEmotionBars(settingsPanel.querySelector('#settings-emotion-bars'))
1378
+
1379
+ const bindRange = (id, valId, suffix) => {
1380
+ const input = settingsPanel.querySelector(id)
1381
+ const output = settingsPanel.querySelector(valId)
1382
+ input.addEventListener('input', () => { output.textContent = `${input.value}${suffix}` })
1383
+ }
1384
+ bindRange('#set-moveChance', '#set-moveChance-val', '%')
1385
+ bindRange('#set-actionDelayMs', '#set-actionDelayMs-val', 'ms')
1386
+ bindRange('#set-playbackRate', '#set-playbackRate-val', 'x')
1387
+
1388
+ settingsPanel.querySelector('#settings-close').addEventListener('click', closeSettings)
1389
+ settingsPanel.querySelector('#settings-save').addEventListener('click', saveSettingsPanel)
1390
+ settingsPanel.querySelector('#set-festival-play').addEventListener('click', () => {
1391
+ const festival = getTodayFestival()
1392
+ if (festival) playFestivalGreeting(festival)
1393
+ })
1394
+ }
1395
+
1396
+ function updateSettingsFestivalSection() {
1397
+ if (!settingsPanel.classList.contains('visible')) return
1398
+ const todayFestival = getTodayFestival()
1399
+ const labelEl = settingsPanel.querySelector('#set-festival-label')
1400
+ const buttonEl = settingsPanel.querySelector('#set-festival-play')
1401
+ if (labelEl) labelEl.textContent = todayFestival ? todayFestival.label : '今日无节日'
1402
+ if (!buttonEl) return
1403
+ const disabled = !todayFestival || !CONFIG.holidayEnabled
1404
+ buttonEl.textContent = todayFestival ? `播放${todayFestival.label}` : '今日无节日'
1405
+ buttonEl.disabled = disabled
1406
+ buttonEl.style.background = disabled ? '#f0f1f4' : '#f5f6f8'
1407
+ buttonEl.style.cursor = disabled ? 'not-allowed' : 'pointer'
1408
+ }
1409
+
1410
+ function saveSettingsPanel() {
1411
+ const val = (id) => settingsPanel.querySelector(id)
1412
+ const number = (id, fallback, min, max) => {
1413
+ const raw = Number(val(id).value)
1414
+ return Math.min(max, Math.max(min, Number.isFinite(raw) ? raw : fallback))
1415
+ }
1416
+ const petSize = Math.round(number('#set-petSize', CONFIG.petSize, 100, 1000) / 10) * 10
1417
+ const moveChance = number('#set-moveChance', CONFIG.moveChance, 0, 100)
1418
+ const actionDelayMs = number('#set-actionDelayMs', CONFIG.actionDelayMs, 0, 5000)
1419
+ const playbackRate = number('#set-playbackRate', CONFIG.playbackRate, 1, 2)
1420
+ const activityLevel = val('#set-activityLevel').value
1421
+ const reducedMotion = val('#set-reducedMotion').checked
1422
+ const walkEnabled = val('#set-walkEnabled').checked
1423
+ const workMinutes = number('#set-workMinutes', CONFIG.workMinutes, 1, 120)
1424
+ const breakMinutes = number('#set-breakMinutes', CONFIG.breakMinutes, 1, 60)
1425
+ const roastEnabled = val('#set-roastEnabled').checked
1426
+ const holidayEnabled = val('#set-holidayEnabled').checked
1427
+ const bubbleMode = val('#set-bubbleMode').value
1428
+ const bubbleStates = parseList(val('#set-bubbleStates').value)
1429
+ const enabledActions = parseList(val('#set-enabledActions').value)
1430
+ const actionOrder = parseList(val('#set-actionOrder').value)
1431
+
1432
+ Object.assign(CONFIG, {
1433
+ petSize, moveChance, actionDelayMs, playbackRate, activityLevel,
1434
+ reducedMotion, walkEnabled, workMinutes, breakMinutes, roastEnabled,
1435
+ holidayEnabled,
1436
+ bubbleMode, bubbleStates, enabledActions, actionOrder,
1437
+ })
1438
+ for (const video of [videoA, videoB]) {
1439
+ if (video) video.playbackRate = playbackRate
1440
+ }
1441
+ applySize()
1442
+ window.petBridge.saveConfig({
1443
+ petSize, moveChance, actionDelayMs, playbackRate, activityLevel,
1444
+ reducedMotion, walkEnabled, workMinutes, breakMinutes, roastEnabled,
1445
+ holidayEnabled,
1446
+ bubbleMode, bubbleStates, enabledActions, actionOrder,
1447
+ })
1448
+ if (holidayEnabled) maybeAutoPlayFestival()
1449
+ closeSettings()
1450
+ }
1451
+
1452
+ function openSettings() {
1453
+ renderSettingsPanelContent()
1454
+ settingsPanel.classList.add('visible')
1455
+ updateSettingsFestivalSection()
1456
+ if (!settingsFestivalTimer) {
1457
+ settingsFestivalTimer = setInterval(updateSettingsFestivalSection, 60 * 1000)
1458
+ settingsFestivalTimer.unref?.()
1459
+ }
1460
+ window.petBridge.setIgnoreMouse(false)
1461
+ }
1462
+
1463
+ function closeSettings() {
1464
+ settingsPanel.classList.remove('visible')
1465
+ if (settingsFestivalTimer) {
1466
+ clearInterval(settingsFestivalTimer)
1467
+ settingsFestivalTimer = null
1468
+ }
1469
+ updateClickThrough()
1470
+ }
1471
+
1472
+ let chatMessages = []
1473
+ let chatAppendMsg = null
1474
+ let chatDictationPending = false
1475
+ function renderChatPanel() {
1476
+ chatPanel.innerHTML = `
1477
+ <div class="chat-header"><span>🐳 和大肥鱼闲聊</span><span class="chat-close">✕</span></div>
1478
+ <div class="chat-messages"></div>
1479
+ <div class="chat-input-row"><span id="chat-mic">🎤</span><span id="chat-task-send" style="display:none;padding:8px 12px;background:#ff9f43;color:#fff;border-radius:8px;font-size:12px;cursor:pointer;user-select:none;white-space:nowrap">执行任务</span><input placeholder="说点什么…"><span>发送</span></div>
1480
+ `
1481
+ const close = chatPanel.querySelector('.chat-close')
1482
+ close.onmousedown = (e) => { e.preventDefault(); closeChat() }
1483
+ const header = chatPanel.querySelector('.chat-header')
1484
+ let chatDrag = null
1485
+ header.onmousedown = (e) => {
1486
+ if (e.target.classList.contains('chat-close')) return
1487
+ e.preventDefault()
1488
+ chatDrag = {
1489
+ startX: e.clientX,
1490
+ startY: e.clientY,
1491
+ left: chatPanel.offsetLeft,
1492
+ top: chatPanel.offsetTop,
1493
+ }
1494
+ const onMove = (ev) => {
1495
+ if (!chatDrag) return
1496
+ const dx = ev.clientX - chatDrag.startX
1497
+ const dy = ev.clientY - chatDrag.startY
1498
+ chatPanel.style.left = Math.max(0, Math.min(window.innerWidth - 100, chatDrag.left + dx)) + 'px'
1499
+ chatPanel.style.top = Math.max(0, Math.min(window.innerHeight - 60, chatDrag.top + dy)) + 'px'
1500
+ }
1501
+ const onUp = () => {
1502
+ chatDrag = null
1503
+ window.removeEventListener('mousemove', onMove)
1504
+ window.removeEventListener('mouseup', onUp)
1505
+ }
1506
+ window.addEventListener('mousemove', onMove)
1507
+ window.addEventListener('mouseup', onUp)
1508
+ }
1509
+ const messagesEl = chatPanel.querySelector('.chat-messages')
1510
+ const input = chatPanel.querySelector('input')
1511
+ const send = chatPanel.querySelector('.chat-input-row span:last-child')
1512
+ const mic = chatPanel.querySelector('#chat-mic')
1513
+ if (CONFIG.voiceEnabled === false) mic.style.display = 'none'
1514
+ const taskBtn = chatPanel.querySelector('#chat-task-send')
1515
+ const setTaskMode = (active) => {
1516
+ taskBtn.style.display = active ? 'inline-block' : 'none'
1517
+ send.style.display = active ? 'none' : 'inline-block'
1518
+ }
1519
+ const runTask = async () => {
1520
+ const content = input.value.trim()
1521
+ if (!content) return
1522
+ setTaskMode(false)
1523
+ if (chatAppendMsg) chatAppendMsg('pet', '好的,我来执行任务…')
1524
+ const result = await window.petBridge.executeTask(content)
1525
+ const reply = result?.result || '任务执行完成'
1526
+ if (chatAppendMsg) chatAppendMsg('pet', reply)
1527
+ }
1528
+ taskBtn.onmousedown = (e) => { e.preventDefault(); void runTask() }
1529
+ const appendMsg = (role, text) => {
1530
+ const div = document.createElement('div')
1531
+ div.className = `chat-msg ${role}`
1532
+ div.textContent = text
1533
+ messagesEl.appendChild(div)
1534
+ messagesEl.scrollTop = messagesEl.scrollHeight
1535
+ }
1536
+ chatAppendMsg = appendMsg
1537
+ for (const msg of chatMessages) appendMsg(msg.role, msg.content)
1538
+ const doSend = async (text) => {
1539
+ const content = String(text || input.value || '').trim()
1540
+ if (!content) return
1541
+ input.value = ''
1542
+ setTaskMode(false)
1543
+ appendMsg('user', content)
1544
+ chatMessages.push({ role: 'user', content })
1545
+ appendMsg('pet', '正在想…')
1546
+ const result = await window.petBridge.sendChat(content)
1547
+ const reply = result?.reply || '大肥鱼走神了,再说一遍吧~'
1548
+ const last = messagesEl.querySelector('.chat-msg.pet:last-child')
1549
+ if (last) last.textContent = reply
1550
+ chatMessages.push({ role: 'assistant', content: reply })
1551
+ messagesEl.scrollTop = messagesEl.scrollHeight
1552
+
1553
+ }
1554
+ mic.onmousedown = async (e) => {
1555
+ e.preventDefault()
1556
+ if (senseRecording) {
1557
+ appendMsg('pet', '正在停止录音…')
1558
+ await stopSenseRecording()
1559
+ return
1560
+ }
1561
+ if (chatDictationPending) return
1562
+ chatDictationPending = true
1563
+ appendMsg('pet', '我在听,请说话…')
1564
+ try {
1565
+ await startSenseRecording()
1566
+ } catch {
1567
+ // 本地录音不可用时,回退到 SAPI 命令/听写
1568
+ chatDictationPending = false
1569
+ appendMsg('pet', '本地录音不可用,切换系统识别…')
1570
+ window.petBridge.startDictation()
1571
+ }
1572
+ }
1573
+ send.onmousedown = (e) => { e.preventDefault(); void doSend() }
1574
+ input.addEventListener('keydown', (e) => {
1575
+ if (e.key !== 'Enter') return
1576
+ e.preventDefault()
1577
+ if (taskBtn.style.display !== 'none') void runTask()
1578
+ else void doSend()
1579
+ })
1580
+ }
1581
+ function openChat() {
1582
+ renderChatPanel()
1583
+ chatPanel.style.left = Math.max(0, Math.round((window.innerWidth - 420) / 2)) + 'px'
1584
+ chatPanel.style.top = Math.max(0, Math.round((window.innerHeight - 520) / 2)) + 'px'
1585
+ chatPanel.style.transform = 'none'
1586
+ chatPanel.classList.add('visible')
1587
+ window.petBridge.setIgnoreMouse(false)
1588
+ }
1589
+ function closeChat() {
1590
+ chatPanel.classList.remove('visible')
1591
+ updateClickThrough()
1592
+ }
1593
+
1594
+ async function sendChatText(content) {
1595
+ const text = String(content || '').trim()
1596
+ if (!text) return
1597
+ if (chatAppendMsg) chatAppendMsg('user', text)
1598
+ chatMessages.push({ role: 'user', content: text })
1599
+ if (chatAppendMsg) chatAppendMsg('pet', '正在想…')
1600
+ const result = await window.petBridge.sendChat(text)
1601
+ const reply = result?.reply || '大肥鱼走神了,再说一遍吧~'
1602
+ if (chatPanel && chatPanel.classList.contains('visible')) {
1603
+ const messagesEl = chatPanel.querySelector('.chat-messages')
1604
+ const last = messagesEl?.querySelector('.chat-msg.pet:last-child')
1605
+ if (last) last.textContent = reply
1606
+ if (messagesEl) messagesEl.scrollTop = messagesEl.scrollHeight
1607
+ }
1608
+ chatMessages.push({ role: 'assistant', content: reply })
1609
+ // 连续对话:回复播完后自动开始听下一句
1610
+ if (CONFIG.voiceAutoRecord !== false && CONFIG.voiceEnabled !== false && chatPanel.classList.contains('visible') && !senseRecording) {
1611
+ setTimeout(async () => {
1612
+ try {
1613
+ await startSenseRecording()
1614
+ if (chatAppendMsg) chatAppendMsg('pet', '我在,请说~')
1615
+ } catch {
1616
+ // 自动续听失败时静默,用户可手动点 🎤
1617
+ }
1618
+ }, 800)
1619
+ }
1620
+ }
1621
+
1622
+ function matchRuleCommand(text) {
1623
+ const t = String(text || '')
1624
+ if (t.includes('停止番茄钟')) return { action: 'pomodoro_stop' }
1625
+ if (t.includes('开始番茄钟') || t.includes('番茄钟')) return { action: 'pomodoro_start' }
1626
+ if (t.includes('喂食') || t.includes('吃饭')) return { action: 'feed' }
1627
+ if (t.includes('隐藏')) return { action: 'hide' }
1628
+ if (t.includes('关闭') || t.includes('退出')) return { action: 'close' }
1629
+ if (t.includes('余额')) return { action: 'balance' }
1630
+ if (t.includes('吐槽')) return { action: 'roast' }
1631
+ if (t.includes('设置')) return { action: 'settings' }
1632
+ if (t.includes('打开') && (t.includes('网页') || t.includes('浏览器') || t.includes('网站'))) return { action: 'open_web' }
1633
+ if (t.includes('提醒')) return { action: 'remind' }
1634
+ if (t.includes('左边') || t.includes('左侧') || t.includes('左面')) return { action: 'move_pet', args: { position: 'left' } }
1635
+ if (t.includes('右边') || t.includes('右侧') || t.includes('右面')) return { action: 'move_pet', args: { position: 'right' } }
1636
+ if (t.includes('中间') || t.includes('居中')) return { action: 'move_pet', args: { position: 'center' } }
1637
+ if (t.includes('上面') || t.includes('顶部') || t.includes('上方')) return { action: 'move_pet', args: { position: 'top' } }
1638
+ if (t.includes('下面') || t.includes('底部') || t.includes('下方')) return { action: 'move_pet', args: { position: 'bottom' } }
1639
+ return null
1640
+ }
1641
+
1642
+ function executeAction(action, args = {}) {
1643
+ switch (action) {
1644
+ case 'pomodoro_start':
1645
+ startPomodoro('work', CONFIG.workMinutes)
1646
+ showManualBubble('收到,开始番茄钟~', `${CONFIG.workMinutes} 分钟`, 3000)
1647
+ return true
1648
+ case 'pomodoro_stop':
1649
+ stopPomodoro()
1650
+ showManualBubble('番茄钟已停止~', '', 2500)
1651
+ return true
1652
+ case 'feed':
1653
+ feedPet()
1654
+ return true
1655
+ case 'hide':
1656
+ window.petBridge.hide()
1657
+ return true
1658
+ case 'close':
1659
+ window.petBridge.close('user')
1660
+ return true
1661
+ case 'balance':
1662
+ window.petBridge.refreshBalance()
1663
+ showManualBubble('正在刷新余额~', '', 2000)
1664
+ return true
1665
+ case 'roast':
1666
+ window.petBridge.requestRoast()
1667
+ return true
1668
+ case 'settings':
1669
+ menuPage = 'settings'
1670
+ showMenu(lastMenuPos.x, lastMenuPos.y)
1671
+ return true
1672
+ case 'open_web':
1673
+ window.petBridge.openWebUi(args.url || CONFIG.webuiUrl)
1674
+ showManualBubble('正在打开…', args.url || CONFIG.webuiUrl || '', 2000)
1675
+ return true
1676
+ case 'move_pet': {
1677
+ const position = args.position || 'left'
1678
+ const minX = -(HIT_BOX.x0 / 640 * size)
1679
+ const maxX = window.innerWidth - (HIT_BOX.x1 / 640 * size)
1680
+ const maxY = window.innerHeight - size * 9 / 16
1681
+ if (position === 'left') petPos.x = minX
1682
+ else if (position === 'right') petPos.x = maxX
1683
+ else if (position === 'center') petPos.x = Math.max(minX, Math.min(maxX, (window.innerWidth - size) / 2))
1684
+ else if (position === 'top') petPos.y = 0
1685
+ else if (position === 'bottom') petPos.y = maxY
1686
+ applyPetPosition()
1687
+ showManualBubble('好的,我挪过去~', position, 2000)
1688
+ return true
1689
+ }
1690
+ case 'remind': {
1691
+ const minutes = Number(args.minutes) || 10
1692
+ const text = args.text || '该做事啦'
1693
+ showManualBubble(`好的,${minutes}分钟后提醒你`, text, 3000)
1694
+ return true
1695
+ }
1696
+ default:
1697
+ return false
1698
+ }
1699
+ }
1700
+
1701
+ async function handleUserSpeech(text) {
1702
+ const content = String(text || '').trim()
1703
+ if (!content) return
1704
+ // 先走本地规则命令,零 Token、零上下文污染
1705
+ const rule = matchRuleCommand(content)
1706
+ if (rule && executeAction(rule.action, rule.args)) return
1707
+ // 再走独立 LLM 意图分类(不带闲聊历史)
1708
+ const result = await window.petBridge.classifyIntent(content)
1709
+ if (result?.type === 'command' && result.action && executeAction(result.action, result.args)) return
1710
+ // 识别为任务:不自动执行,填入输入框并显示「执行任务」按钮,等用户手动确认
1711
+ if (result?.type === 'task') {
1712
+ if (!chatPanel.classList.contains('visible')) openChat()
1713
+ const input = chatPanel.querySelector('input')
1714
+ const taskBtn = chatPanel.querySelector('#chat-task-send')
1715
+ if (input) {
1716
+ input.value = result.task || content
1717
+ input.focus()
1718
+ input.setSelectionRange(input.value.length, input.value.length)
1719
+ }
1720
+ const sendBtn = chatPanel.querySelector('.chat-input-row span:last-child')
1721
+ if (taskBtn) taskBtn.style.display = 'inline-block'
1722
+ if (sendBtn) sendBtn.style.display = 'none'
1723
+ if (chatAppendMsg) chatAppendMsg('pet', '已识别为任务,确认无误后点击「执行任务」执行;不想执行可直接修改或清空输入框。')
1724
+ return
1725
+ }
1726
+ // 都不是任务 → 进入闲聊(独立上下文)
1727
+ await sendChatText(content)
1728
+ }
1729
+
1730
+
1731
+ let senseRecording = null
1732
+ let senseChunks = []
1733
+
1734
+ function encodeWav(samples, sampleRate) {
1735
+ const buffer = new ArrayBuffer(44 + samples.length * 2)
1736
+ const view = new DataView(buffer)
1737
+ const writeString = (offset, str) => {
1738
+ for (let i = 0; i < str.length; i++) view.setUint8(offset + i, str.charCodeAt(i))
1739
+ }
1740
+ writeString(0, 'RIFF')
1741
+ view.setUint32(4, 36 + samples.length * 2, true)
1742
+ writeString(8, 'WAVE')
1743
+ writeString(12, 'fmt ')
1744
+ view.setUint32(16, 16, true)
1745
+ view.setUint16(20, 1, true)
1746
+ view.setUint16(22, 1, true)
1747
+ view.setUint32(24, sampleRate, true)
1748
+ view.setUint32(28, sampleRate * 2, true)
1749
+ view.setUint16(32, 2, true)
1750
+ view.setUint16(34, 16, true)
1751
+ writeString(36, 'data')
1752
+ view.setUint32(40, samples.length * 2, true)
1753
+ for (let i = 0; i < samples.length; i++) {
1754
+ const s = Math.max(-1, Math.min(1, samples[i]))
1755
+ view.setInt16(44 + i * 2, s < 0 ? s * 0x8000 : s * 0x7fff, true)
1756
+ }
1757
+ return new Uint8Array(buffer)
1758
+ }
1759
+
1760
+ function resampleLinear(input, fromRate, toRate) {
1761
+ if (input.length === 0) return new Float32Array(0)
1762
+ const ratio = fromRate / toRate
1763
+ const outputLength = Math.max(1, Math.round(input.length / ratio))
1764
+ const output = new Float32Array(outputLength)
1765
+ for (let i = 0; i < outputLength; i++) {
1766
+ const pos = i * ratio
1767
+ const index = Math.floor(pos)
1768
+ const frac = pos - index
1769
+ const a = input[Math.min(index, input.length - 1)]
1770
+ const b = input[Math.min(index + 1, input.length - 1)]
1771
+ output[i] = a + (b - a) * frac
1772
+ }
1773
+ return output
1774
+ }
1775
+
1776
+ async function startSenseRecording() {
1777
+ if (senseRecording) return
1778
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
1779
+ const audioContext = new AudioContext({ sampleRate: 16000 })
1780
+ const source = audioContext.createMediaStreamSource(stream)
1781
+ const scriptNode = audioContext.createScriptProcessor(4096, 1, 1)
1782
+ senseChunks = []
1783
+ let hasVoice = false
1784
+ let lastVoice = 0
1785
+ const startTime = Date.now()
1786
+ let autoStopped = false
1787
+ scriptNode.onaudioprocess = (event) => {
1788
+ const data = event.inputBuffer.getChannelData(0)
1789
+ senseChunks.push(new Float32Array(data))
1790
+ let sum = 0
1791
+ for (let i = 0; i < data.length; i++) sum += data[i] * data[i]
1792
+ const rms = Math.sqrt(sum / data.length)
1793
+ if (rms > 0.012) {
1794
+ hasVoice = true
1795
+ lastVoice = Date.now()
1796
+ }
1797
+ // 自动断句:检测到人声后,静音超过设定时长自动停止并转写
1798
+ const silenceMs = CONFIG.voiceSilenceMs || 1200
1799
+ if (hasVoice && !autoStopped && Date.now() - lastVoice > silenceMs && Date.now() - startTime > 800) {
1800
+ autoStopped = true
1801
+ scriptNode.onaudioprocess = null
1802
+ setTimeout(() => {
1803
+ if (senseRecording) void stopSenseRecording(CONFIG.voiceAutoSend !== false)
1804
+ }, 0)
1805
+ }
1806
+ }
1807
+ source.connect(scriptNode)
1808
+ scriptNode.connect(audioContext.destination)
1809
+ senseRecording = { stream, audioContext, source, scriptNode }
1810
+ }
1811
+
1812
+ async function stopSenseRecording(autoSend = false) {
1813
+ if (!senseRecording) return
1814
+ const { stream, audioContext, source, scriptNode } = senseRecording
1815
+ senseRecording = null
1816
+ try {
1817
+ scriptNode.disconnect()
1818
+ source.disconnect()
1819
+ stream.getTracks().forEach((track) => track.stop())
1820
+ await audioContext.close()
1821
+ } catch {
1822
+ // 忽略清理异常
1823
+ }
1824
+ const sampleRate = audioContext.sampleRate || 16000
1825
+ let samples = new Float32Array(senseChunks.reduce((sum, chunk) => sum + chunk.length, 0))
1826
+ let offset = 0
1827
+ for (const chunk of senseChunks) {
1828
+ samples.set(chunk, offset)
1829
+ offset += chunk.length
1830
+ }
1831
+ senseChunks = []
1832
+ if (sampleRate !== 16000) samples = resampleLinear(samples, sampleRate, 16000)
1833
+ const wav = encodeWav(samples, 16000)
1834
+ chatDictationPending = false
1835
+ if (chatAppendMsg) chatAppendMsg('pet', '识别中…')
1836
+ const result = await window.petBridge.transcribe(wav.buffer)
1837
+ const text = result?.text || ''
1838
+ if (!text) {
1839
+ const error = result?.error || ''
1840
+ if (chatAppendMsg) chatAppendMsg('pet', error ? `识别失败:${error}` : '没听清,再说一次吧~')
1841
+ return
1842
+ }
1843
+ if (autoSend) {
1844
+ await handleUserSpeech(text)
1845
+ return
1846
+ }
1847
+ if (chatPanel && chatPanel.classList.contains('visible')) {
1848
+ const input = chatPanel.querySelector('input')
1849
+ if (input) {
1850
+ input.value = text
1851
+ input.focus()
1852
+ if (chatAppendMsg) chatAppendMsg('pet', `识别到:${text}\n可修改后按回车发送`)
1853
+ return
1854
+ }
1855
+ }
1856
+ await handleDictationResult(text)
1857
+ }
1858
+
1859
+ async function handleDictationResult(text) {
1860
+ chatDictationPending = false
1861
+ const content = String(text || '').trim()
1862
+ if (!content) {
1863
+ if (chatAppendMsg) chatAppendMsg('pet', '没听清,再说一次吧~')
1864
+ return
1865
+ }
1866
+ // 识别结果先放进输入框,让用户确认/修改后再发送,避免错字直接发给大肥鱼。
1867
+ if (chatPanel && chatPanel.classList.contains('visible')) {
1868
+ const input = chatPanel.querySelector('input')
1869
+ if (input) {
1870
+ input.value = content
1871
+ input.focus()
1872
+ if (chatAppendMsg) chatAppendMsg('pet', `识别到:${content}\n可修改后按回车发送`)
1873
+ return
1874
+ }
1875
+ }
1876
+ // 极端情况:聊天窗已关闭时,直接作为消息发送。
1877
+ if (chatAppendMsg) chatAppendMsg('user', content)
1878
+ chatMessages.push({ role: 'user', content })
1879
+ if (chatAppendMsg) chatAppendMsg('pet', '正在想…')
1880
+ const result = await window.petBridge.sendChat(content)
1881
+ const reply = result?.reply || '大肥鱼走神了,再说一遍吧~'
1882
+ if (chatPanel && chatPanel.classList.contains('visible')) {
1883
+ const messagesEl = chatPanel.querySelector('.chat-messages')
1884
+ const last = messagesEl?.querySelector('.chat-msg.pet:last-child')
1885
+ if (last) last.textContent = reply
1886
+ if (messagesEl) messagesEl.scrollTop = messagesEl.scrollHeight
1887
+ }
1888
+ chatMessages.push({ role: 'assistant', content: reply })
1889
+ }
1890
+
1891
+ function renderSettingsPage() {
1892
+ addMenuButton('← 返回主菜单', () => {
1893
+ menuPage = 'main'
1894
+ showMenu(lastMenuPos.x, lastMenuPos.y)
1895
+ })
1896
+ const bubbleStatesText = Array.isArray(CONFIG.bubbleStates) ? CONFIG.bubbleStates.join(', ') : ''
1897
+ const todayFestival = getTodayFestival()
1898
+ const todayLunar = getLunarDateParts()
1899
+ const festivalButtonLabel = todayFestival ? `播放${todayFestival.label}` : '今日无节日'
1900
+ const festivalButtonDisabled = !todayFestival || !CONFIG.holidayEnabled
1901
+ let activityLevel = CONFIG.activityLevel
1902
+ let bubbleMode = CONFIG.bubbleMode
1903
+ let enabledActions = CONFIG.enabledActions.length ? CONFIG.enabledActions.slice() : ACTS.slice()
1904
+ let actionOrder = CONFIG.actionOrder.filter((name) => ACTS.includes(name))
1905
+
1906
+ const form = document.createElement('div')
1907
+ form.style.cssText = 'min-width:320px;padding:2px 2px 6px;pointer-events:auto'
1908
+ form.innerHTML = `
1909
+ <div style="font-size:13px;font-weight:600;margin:4px 0 6px;color:#333">外观与行为</div>
1910
+ <div class="ms-field"><span>宠物宽度</span><input type="number" id="ms-petSize" min="100" max="1000" step="10" value="${CONFIG.petSize}"></div>
1911
+ <div class="ms-field"><span>移动频繁度</span><input type="range" id="ms-moveChance" min="0" max="100" step="1" value="${CONFIG.moveChance}"><em id="ms-moveChance-val">${CONFIG.moveChance}%</em></div>
1912
+ <div class="ms-field"><span>空闲动作间隔</span><input type="range" id="ms-actionDelayMs" min="0" max="5000" step="100" value="${CONFIG.actionDelayMs}"><em id="ms-actionDelayMs-val">${CONFIG.actionDelayMs}ms</em></div>
1913
+ <div class="ms-field"><span>播放速度</span><input type="range" id="ms-playbackRate" min="1" max="2" step="0.1" value="${CONFIG.playbackRate}"><em id="ms-playbackRate-val">${CONFIG.playbackRate}x</em></div>
1914
+ <div class="ms-field"><span>活跃程度</span><span id="ms-activityLevel" class="ms-seg"></span></div>
1915
+ <label class="ms-check"><input type="checkbox" id="ms-reducedMotion" ${CONFIG.reducedMotion ? 'checked' : ''}> 减少动态</label>
1916
+ <label class="ms-check"><input type="checkbox" id="ms-walkEnabled" ${CONFIG.walkEnabled ? 'checked' : ''}> 允许行走</label>
1917
+ <div style="font-size:13px;font-weight:600;margin:8px 0 6px;color:#333">番茄钟</div>
1918
+ <div class="ms-field"><span>工作时长</span><input type="number" id="ms-workMinutes" min="1" max="120" step="1" value="${CONFIG.workMinutes}"></div>
1919
+ <div class="ms-field"><span>休息时长</span><input type="number" id="ms-breakMinutes" min="1" max="60" step="1" value="${CONFIG.breakMinutes}"></div>
1920
+ <div style="font-size:13px;font-weight:600;margin:8px 0 6px;color:#333">动作</div>
1921
+ <div class="ms-field" style="align-items:flex-start"><span>待机动作</span><span id="ms-enabledActionsList" class="ms-list"></span></div>
1922
+ <div style="font-size:12px;color:#888;margin:2px 0 4px">播放顺序:按勾选顺序排列,可用 ↑↓ 调整</div>
1923
+ <div id="ms-orderPreview" class="ms-order-preview"></div>
1924
+ <div class="ms-field" style="align-items:flex-start"><span>可选动作</span><span id="ms-actionOrderList" class="ms-list"></span></div>
1925
+ <div style="font-size:13px;font-weight:600;margin:8px 0 6px;color:#333">功能</div>
1926
+ <label class="ms-check"><input type="checkbox" id="ms-roastEnabled" ${CONFIG.roastEnabled ? 'checked' : ''}> 自动吐槽</label>
1927
+ <label class="ms-check"><input type="checkbox" id="ms-holidayEnabled" ${CONFIG.holidayEnabled ? 'checked' : ''}> 节日祝福</label>
1928
+ <label class="ms-check"><input type="checkbox" id="ms-voiceEnabled" ${CONFIG.voiceEnabled !== false ? 'checked' : ''}> 启用语音功能(麦克风)</label>
1929
+ <label class="ms-check"><input type="checkbox" id="ms-voiceWakeNow" ${wakeWordEnabled ? 'checked' : ''}> 开启语音唤醒(麦克风,立即生效)</label>
1930
+ <label class="ms-check"><input type="checkbox" id="ms-voiceWakeAutoStart" ${CONFIG.voiceWakeAutoStart ? 'checked' : ''}> 启动时自动开启语音唤醒</label>
1931
+ <div class="ms-field"><span>断句静音</span><input type="range" id="ms-voiceSilenceMs" min="300" max="5000" step="100" value="${CONFIG.voiceSilenceMs}"><em id="ms-voiceSilenceMs-val">${CONFIG.voiceSilenceMs}ms</em></div>
1932
+ <label class="ms-check"><input type="checkbox" id="ms-voiceAutoSend" ${CONFIG.voiceAutoSend !== false ? 'checked' : ''}> 语音识别后自动发送</label>
1933
+ <label class="ms-check"><input type="checkbox" id="ms-voiceAutoRecord" ${CONFIG.voiceAutoRecord !== false ? 'checked' : ''}> 闲聊时说“大肥鱼”自动录音</label>
1934
+ <div class="ms-field"><span>唤醒词</span><input type="text" id="ms-wakeWord" value="${CONFIG.wakeWord}" placeholder="例如:大肥鱼"></div>
1935
+ <div class="ms-field"><span>任务目录</span><input type="text" id="ms-taskCwd" value="${CONFIG.taskCwd || ''}" placeholder="留空=用户主目录"></div>
1936
+ <div class="ms-field"><span>气泡模式</span><span id="ms-bubbleMode" class="ms-seg"></span></div>
1937
+ <div class="ms-field"><span>气泡状态</span><textarea id="ms-bubbleStates" placeholder="SUCCESS,ERROR,WAITING">${bubbleStatesText}</textarea></div>
1938
+ <div id="ms-festival-area" style="margin-top:8px;padding-top:8px;border-top:1px solid #eee">
1939
+ <div style="font-size:13px;font-weight:600;margin-bottom:6px;color:#333">今日节日</div>
1940
+ <div class="ms-field"><span>节日名称</span><strong id="ms-festival-label">${todayFestival ? todayFestival.label : '今日无节日'}</strong></div>
1941
+ <div class="ms-field"><span>今日农历</span><strong>${todayLunar.month}${todayLunar.dayText || ''}</strong></div>
1942
+ <div class="ms-field"><span>节日祝福</span><button id="ms-festival-play" type="button" ${festivalButtonDisabled ? 'disabled' : ''} style="padding:4px 8px;border:1px solid #d8d8d8;border-radius:6px;background:${festivalButtonDisabled ? '#f0f1f4' : '#f5f6f8'};cursor:${festivalButtonDisabled ? 'not-allowed' : 'pointer'}">${festivalButtonLabel}</button></div>
1943
+ </div>
1944
+ `
1945
+ menuEl.appendChild(form)
1946
+
1947
+ const bindRange = (id, valId, suffix) => {
1948
+ const input = form.querySelector(id)
1949
+ const output = form.querySelector(valId)
1950
+ input.addEventListener('input', () => { output.textContent = `${input.value}${suffix}` })
1951
+ }
1952
+ bindRange('#ms-moveChance', '#ms-moveChance-val', '%')
1953
+ bindRange('#ms-actionDelayMs', '#ms-actionDelayMs-val', 'ms')
1954
+ bindRange('#ms-playbackRate', '#ms-playbackRate-val', 'x')
1955
+ bindRange('#ms-voiceSilenceMs', '#ms-voiceSilenceMs-val', 'ms')
1956
+
1957
+ const renderSeg = (container, name, options, current, onChange) => {
1958
+ container.innerHTML = ''
1959
+ for (const option of options) {
1960
+ const label = document.createElement('label')
1961
+ label.style.cssText = `display:inline-block;padding:4px 8px;border:1px solid #d8d8d8;border-radius:6px;font-size:12px;cursor:pointer;pointer-events:auto;background:${option.value === current ? '#4a7cff' : '#fff'};color:${option.value === current ? '#fff' : '#333'}`
1962
+ const radio = document.createElement('input')
1963
+ radio.type = 'radio'
1964
+ radio.name = name
1965
+ radio.value = option.value
1966
+ radio.checked = option.value === current
1967
+ radio.style.display = 'none'
1968
+ radio.addEventListener('change', () => {
1969
+ if (radio.checked) {
1970
+ onChange(option.value)
1971
+ renderSeg(container, name, options, option.value, onChange)
1972
+ }
1973
+ })
1974
+ label.append(radio, option.label)
1975
+ container.appendChild(label)
1976
+ }
1977
+ }
1978
+ renderSeg(form.querySelector('#ms-activityLevel'), 'ms-activity', [
1979
+ { value: 'quiet', label: '安静' },
1980
+ { value: 'normal', label: '标准' },
1981
+ { value: 'lively', label: '活泼' },
1982
+ ], activityLevel, (value) => { activityLevel = value })
1983
+
1984
+ const enabledListEl = form.querySelector('#ms-enabledActionsList')
1985
+ const renderEnabledList = () => {
1986
+ enabledListEl.innerHTML = ''
1987
+ for (const name of ACTS) {
1988
+ const label = document.createElement('label')
1989
+ label.style.cssText = 'display:flex;align-items:center;gap:6px;font-size:12px;padding:2px 0;cursor:pointer'
1990
+ const checkbox = document.createElement('input')
1991
+ checkbox.type = 'checkbox'
1992
+ checkbox.checked = enabledActions.includes(name)
1993
+ checkbox.addEventListener('change', () => {
1994
+ if (checkbox.checked) {
1995
+ if (!enabledActions.includes(name)) enabledActions.push(name)
1996
+ } else {
1997
+ enabledActions = enabledActions.filter((n) => n !== name)
1998
+ }
1999
+ })
2000
+ label.append(checkbox, name)
2001
+ enabledListEl.appendChild(label)
2002
+ }
2003
+ }
2004
+ renderEnabledList()
2005
+
2006
+ const orderPreviewEl = form.querySelector('#ms-orderPreview')
2007
+ const orderListEl = form.querySelector('#ms-actionOrderList')
2008
+ const renderOrder = () => {
2009
+ orderPreviewEl.innerHTML = ''
2010
+ if (actionOrder.length === 0) {
2011
+ orderPreviewEl.textContent = '未设置顺序,将随机播放'
2012
+ orderPreviewEl.style.color = '#999'
2013
+ orderPreviewEl.style.fontSize = '12px'
2014
+ } else {
2015
+ orderPreviewEl.style.color = '#333'
2016
+ actionOrder.forEach((name, index) => {
2017
+ const chip = document.createElement('span')
2018
+ chip.style.cssText = 'display:inline-flex;align-items:center;gap:4px;margin:2px;padding:3px 6px;background:#eef2ff;border-radius:6px;font-size:12px'
2019
+ const label = document.createElement('span')
2020
+ label.textContent = `${index + 1}. ${name}`
2021
+ const makeAction = (text, color, action) => {
2022
+ const span = document.createElement('span')
2023
+ span.textContent = text
2024
+ span.setAttribute('role', 'button')
2025
+ span.style.cssText = `cursor:pointer;font-size:12px;padding:0 4px;pointer-events:auto;user-select:none;display:inline-block;${color ? `color:${color};` : ''}`
2026
+ span.onmousedown = (event) => {
2027
+ event.preventDefault()
2028
+ event.stopPropagation()
2029
+ action()
2030
+ }
2031
+ return span
2032
+ }
2033
+ const up = makeAction('↑', '', () => {
2034
+ if (index > 0) {
2035
+ const prev = actionOrder[index - 1]
2036
+ actionOrder[index - 1] = name
2037
+ actionOrder[index] = prev
2038
+ renderOrder()
2039
+ }
2040
+ })
2041
+ const down = makeAction('↓', '', () => {
2042
+ if (index < actionOrder.length - 1) {
2043
+ const next = actionOrder[index + 1]
2044
+ actionOrder[index + 1] = name
2045
+ actionOrder[index] = next
2046
+ renderOrder()
2047
+ }
2048
+ })
2049
+ const remove = makeAction('×', '#e55', () => {
2050
+ actionOrder = actionOrder.filter((n) => n !== name)
2051
+ renderOrder()
2052
+ renderOrderList()
2053
+ })
2054
+ chip.append(label, up, down, remove)
2055
+ orderPreviewEl.appendChild(chip)
2056
+ })
2057
+ }
2058
+ renderOrderList()
2059
+ }
2060
+ const renderOrderList = () => {
2061
+ orderListEl.innerHTML = ''
2062
+ for (const name of ACTS) {
2063
+ const label = document.createElement('label')
2064
+ label.style.cssText = 'display:flex;align-items:center;gap:6px;font-size:12px;padding:2px 0;cursor:pointer'
2065
+ const checkbox = document.createElement('input')
2066
+ checkbox.type = 'checkbox'
2067
+ checkbox.checked = actionOrder.includes(name)
2068
+ checkbox.addEventListener('change', () => {
2069
+ if (checkbox.checked) {
2070
+ if (!actionOrder.includes(name)) actionOrder.push(name)
2071
+ } else {
2072
+ actionOrder = actionOrder.filter((n) => n !== name)
2073
+ }
2074
+ renderOrder()
2075
+ })
2076
+ label.append(checkbox, name)
2077
+ orderListEl.appendChild(label)
2078
+ }
2079
+ }
2080
+ renderOrder()
2081
+
2082
+ renderSeg(form.querySelector('#ms-bubbleMode'), 'ms-bubble', [
2083
+ { value: 'always', label: '常驻' },
2084
+ { value: 'hidden', label: '隐藏' },
2085
+ { value: 'custom', label: '自定义' },
2086
+ ], bubbleMode, (value) => { bubbleMode = value })
2087
+
2088
+ const voiceWakeNow = form.querySelector('#ms-voiceWakeNow')
2089
+ voiceWakeNow.addEventListener('change', () => {
2090
+ window.petBridge.toggleWakeWord()
2091
+ wakeWordEnabled = voiceWakeNow.checked
2092
+ showManualBubble(voiceWakeNow.checked ? '语音唤醒已开启' : '语音唤醒已关闭', voiceWakeNow.checked ? '说“大肥鱼+指令”' : '', 2500)
2093
+ })
2094
+ const festivalPlayButton = form.querySelector('#ms-festival-play')
2095
+ if (todayFestival && festivalPlayButton && !festivalButtonDisabled) {
2096
+ festivalPlayButton.addEventListener('click', () => {
2097
+ menuEl.classList.remove('visible')
2098
+ updateClickThrough()
2099
+ playFestivalGreeting(todayFestival)
2100
+ })
2101
+ }
2102
+
2103
+ addMenuButton('保存', () => {
2104
+ const val = (id) => form.querySelector(id)
2105
+ const number = (id, fallback, min, max) => {
2106
+ const raw = Number(val(id).value)
2107
+ return Math.min(max, Math.max(min, Number.isFinite(raw) ? raw : fallback))
2108
+ }
2109
+ const petSize = Math.round(number('#ms-petSize', CONFIG.petSize, 100, 1000) / 10) * 10
2110
+ const moveChance = number('#ms-moveChance', CONFIG.moveChance, 0, 100)
2111
+ const actionDelayMs = number('#ms-actionDelayMs', CONFIG.actionDelayMs, 0, 5000)
2112
+ const playbackRate = number('#ms-playbackRate', CONFIG.playbackRate, 1, 2)
2113
+ const reducedMotion = val('#ms-reducedMotion').checked
2114
+ const walkEnabled = val('#ms-walkEnabled').checked
2115
+ const workMinutes = number('#ms-workMinutes', CONFIG.workMinutes, 1, 120)
2116
+ const breakMinutes = number('#ms-breakMinutes', CONFIG.breakMinutes, 1, 60)
2117
+ const roastEnabled = val('#ms-roastEnabled').checked
2118
+ const holidayEnabled = val('#ms-holidayEnabled').checked
2119
+ const wakeWord = val('#ms-wakeWord').value.trim() || '大肥鱼'
2120
+ const taskCwd = val('#ms-taskCwd').value.trim()
2121
+ const voiceEnabled = val('#ms-voiceEnabled').checked
2122
+ const voiceWakeAutoStart = val('#ms-voiceWakeAutoStart').checked
2123
+ const voiceSilenceMs = number('#ms-voiceSilenceMs', CONFIG.voiceSilenceMs, 300, 5000)
2124
+ const voiceAutoSend = val('#ms-voiceAutoSend').checked
2125
+ const voiceAutoRecord = val('#ms-voiceAutoRecord').checked
2126
+ const bubbleStates = parseList(val('#ms-bubbleStates').value)
2127
+ const finalEnabledActions = enabledActions.length === ACTS.length ? [] : enabledActions.slice()
2128
+ const finalActionOrder = actionOrder.slice()
2129
+ Object.assign(CONFIG, {
2130
+ petSize, moveChance, actionDelayMs, playbackRate, activityLevel,
2131
+ reducedMotion, walkEnabled, workMinutes, breakMinutes, roastEnabled,
2132
+ holidayEnabled,
2133
+ wakeWord,
2134
+ taskCwd,
2135
+ voiceEnabled,
2136
+ voiceWakeAutoStart,
2137
+ voiceSilenceMs,
2138
+ voiceAutoSend,
2139
+ voiceAutoRecord,
2140
+ bubbleMode, bubbleStates, enabledActions: finalEnabledActions, actionOrder: finalActionOrder,
2141
+ })
2142
+ if (!voiceEnabled && wakeWordEnabled) {
2143
+ window.petBridge.toggleWakeWord()
2144
+ wakeWordEnabled = false
2145
+ }
2146
+ for (const video of [videoA, videoB]) {
2147
+ if (video) video.playbackRate = playbackRate
2148
+ }
2149
+ applySize()
2150
+ window.petBridge.saveConfig({
2151
+ petSize, moveChance, actionDelayMs, playbackRate, activityLevel,
2152
+ reducedMotion, walkEnabled, workMinutes, breakMinutes, roastEnabled,
2153
+ holidayEnabled,
2154
+ wakeWord,
2155
+ taskCwd,
2156
+ voiceEnabled,
2157
+ voiceWakeAutoStart,
2158
+ voiceSilenceMs,
2159
+ voiceAutoSend,
2160
+ voiceAutoRecord,
2161
+ bubbleMode, bubbleStates, enabledActions: finalEnabledActions, actionOrder: finalActionOrder,
2162
+ })
2163
+ window.petBridge.setWakeWord(wakeWord)
2164
+ if (holidayEnabled) maybeAutoPlayFestival()
2165
+ menuPage = 'main'
2166
+ showMenu(lastMenuPos.x, lastMenuPos.y)
2167
+ })
2168
+ addMenuButton('返回', () => {
2169
+ menuPage = 'main'
2170
+ showMenu(lastMenuPos.x, lastMenuPos.y)
2171
+ })
2172
+ }
2173
+
2174
+ function renderFeatureSettings() {
2175
+ addMenuButton('← 返回设置', () => {
2176
+ menuPage = 'settings'
2177
+ showMenu(lastMenuPos.x, lastMenuPos.y)
2178
+ })
2179
+ const toggleButton = (label, current, onToggle) => {
2180
+ addMenuButton(`${label}:${current ? '开' : '关'}`, () => {
2181
+ onToggle(!current)
2182
+ menuPage = 'features'
2183
+ showMenu(lastMenuPos.x, lastMenuPos.y)
2184
+ })
2185
+ }
2186
+ toggleButton('自动吐槽', CONFIG.roastEnabled === true, (next) => {
2187
+ CONFIG.roastEnabled = next
2188
+ window.petBridge.saveConfig({ roastEnabled: next })
2189
+ })
2190
+ toggleButton('节日祝福', CONFIG.holidayEnabled === true, (next) => {
2191
+ CONFIG.holidayEnabled = next
2192
+ window.petBridge.saveConfig({ holidayEnabled: next })
2193
+ if (next) maybeAutoPlayFestival()
2194
+ })
2195
+ toggleButton('允许行走', CONFIG.walkEnabled !== false, (next) => {
2196
+ CONFIG.walkEnabled = next
2197
+ window.petBridge.saveConfig({ walkEnabled: next })
2198
+ })
2199
+ toggleButton('减少动态效果', CONFIG.reducedMotion === true, (next) => {
2200
+ CONFIG.reducedMotion = next
2201
+ window.petBridge.saveConfig({ reducedMotion: next })
2202
+ })
2203
+ addMenuButton('返回', () => {
2204
+ menuPage = 'settings'
2205
+ showMenu(lastMenuPos.x, lastMenuPos.y)
2206
+ })
2207
+ }
2208
+
2209
+ function renderMainMenu() {
2210
+ renderEmotionBars(menuEl)
2211
+ addMenuButton('喂食', () => {
2212
+ menuEl.classList.remove('visible')
2213
+ updateClickThrough()
2214
+ feedPet()
2215
+ })
2216
+ addMenuButton(`开始番茄钟 ${CONFIG.workMinutes}分`, () => {
2217
+ menuEl.classList.remove('visible')
2218
+ updateClickThrough()
2219
+ startPomodoro('work', CONFIG.workMinutes)
2220
+ })
2221
+ addMenuButton(`开始短休息 ${CONFIG.breakMinutes}分`, () => {
2222
+ menuEl.classList.remove('visible')
2223
+ updateClickThrough()
2224
+ startPomodoro('break', CONFIG.breakMinutes)
2225
+ })
2226
+ if (pomodoro) {
2227
+ addMenuButton('停止番茄钟', () => {
2228
+ menuEl.classList.remove('visible')
2229
+ updateClickThrough()
2230
+ stopPomodoro()
2231
+ })
2232
+ }
2233
+ addMenuButton('让大肥鱼吐槽一下', () => {
2234
+ menuEl.classList.remove('visible')
2235
+ updateClickThrough()
2236
+ window.petBridge.requestRoast()
2237
+ })
2238
+ if (CONFIG.voiceEnabled !== false) {
2239
+ addMenuButton('语音控制', () => {
2240
+ menuEl.classList.remove('visible')
2241
+ updateClickThrough()
2242
+ showManualBubble('我在听…请说指令', '例如:开始番茄钟 / 喂食 / 余额', 4000)
2243
+ window.petBridge.startVoice()
2244
+ })
2245
+ addMenuButton(wakeWordEnabled ? '关闭语音唤醒' : '开启语音唤醒', () => {
2246
+ menuEl.classList.remove('visible')
2247
+ updateClickThrough()
2248
+ window.petBridge.toggleWakeWord()
2249
+ showManualBubble(
2250
+ wakeWordEnabled ? '语音唤醒已关闭' : '语音唤醒已开启',
2251
+ wakeWordEnabled ? '' : '说“大肥鱼+指令”,例如:大肥鱼开始番茄钟',
2252
+ 3000,
2253
+ )
2254
+ })
2255
+ }
2256
+ addMenuButton('闲聊', (event) => {
2257
+ event.stopPropagation()
2258
+ menuEl.classList.remove('visible')
2259
+ updateClickThrough()
2260
+ openChat()
2261
+ })
2262
+ addMenuButton('检查更新', () => {
2263
+ menuEl.classList.remove('visible')
2264
+ updateClickThrough()
2265
+ showManualBubble('正在检查更新…', '', 2000)
2266
+ window.petBridge.checkUpdate()
2267
+ })
2268
+ addMenuButton('设置…', () => {
2269
+ menuPage = 'settings'
2270
+ showMenu(lastMenuPos.x, lastMenuPos.y)
2271
+ })
2272
+ addMenuButton('本次隐藏', () => {
2273
+ menuEl.classList.remove('visible')
2274
+ updateClickThrough()
2275
+ window.petBridge.hide()
2276
+ })
2277
+ addMenuButton('本次关闭', () => {
2278
+ menuEl.classList.remove('visible')
2279
+ updateClickThrough()
2280
+ window.petBridge.close('user')
2281
+ })
2282
+ }
2283
+
2284
+ function renderPomodoroSettings() {
2285
+ addMenuButton('← 返回设置', () => {
2286
+ menuPage = 'settings'
2287
+ showMenu(lastMenuPos.x, lastMenuPos.y)
2288
+ })
2289
+ const workInput = document.createElement('input')
2290
+ workInput.type = 'number'
2291
+ workInput.min = 1
2292
+ workInput.max = 120
2293
+ workInput.value = String(CONFIG.workMinutes)
2294
+ workInput.style.width = '80px'
2295
+
2296
+ const breakInput = document.createElement('input')
2297
+ breakInput.type = 'number'
2298
+ breakInput.min = 1
2299
+ breakInput.max = 60
2300
+ breakInput.value = String(CONFIG.breakMinutes)
2301
+ breakInput.style.width = '80px'
2302
+
2303
+ const workRow = document.createElement('div')
2304
+ workRow.style.cssText = 'display:flex;justify-content:space-between;align-items:center;gap:8px;padding:4px 0'
2305
+ workRow.append('工作时长(分)', workInput)
2306
+
2307
+ const breakRow = document.createElement('div')
2308
+ breakRow.style.cssText = 'display:flex;justify-content:space-between;align-items:center;gap:8px;padding:4px 0'
2309
+ breakRow.append('休息时长(分)', breakInput)
2310
+
2311
+ menuEl.append(workRow, breakRow)
2312
+
2313
+ addMenuButton('保存', () => {
2314
+ const work = Math.min(120, Math.max(1, Number(workInput.value) || 25))
2315
+ const rest = Math.min(60, Math.max(1, Number(breakInput.value) || 5))
2316
+ CONFIG.workMinutes = work
2317
+ CONFIG.breakMinutes = rest
2318
+ window.petBridge.saveConfig({ workMinutes: work, breakMinutes: rest })
2319
+ menuPage = 'main'
2320
+ menuEl.classList.remove('visible')
2321
+ updateClickThrough()
2322
+ updateBubble()
2323
+ })
2324
+ addMenuButton('返回', () => {
2325
+ menuPage = 'settings'
2326
+ showMenu(lastMenuPos.x, lastMenuPos.y)
2327
+ })
2328
+ }
2329
+
2330
+ function renderAppearanceSettings() {
2331
+ addMenuButton('← 返回设置', () => {
2332
+ menuPage = 'settings'
2333
+ showMenu(lastMenuPos.x, lastMenuPos.y)
2334
+ })
2335
+
2336
+ const sizeInput = document.createElement('input')
2337
+ sizeInput.type = 'number'
2338
+ sizeInput.min = 100
2339
+ sizeInput.max = 1000
2340
+ sizeInput.step = 10
2341
+ sizeInput.value = String(CONFIG.petSize)
2342
+ sizeInput.style.width = '80px'
2343
+
2344
+ const moveInput = document.createElement('input')
2345
+ moveInput.type = 'range'
2346
+ moveInput.min = 0
2347
+ moveInput.max = 100
2348
+ moveInput.step = 1
2349
+ moveInput.value = String(CONFIG.moveChance)
2350
+ moveInput.style.width = '120px'
2351
+
2352
+ const delayInput = document.createElement('input')
2353
+ delayInput.type = 'range'
2354
+ delayInput.min = 0
2355
+ delayInput.max = 5000
2356
+ delayInput.step = 100
2357
+ delayInput.value = String(CONFIG.actionDelayMs)
2358
+ delayInput.style.width = '120px'
2359
+
2360
+ const speedInput = document.createElement('input')
2361
+ speedInput.type = 'range'
2362
+ speedInput.min = 1
2363
+ speedInput.max = 2
2364
+ speedInput.step = 0.1
2365
+ speedInput.value = String(CONFIG.playbackRate)
2366
+ speedInput.style.width = '120px'
2367
+
2368
+ const row = (label, input, hint) => {
2369
+ const div = document.createElement('div')
2370
+ div.style.cssText = 'display:flex;justify-content:space-between;align-items:center;gap:8px;padding:4px 0;font-size:12px'
2371
+ const left = document.createElement('span')
2372
+ left.textContent = label
2373
+ div.append(left, input)
2374
+ if (hint) {
2375
+ const small = document.createElement('small')
2376
+ small.textContent = hint
2377
+ small.style.cssText = 'display:block;opacity:.65;font-size:11px'
2378
+ div.appendChild(small)
2379
+ }
2380
+ return div
2381
+ }
2382
+
2383
+ menuEl.append(
2384
+ row('宠物宽度(px)', sizeInput, '重启后生效'),
2385
+ row(`移动频繁度 ${moveInput.value}%`, moveInput),
2386
+ row(`动作切换间隔 ${delayInput.value}ms`, delayInput),
2387
+ row(`播放速度 ${speedInput.value}x`, speedInput),
2388
+ )
2389
+ moveInput.addEventListener('input', () => {
2390
+ const label = moveInput.parentElement
2391
+ label.firstChild.textContent = `移动频繁度 ${moveInput.value}%`
2392
+ })
2393
+ delayInput.addEventListener('input', () => {
2394
+ const label = delayInput.parentElement
2395
+ label.firstChild.textContent = `动作切换间隔 ${delayInput.value}ms`
2396
+ })
2397
+ speedInput.addEventListener('input', () => {
2398
+ const label = speedInput.parentElement
2399
+ label.firstChild.textContent = `播放速度 ${speedInput.value}x`
2400
+ })
2401
+
2402
+ addMenuButton('保存', () => {
2403
+ CONFIG.petSize = Math.min(1000, Math.max(100, Math.round(Number(sizeInput.value) / 10) * 10 || 460))
2404
+ CONFIG.moveChance = Math.min(100, Math.max(0, Number(moveInput.value) || 0))
2405
+ CONFIG.actionDelayMs = Math.min(5000, Math.max(0, Number(delayInput.value) || 0))
2406
+ CONFIG.playbackRate = Math.min(2, Math.max(1, Number(speedInput.value) || 1))
2407
+ for (const video of [videoA, videoB]) {
2408
+ if (video) video.playbackRate = CONFIG.playbackRate
2409
+ }
2410
+ window.petBridge.saveConfig({
2411
+ petSize: CONFIG.petSize,
2412
+ moveChance: CONFIG.moveChance,
2413
+ actionDelayMs: CONFIG.actionDelayMs,
2414
+ playbackRate: CONFIG.playbackRate,
2415
+ })
2416
+ menuPage = 'main'
2417
+ menuEl.classList.remove('visible')
2418
+ updateClickThrough()
2419
+ })
2420
+ addMenuButton('返回', () => {
2421
+ menuPage = 'settings'
2422
+ showMenu(lastMenuPos.x, lastMenuPos.y)
2423
+ })
2424
+ }
2425
+
2426
+ function renderActionSettings() {
2427
+ // 空数组 = 全部动作,所以 UI 里初始化为全选。
2428
+ addMenuButton('← 返回设置', () => {
2429
+ menuPage = 'settings'
2430
+ showMenu(lastMenuPos.x, lastMenuPos.y)
2431
+ })
2432
+ const working = CONFIG.enabledActions.length > 0 ? CONFIG.enabledActions.slice() : ACTS.slice()
2433
+ const list = document.createElement('div')
2434
+ list.style.cssText = 'max-height:70vh;overflow-y:auto;margin:4px 0'
2435
+
2436
+ const addToggle = (name) => {
2437
+ const label = document.createElement('label')
2438
+ label.style.cssText = 'display:flex;align-items:center;gap:6px;padding:2px 0;font-size:12px;cursor:pointer'
2439
+ const checkbox = document.createElement('input')
2440
+ checkbox.type = 'checkbox'
2441
+ checkbox.checked = working.includes(name)
2442
+ checkbox.addEventListener('change', () => {
2443
+ if (checkbox.checked) {
2444
+ if (!working.includes(name)) working.push(name)
2445
+ } else {
2446
+ const index = working.indexOf(name)
2447
+ if (index >= 0) working.splice(index, 1)
2448
+ }
2449
+ })
2450
+ label.append(checkbox, name)
2451
+ list.appendChild(label)
2452
+ }
2453
+
2454
+ ACTS.forEach(addToggle)
2455
+ menuEl.append(list)
2456
+
2457
+ addMenuButton('全部动作', () => {
2458
+ working.length = 0
2459
+ working.push(...ACTS)
2460
+ for (const input of list.querySelectorAll('input')) input.checked = true
2461
+ })
2462
+ addMenuButton('保存', () => {
2463
+ // 全选时保存空数组 = 全部动作;否则保存勾选子集。
2464
+ const next = working.length === ACTS.length ? [] : working.slice()
2465
+ CONFIG.enabledActions = next
2466
+ window.petBridge.saveConfig({ enabledActions: next })
2467
+ menuPage = 'main'
2468
+ menuEl.classList.remove('visible')
2469
+ updateClickThrough()
2470
+ })
2471
+ addMenuButton('返回', () => {
2472
+ menuPage = 'settings'
2473
+ showMenu(lastMenuPos.x, lastMenuPos.y)
2474
+ })
2475
+ }
2476
+
2477
+ function renderActionFlyoutContent(panel) {
2478
+ panel.innerHTML = ''
2479
+ const working = CONFIG.enabledActions.length > 0 ? CONFIG.enabledActions.slice() : ACTS.slice()
2480
+ const list = document.createElement('div')
2481
+ list.style.cssText = 'max-height:60vh;overflow-y:auto;margin:2px 0'
2482
+ ACTS.forEach((name) => {
2483
+ const label = document.createElement('label')
2484
+ label.style.cssText = 'display:flex;align-items:center;gap:6px;padding:2px 0;font-size:12px;cursor:pointer'
2485
+ const checkbox = document.createElement('input')
2486
+ checkbox.type = 'checkbox'
2487
+ checkbox.checked = working.includes(name)
2488
+ checkbox.addEventListener('change', () => {
2489
+ if (checkbox.checked) {
2490
+ if (!working.includes(name)) working.push(name)
2491
+ } else {
2492
+ const index = working.indexOf(name)
2493
+ if (index >= 0) working.splice(index, 1)
2494
+ }
2495
+ })
2496
+ label.append(checkbox, name)
2497
+ list.appendChild(label)
2498
+ })
2499
+ panel.appendChild(list)
2500
+
2501
+ const row = document.createElement('div')
2502
+ row.style.cssText = 'display:flex;gap:6px;margin-top:4px'
2503
+ const allBtn = document.createElement('button')
2504
+ allBtn.textContent = '全部动作'
2505
+ allBtn.addEventListener('click', () => {
2506
+ working.length = 0
2507
+ working.push(...ACTS)
2508
+ for (const input of panel.querySelectorAll('input')) input.checked = true
2509
+ })
2510
+ const saveBtn = document.createElement('button')
2511
+ saveBtn.textContent = '保存'
2512
+ saveBtn.addEventListener('click', () => {
2513
+ const next = working.length === ACTS.length ? [] : working.slice()
2514
+ CONFIG.enabledActions = next
2515
+ window.petBridge.saveConfig({ enabledActions: next })
2516
+ panel.style.display = 'none'
2517
+ })
2518
+ const closeBtn = document.createElement('button')
2519
+ closeBtn.textContent = '关闭'
2520
+ closeBtn.addEventListener('click', () => {
2521
+ panel.style.display = 'none'
2522
+ })
2523
+ row.append(allBtn, saveBtn, closeBtn)
2524
+ panel.appendChild(row)
2525
+ }
2526
+
2527
+ document.addEventListener('click', (e) => {
2528
+ if (settingsPanel.classList.contains('visible')) {
2529
+ if (!settingsPanel.contains(e.target)) closeSettings()
2530
+ return
2531
+ }
2532
+ if (chatPanel.classList.contains('visible')) {
2533
+ if (!chatPanel.contains(e.target)) closeChat()
2534
+ return
2535
+ }
2536
+ if (!menuEl.contains(e.target)) {
2537
+ menuEl.classList.remove('visible')
2538
+ updateClickThrough()
2539
+ }
2540
+ })
2541
+
2542
+ // ---------- 状态订阅 ----------
2543
+ function applyStatus(incoming) {
2544
+ if (!incoming || typeof incoming !== 'object') return
2545
+
2546
+ if (incoming.config) {
2547
+ CONFIG.enabled = incoming.config.enabled !== false
2548
+ CONFIG.bubbleMode = incoming.config.bubbleMode || CONFIG.bubbleMode
2549
+ CONFIG.bubbleStates = Array.isArray(incoming.config.bubbleStates) ? incoming.config.bubbleStates : CONFIG.bubbleStates
2550
+ CONFIG.reducedMotion = incoming.config.reducedMotion === true
2551
+ CONFIG.activityLevel = incoming.config.activityLevel || CONFIG.activityLevel
2552
+ CONFIG.bubbleScale = Number(incoming.config.bubbleScale || CONFIG.bubbleScale)
2553
+ CONFIG.workMinutes = Number(incoming.config.workMinutes) || CONFIG.workMinutes
2554
+ CONFIG.breakMinutes = Number(incoming.config.breakMinutes) || CONFIG.breakMinutes
2555
+ CONFIG.roastEnabled = incoming.config.roastEnabled === true
2556
+ CONFIG.walkEnabled = incoming.config.walkEnabled !== false
2557
+ CONFIG.enabledActions = Array.isArray(incoming.config.enabledActions) ? incoming.config.enabledActions : []
2558
+ CONFIG.actionOrder = Array.isArray(incoming.config.actionOrder) ? incoming.config.actionOrder : []
2559
+ CONFIG.petSize = Number(incoming.config.petSize) || CONFIG.petSize
2560
+ CONFIG.moveChance = Number(incoming.config.moveChance) ?? CONFIG.moveChance
2561
+ CONFIG.actionDelayMs = Number(incoming.config.actionDelayMs) ?? CONFIG.actionDelayMs
2562
+ CONFIG.playbackRate = Number(incoming.config.playbackRate) || CONFIG.playbackRate
2563
+ CONFIG.voiceEnabled = incoming.config.voiceEnabled !== false
2564
+ CONFIG.voiceWakeAutoStart = incoming.config.voiceWakeAutoStart === true
2565
+ CONFIG.voiceSilenceMs = Number(incoming.config.voiceSilenceMs) ?? CONFIG.voiceSilenceMs
2566
+ CONFIG.voiceAutoSend = incoming.config.voiceAutoSend !== false
2567
+ CONFIG.voiceAutoRecord = incoming.config.voiceAutoRecord !== false
2568
+ CONFIG.holidayEnabled = incoming.config.holidayEnabled === true
2569
+ CONFIG.wakeWord = incoming.config.wakeWord || CONFIG.wakeWord
2570
+ CONFIG.taskCwd = incoming.config.taskCwd || CONFIG.taskCwd
2571
+ CONFIG.scale = Number(incoming.config.scale) || CONFIG.scale
2572
+ if (!CONFIG.holidayEnabled) stopFestivalPlayback()
2573
+ // 播放速度变化立即作用到当前/备用视频。
2574
+ for (const video of [videoA, videoB]) {
2575
+ if (video && !video.paused) video.playbackRate = CONFIG.playbackRate
2576
+ }
2577
+ applySize()
2578
+ if (!incoming.festivalPlay) maybeAutoPlayFestival()
2579
+ }
2580
+
2581
+ if (incoming.festivalPlay) {
2582
+ const playRequestToken = incoming.festivalPlay.token
2583
+ || `${incoming.festivalPlay.festivalId || ''}:${incoming.festivalPlay.requestedAt || ''}`
2584
+ if (playRequestToken && playRequestToken !== lastFestivalPlayToken) {
2585
+ const festival = incoming.festivalPlay.festivalId
2586
+ ? getFestivalById(incoming.festivalPlay.festivalId)
2587
+ : getTodayFestival()
2588
+ if (festival && playFestivalGreeting(festival)) {
2589
+ lastFestivalPlayToken = playRequestToken
2590
+ }
2591
+ }
2592
+ }
2593
+
2594
+ if (incoming.tokenUsage) {
2595
+ tokenUsage = {
2596
+ inputTokens: Number(incoming.tokenUsage.inputTokens) || 0,
2597
+ outputTokens: Number(incoming.tokenUsage.outputTokens) || 0,
2598
+ totalTokens: Number(incoming.tokenUsage.totalTokens) || 0,
2599
+ }
2600
+ }
2601
+
2602
+ if (incoming.balance) {
2603
+ balance = {
2604
+ currency: incoming.balance.currency || 'CNY',
2605
+ total: incoming.balance.total,
2606
+ granted: incoming.balance.granted,
2607
+ toppedUp: incoming.balance.toppedUp,
2608
+ isAvailable: incoming.balance.isAvailable !== false,
2609
+ updatedAt: incoming.balance.updatedAt,
2610
+ }
2611
+ } else if (incoming.balance === null) {
2612
+ balance = null
2613
+ }
2614
+
2615
+ if (incoming.roast && incoming.roast !== lastRoast) {
2616
+ roast = incoming.roast
2617
+ lastRoast = incoming.roast
2618
+ showManualBubble(roast, '大肥鱼吐槽time~', 5000)
2619
+ }
2620
+
2621
+ if (incoming.pulse) {
2622
+ // 同一个脉冲持续轮询时不要反复重播动画。
2623
+ const pulseKey = `${incoming.pulse.state}:${incoming.pulse.expiresAt || incoming.pulse.ttlMs || 1800}`
2624
+ if (lastPulseKey === pulseKey) {
2625
+ if (overlay) {
2626
+ overlay.message = incoming.pulse.message || overlay.message
2627
+ overlay.detail = incoming.pulse.detail || overlay.detail
2628
+ }
2629
+ updateBubble()
2630
+ return
2631
+ }
2632
+ applyPulseMessage(incoming.pulse)
2633
+ return
2634
+ }
2635
+
2636
+ if (incoming.tasks && incoming.tasks.length >= 2) {
2637
+ tasks = incoming.tasks
2638
+ } else if (incoming.tasks) {
2639
+ tasks = incoming.tasks
2640
+ }
2641
+
2642
+ const nextState = incoming.state || 'IDLE'
2643
+ if (nextState !== currentState) {
2644
+ applyStateMessage({
2645
+ state: nextState,
2646
+ message: incoming.message,
2647
+ detail: incoming.detail,
2648
+ project: incoming.project,
2649
+ task: incoming.task,
2650
+ progress: incoming.progress,
2651
+ })
2652
+ } else {
2653
+ // 状态没变:只更新气泡文案/任务信息,不打断当前动画。
2654
+ status = {
2655
+ ...status,
2656
+ state: nextState,
2657
+ message: incoming.message ?? status.message,
2658
+ detail: incoming.detail ?? status.detail,
2659
+ project: incoming.project ?? status.project,
2660
+ task: incoming.task ?? status.task,
2661
+ progress: incoming.progress ?? status.progress,
2662
+ }
2663
+ updateBubble()
2664
+ }
2665
+ }
2666
+
2667
+ async function handleVoiceCommand(text) {
2668
+ const command = String(text || '').trim()
2669
+ if (!command) {
2670
+ showManualBubble('没听清,再说一次吧~', '', 2500)
2671
+ return
2672
+ }
2673
+ // 闲聊框打开时,只说“大肥鱼”就自动开始录音(可关闭)
2674
+ const wake = CONFIG.wakeWord || '大肥鱼'
2675
+ if (CONFIG.voiceAutoRecord !== false && (command === wake || command === `嗨${wake}`) && chatPanel.classList.contains('visible')) {
2676
+ if (!senseRecording) {
2677
+ showManualBubble('我在,请说~', '', 1500)
2678
+ try {
2679
+ await startSenseRecording()
2680
+ } catch {
2681
+ if (chatAppendMsg) chatAppendMsg('pet', '录音不可用,请点击 🎤 重试~')
2682
+ }
2683
+ }
2684
+ return
2685
+ }
2686
+ if (command.includes('在吗') || command.includes('在不在') || command.includes('出来')) {
2687
+ showManualBubble('我在呀~', '', 1500)
2688
+ openChat()
2689
+ if (CONFIG.voiceAutoRecord !== false && CONFIG.voiceEnabled !== false && !senseRecording) {
2690
+ setTimeout(async () => {
2691
+ try {
2692
+ await startSenseRecording()
2693
+ if (chatAppendMsg) chatAppendMsg('pet', '我在,请说~')
2694
+ } catch {
2695
+ if (chatAppendMsg) chatAppendMsg('pet', '录音不可用,请点击 🎤 重试~')
2696
+ }
2697
+ }, 600)
2698
+ }
2699
+ return
2700
+ }
2701
+ if (command.includes('开始') && command.includes('番茄钟')) {
2702
+ startPomodoro('work', CONFIG.workMinutes)
2703
+ showManualBubble('收到,开始番茄钟~', `${CONFIG.workMinutes} 分钟`, 3000)
2704
+ } else if (command.includes('休息')) {
2705
+ startPomodoro('break', CONFIG.breakMinutes)
2706
+ showManualBubble('收到,开始休息~', `${CONFIG.breakMinutes} 分钟`, 3000)
2707
+ } else if (command.includes('停止') && command.includes('番茄钟')) {
2708
+ stopPomodoro()
2709
+ showManualBubble('番茄钟已停止~', '', 2500)
2710
+ } else if (command.includes('喂食')) {
2711
+ feedPet()
2712
+ } else if (command.includes('隐藏')) {
2713
+ window.petBridge.hide()
2714
+ } else if (command.includes('关闭')) {
2715
+ window.petBridge.close('user')
2716
+ } else if (command.includes('余额')) {
2717
+ window.petBridge.refreshBalance()
2718
+ showManualBubble('正在刷新余额~', '', 2000)
2719
+ } else if (command.includes('吐槽')) {
2720
+ window.petBridge.requestRoast()
2721
+ } else if (command.includes('设置')) {
2722
+ menuPage = 'settings'
2723
+ showMenu(lastMenuPos.x, lastMenuPos.y)
2724
+ } else {
2725
+ showManualBubble(`你说的是“${command}”?我还没学会~`, '', 3000)
2726
+ }
2727
+ }
2728
+
2729
+ function handleUpdateResult(result) {
2730
+ if (!result) return
2731
+ if (result.error) {
2732
+ showManualBubble('检查更新失败', result.error, 3000)
2733
+ return
2734
+ }
2735
+ if (result.hasUpdate) {
2736
+ showManualBubble(`发现新版本 ${result.latest}`, `当前 ${result.current},为你打开更新页`, 5000)
2737
+ window.petBridge.openWebUi('https://github.com/ysppwn721/better-dsh-pet/releases')
2738
+ } else {
2739
+ showManualBubble('已是最新版本', `当前 ${result.current}`, 3000)
2740
+ }
2741
+ }
2742
+
2743
+ window.petBridge.onStatus((status) => {
2744
+ applyStatus(status)
2745
+ })
2746
+
2747
+ window.petBridge.onVoiceResult(handleVoiceCommand)
2748
+ window.petBridge.onDictationResult(handleDictationResult)
2749
+ window.petBridge.onUpdateResult(handleUpdateResult)
2750
+ window.petBridge.onWakeState((enabled) => {
2751
+ wakeWordEnabled = enabled
2752
+ })
2753
+
2754
+ // ---------- 启动 ----------
2755
+ loadEmotion()
2756
+ if (CONFIG.voiceEnabled !== false && CONFIG.voiceWakeAutoStart && !wakeWordEnabled) {
2757
+ window.petBridge.toggleWakeWord()
2758
+ wakeWordEnabled = true
2759
+ }
2760
+ playIdle()
2761
+ updateBubble()
2762
+ updateClickThrough()
2763
+ maybeAutoPlayFestival()
2764
+
2765
+ // 情绪缓慢变化:空闲会越来越无聊/疲惫,工作会消耗精力。
2766
+ setInterval(() => {
2767
+ if (currentState === 'IDLE') {
2768
+ updateEmotion({ mood: -1, energy: -1, anxiety: -1, boredom: 2 })
2769
+ } else if (currentState === 'WORKING' || currentState === 'THINKING') {
2770
+ updateEmotion({ energy: -1, boredom: -1 })
2771
+ } else if (currentState === 'WAITING') {
2772
+ updateEmotion({ anxiety: 1, boredom: 1 })
2773
+ }
2774
+ }, 10000)
2775
+
2776
+ setInterval(() => {
2777
+ if (CONFIG.holidayEnabled) maybeAutoPlayFestival()
2778
+ }, 60 * 1000)
2779
+
2780
+ // 看门狗:万一 video 的 ended 事件或 loop 没有按预期工作,这里兜底,
2781
+ // 避免宠物停在最后一帧。
2782
+ setInterval(() => {
2783
+ if (pending) return
2784
+ const el = currentVideo()
2785
+ if (!el || !el.ended) return
2786
+ if (animLoop) {
2787
+ el.currentTime = 0
2788
+ el.play().catch(() => {})
2789
+ } else if (!dragging && !dragState.active) {
2790
+ handleEnded()
2791
+ }
2792
+ }, 500)