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,218 +1,752 @@
1
- /**
2
- * better-dsh-pet desktop helper —— Electron 主进程
3
- *
4
- * 不再依赖 stdin 协议(Windows 下 Electron GUI 进程的 stdin 不可靠),
5
- * 改为轮询 DSH 宿主暴露的 /plugins/better-dsh-pet/status HTTP 端点,
6
- * 把最新状态转发给透明置顶窗口内的 renderer。
7
- */
8
- const { app, BrowserWindow, ipcMain, screen, shell } = require('electron')
9
- const path = require('node:path')
10
- const { spawn } = require('node:child_process')
11
- const { existsSync } = require('node:fs')
12
-
13
- // 允许无用户手势直接播放 MP3 闹钟
14
- app.commandLine.appendSwitch('autoplay-policy', 'no-user-gesture-required')
15
-
16
- let mainWindow = null
17
- let pollTimer = null
18
-
19
- function setClickThrough(ignore) {
20
- if (mainWindow && !mainWindow.isDestroyed()) {
21
- mainWindow.setIgnoreMouseEvents(ignore === true, { forward: true })
22
- }
23
- }
24
-
25
- function resolveDesktopPath() {
26
- const candidates = [
27
- process.env.DSH_PET_DESKTOP_PATH,
28
- process.env.DSH_DESKTOP_PATH,
29
- 'D:\\deepseek harness\\DSH Desktop\\DSH Desktop.exe',
30
- 'D:/deepseek harness/DSH Desktop/DSH Desktop.exe',
31
- ].filter(Boolean)
32
- return candidates.find((candidate) => existsSync(candidate))
33
- }
34
-
35
- function openDesktop() {
36
- const desktopPath = resolveDesktopPath()
37
- if (!desktopPath) {
38
- console.error('[better-dsh-pet-helper] DSH Desktop executable not found')
39
- return
40
- }
41
- try {
42
- const child = spawn(desktopPath, [], {
43
- detached: true,
44
- stdio: 'ignore',
45
- windowsHide: false,
46
- })
47
- child.unref()
48
- } catch (error) {
49
- console.error('[better-dsh-pet-helper] failed to launch DSH Desktop:', error)
50
- }
51
- }
52
-
53
- function createWindow() {
54
- const scale = Number(process.env.DSH_PET_SCALE || '1')
55
- const bubbleScale = Number(process.env.DSH_PET_BUBBLE_SCALE || '1')
56
- // 使用主屏工作区作为透明画布,宠物在画布内自由移动,不移动窗口本身。
57
- const display = screen.getPrimaryDisplay()
58
- const area = display.workArea
59
- const width = area.width
60
- const height = area.height
61
-
62
- mainWindow = new BrowserWindow({
63
- width,
64
- height,
65
- x: area.x,
66
- y: area.y,
67
- show: false,
68
- useContentSize: true,
69
- transparent: true,
70
- frame: false,
71
- alwaysOnTop: true,
72
- skipTaskbar: true,
73
- resizable: false,
74
- hasShadow: false,
75
- webPreferences: {
76
- preload: path.join(__dirname, 'preload.js'),
77
- contextIsolation: true,
78
- nodeIntegration: false,
79
- sandbox: false,
80
- paintWhenInitiallyHidden: false,
81
- },
82
- })
83
-
84
- mainWindow.once('ready-to-show', () => {
85
- mainWindow.show()
86
- })
87
-
88
- mainWindow.setAlwaysOnTop(true, 'screen-saver')
89
- mainWindow.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true })
90
- setClickThrough(true)
91
-
92
- mainWindow.loadFile('index.html', {
93
- query: {
94
- scale: String(scale),
95
- bubbleScale: String(bubbleScale),
96
- activityLevel: process.env.DSH_PET_ACTIVITY_LEVEL || 'normal',
97
- reducedMotion: process.env.DSH_PET_REDUCED_MOTION === '1' ? '1' : '0',
98
- bubbleMode: process.env.DSH_PET_BUBBLE_MODE || 'always',
99
- bubbleStates: process.env.DSH_PET_BUBBLE_STATES || 'SUCCESS,ERROR,WAITING',
100
- webuiUrl: process.env.DSH_PET_WEBUI_URL || 'http://127.0.0.1:3080/',
101
- },
102
- }).then(() => {
103
- startPolling()
104
- }).catch((error) => {
105
- console.error('[better-dsh-pet-helper] page load failed:', error)
106
- app.quit()
107
- })
108
-
109
- mainWindow.on('closed', () => {
110
- mainWindow = null
111
- if (pollTimer) clearInterval(pollTimer)
112
- pollTimer = null
113
- })
114
- }
115
-
116
- async function notifyHostClosed() {
117
- const statusUrl = process.env.DSH_PET_STATUS_URL
118
- if (!statusUrl) return
119
- try {
120
- const closeUrl = statusUrl.replace(/\/plugins\/better-dsh-pet\/status$/, '/plugins/better-dsh-pet/close')
121
- await fetch(closeUrl, { method: 'POST', cache: 'no-store' })
122
- } catch {
123
- // 宿主不可达时无法通知,仍继续退出;宿主侧可能按崩溃重启处理。
124
- }
125
- }
126
-
127
- function startPolling() {
128
- const statusUrl = process.env.DSH_PET_STATUS_URL
129
- if (!statusUrl) {
130
- console.error('[better-dsh-pet-helper] DSH_PET_STATUS_URL is not set')
131
- return
132
- }
133
- const poll = async () => {
134
- if (!mainWindow || mainWindow.isDestroyed()) return
135
- try {
136
- const response = await fetch(statusUrl, { cache: 'no-store' })
137
- if (!response.ok) return
138
- const status = await response.json()
139
- if (mainWindow && !mainWindow.isDestroyed()) {
140
- mainWindow.webContents.send('pet:status', status)
141
- }
142
- } catch (error) {
143
- // DSH 尚未就绪或临时不可达时静默跳过,下个周期再试。
1
+ /**
2
+ * better-dsh-pet desktop helper —— Electron 主进程
3
+ *
4
+ * 不再依赖 stdin 协议(Windows 下 Electron GUI 进程的 stdin 不可靠),
5
+ * 改为轮询 DSH 宿主暴露的 /plugins/better-dsh-pet/status HTTP 端点,
6
+ * 把最新状态转发给透明置顶窗口内的 renderer。
7
+ */
8
+ const { app, BrowserWindow, ipcMain, screen, shell, Tray, Menu, nativeImage, session } = require('electron')
9
+ const path = require('node:path')
10
+ const { spawn, execFile } = require('node:child_process')
11
+ const { existsSync, readFileSync } = require('node:fs')
12
+
13
+ // 允许无用户手势直接播放 MP3 闹钟
14
+ app.commandLine.appendSwitch('autoplay-policy', 'no-user-gesture-required')
15
+
16
+ // 透明置顶全屏窗口在某些显卡/驱动下会干扰硬件视频叠加层,
17
+ // 导致 B 站等视频在拖拽桌宠或系统音量弹层出现时黑屏。
18
+ // 关闭本应用的硬件加速可避免这种合成冲突(桌宠是轻量 2D 动画,影响很小)。
19
+ app.disableHardwareAcceleration()
20
+
21
+ let mainWindow = null
22
+ let pollTimer = null
23
+ let tray = null
24
+ let userHidden = false
25
+ let fullscreenHidden = false
26
+ let fullscreenCheckTimer = null
27
+ let wakeWordProcess = null
28
+ let currentWakeWord = process.env.DSH_PET_WAKE_WORD || '大肥鱼'
29
+
30
+ function setClickThrough(ignore) {
31
+ if (mainWindow && !mainWindow.isDestroyed()) {
32
+ mainWindow.setIgnoreMouseEvents(ignore === true, { forward: true })
33
+ }
34
+ }
35
+
36
+ function resolveDesktopPath() {
37
+ const candidates = [
38
+ process.env.DSH_PET_DESKTOP_PATH,
39
+ process.env.DSH_DESKTOP_PATH,
40
+ process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, 'DeepSeek Harness', 'DSH Desktop', 'DSH Desktop.exe'),
41
+ process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, 'Programs', 'DeepSeek Harness', 'DSH Desktop', 'DSH Desktop.exe'),
42
+ process.env.ProgramFiles && path.join(process.env.ProgramFiles, 'DeepSeek Harness', 'DSH Desktop', 'DSH Desktop.exe'),
43
+ process.env.ProgramFiles && path.join(process.env.ProgramFiles, 'DSH Desktop', 'DSH Desktop.exe'),
44
+ 'D:\\deepseek harness\\DSH Desktop\\DSH Desktop.exe',
45
+ 'D:/deepseek harness/DSH Desktop/DSH Desktop.exe',
46
+ ].filter(Boolean)
47
+ return candidates.find((candidate) => existsSync(candidate))
48
+ }
49
+
50
+ function openDesktop() {
51
+ const desktopPath = resolveDesktopPath()
52
+ if (!desktopPath) {
53
+ console.error('[better-dsh-pet-helper] DSH Desktop executable not found')
54
+ return
55
+ }
56
+ try {
57
+ const child = spawn(desktopPath, [], {
58
+ detached: true,
59
+ stdio: 'ignore',
60
+ windowsHide: false,
61
+ })
62
+ child.unref()
63
+ } catch (error) {
64
+ console.error('[better-dsh-pet-helper] failed to launch DSH Desktop:', error)
65
+ }
66
+ }
67
+
68
+ function createTray() {
69
+ if (tray) return
70
+ const iconPath = path.join(__dirname, '..', '..', 'assets', 'tray-icon.png')
71
+ let icon = nativeImage.createFromPath(iconPath)
72
+ if (icon.isEmpty()) {
73
+ // 兜底:图标文件缺失时使用内置蓝色小圆点
74
+ icon = nativeImage.createFromDataURL('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAABKSURBVDhPzY6xDQAwCMN6Wo/tn3RjMLQiEgORPBFHrDUy+5i9YDeEQgYdD4s/6EpyOsJjhb4BHqr0fTBjQB2h62Exg04IBUlWcwH8iaT0f2HaowAAAABJRU5ErkJggg==')
75
+ }
76
+ tray = new Tray(icon)
77
+ tray.setToolTip('Better DSH Pet')
78
+ const toggleVisible = () => {
79
+ if (!mainWindow || mainWindow.isDestroyed()) return
80
+ if (mainWindow.isVisible()) {
81
+ mainWindow.hide()
82
+ userHidden = true
83
+ } else {
84
+ mainWindow.show()
85
+ userHidden = false
86
+ }
87
+ }
88
+ tray.setContextMenu(Menu.buildFromTemplate([
89
+ { label: '显示 / 隐藏桌宠', click: toggleVisible },
90
+ { type: 'separator' },
91
+ {
92
+ label: '退出',
93
+ click: () => {
94
+ void notifyHostClosed().finally(() => app.quit())
95
+ },
96
+ },
97
+ ]))
98
+ tray.on('click', toggleVisible)
99
+ }
100
+
101
+ // Windows 上资源管理器重启、分辨率/DPI 变化、休眠唤醒等可能让置顶丢失,
102
+ // 借鉴 dsh-pet-indesktop 的“置顶看门狗”:定期重新置顶。
103
+ function startTopmostWatchdog() {
104
+ const timer = setInterval(() => {
105
+ if (!mainWindow || mainWindow.isDestroyed()) return
106
+ mainWindow.setAlwaysOnTop(true, 'screen-saver')
107
+ }, 30000)
108
+ if (timer.unref) timer.unref()
109
+ if (mainWindow) {
110
+ mainWindow.on('show', () => {
111
+ mainWindow.setAlwaysOnTop(true, 'screen-saver')
112
+ })
113
+ }
114
+ }
115
+
116
+ // 全屏自动隐身:检测前台窗口是否铺满某块屏幕。
117
+ // 用 PowerShell 调 user32 拿前台窗口矩形,避免引入额外原生依赖。
118
+ function getForegroundWindowRect(callback) {
119
+ const script = `
120
+ Add-Type @"
121
+ using System;
122
+ using System.Runtime.InteropServices;
123
+ public class Win32Foreground {
124
+ [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
125
+ [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hWnd, out RECT rect);
126
+ [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hWnd);
127
+ [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);
128
+ public struct RECT { public int Left; public int Top; public int Right; public int Bottom; }
129
+ }
130
+ "@
131
+ $h = [Win32Foreground]::GetForegroundWindow()
132
+ if ($h -eq [IntPtr]::Zero) { 'none'; exit }
133
+ if (-not [Win32Foreground]::IsWindowVisible($h)) { 'none'; exit }
134
+ $r = New-Object Win32Foreground+RECT
135
+ [Win32Foreground]::GetWindowRect($h, [ref]$r) | Out-Null
136
+ $procId = 0
137
+ [Win32Foreground]::GetWindowThreadProcessId($h, [ref]$procId) | Out-Null
138
+ $proc = Get-Process -Id $procId -ErrorAction SilentlyContinue
139
+ $procName = if ($proc) { $proc.ProcessName } else { '' }
140
+ "$($r.Left),$($r.Top),$($r.Right),$($r.Bottom)|$procName"
141
+ `
142
+ execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], {
143
+ timeout: 3000,
144
+ windowsHide: true,
145
+ }, (error, stdout) => {
146
+ if (error) {
147
+ callback(null)
148
+ return
149
+ }
150
+ const text = String(stdout || '').trim()
151
+ if (!text || text === 'none') {
152
+ callback(null)
153
+ return
154
+ }
155
+ const [rectPart, processName = ''] = text.split('|')
156
+ const parts = rectPart.split(',').map((n) => Number(n.trim()))
157
+ if (parts.length !== 4 || parts.some((n) => !Number.isFinite(n))) {
158
+ callback(null)
159
+ return
160
+ }
161
+ callback({
162
+ x: parts[0],
163
+ y: parts[1],
164
+ width: parts[2] - parts[0],
165
+ height: parts[3] - parts[1],
166
+ processName: String(processName || '').trim().toLowerCase(),
167
+ })
168
+ })
169
+ }
170
+
171
+ function isFullscreenRect(rect) {
172
+ if (!rect) return false
173
+ const displays = screen.getAllDisplays()
174
+ return displays.some((display) => {
175
+ // 用 bounds(整个屏幕含任务栏区域)判断“真全屏”;
176
+ // 最大化窗口只覆盖 workArea,不应算全屏,避免 B 站 App 一打开就误藏桌宠。
177
+ const bounds = display.bounds
178
+ const tolerance = 2
179
+ return rect.x <= bounds.x + tolerance
180
+ && rect.y <= bounds.y + tolerance
181
+ && rect.x + rect.width >= bounds.x + bounds.width - tolerance
182
+ && rect.y + rect.height >= bounds.y + bounds.height - tolerance
183
+ })
184
+ }
185
+
186
+ // 只对“游戏全屏 / 视频全屏”自动隐藏,避免普通办公软件全屏也把桌宠藏起来。
187
+ const KEEP_VISIBLE_FULLSCREEN_PROCESSES = new Set([
188
+ 'explorer', 'code', 'devenv', 'winword', 'excel', 'powerpnt', 'onenote', 'outlook',
189
+ 'acrobat', 'acrord32', 'notepad', 'notepad++', 'windowsTerminal', 'mintty', 'obsidian',
190
+ 'typora', 'wechat', 'qq', 'dingtalk', 'feishu', 'slack', 'teams', 'zoom', 'wps', 'et', 'wpp',
191
+ 'dsh desktop', 'dsh',
192
+ ])
193
+ const BROWSER_PROCESSES = new Set([
194
+ 'chrome', 'msedge', 'firefox', 'opera', 'brave', 'vivaldi', 'chromium',
195
+ '360chrome', 'qqbrowser', 'sogouexplorer', 'ucbrowser', 'centbrowser', 'liebao',
196
+ ])
197
+ const MEDIA_PLAYER_PROCESSES = new Set([
198
+ 'potplayer', 'vlc', 'mpv', 'wmplayer', 'qqplayer', 'baofengplayer', 'kmplayer',
199
+ 'gplayer', 'dplayer', 'iina', 'mxplayer', 'loveplayer', 'stormplayer', 'foxplayer',
200
+ ])
201
+
202
+ function shouldAutoHideForProcess(processName) {
203
+ if (!processName) return true // 拿不到进程名时按“可能游戏/视频”处理
204
+ if (KEEP_VISIBLE_FULLSCREEN_PROCESSES.has(processName)) return false
205
+ if (BROWSER_PROCESSES.has(processName)) return true
206
+ if (MEDIA_PLAYER_PROCESSES.has(processName)) return true
207
+ // 其余未知全屏进程按游戏全屏处理(游戏进程名无法穷举)
208
+ return true
209
+ }
210
+
211
+ function checkFullscreenAndHide() {
212
+ if (!mainWindow || mainWindow.isDestroyed()) return
213
+ getForegroundWindowRect((rect) => {
214
+ if (!mainWindow || mainWindow.isDestroyed()) return
215
+ const fullscreen = isFullscreenRect(rect)
216
+ const shouldHide = fullscreen && shouldAutoHideForProcess(rect?.processName)
217
+ // 桌宠自己的窗口也是全屏透明画布,用户正在拖/点时不能把自己当成“全屏应用”藏起来。
218
+ const selfForeground = mainWindow.isFocused()
219
+ if (shouldHide && !fullscreenHidden && !selfForeground) {
220
+ fullscreenHidden = true
221
+ mainWindow.hide()
222
+ } else if (!fullscreen && fullscreenHidden && !userHidden) {
223
+ fullscreenHidden = false
224
+ mainWindow.show()
225
+ mainWindow.setAlwaysOnTop(true, 'screen-saver')
226
+ }
227
+ })
228
+ }
229
+
230
+ function startFullscreenWatchdog() {
231
+ checkFullscreenAndHide()
232
+ fullscreenCheckTimer = setInterval(checkFullscreenAndHide, 2000)
233
+ if (fullscreenCheckTimer.unref) fullscreenCheckTimer.unref()
234
+ }
235
+
236
+ function startVoiceRecognition(callback) {
237
+ const script = `
238
+ [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
239
+ Add-Type -AssemblyName System.Speech
240
+ try {
241
+ $culture = [System.Globalization.CultureInfo]::GetCultureInfo('zh-CN')
242
+ $recognizer = New-Object System.Speech.Recognition.SpeechRecognitionEngine($culture)
243
+ $recognizer.SetInputToDefaultAudioDevice()
244
+ $choices = New-Object System.Speech.Recognition.Choices
245
+ $choices.Add('开始番茄钟')
246
+ $choices.Add('开始休息')
247
+ $choices.Add('停止番茄钟')
248
+ $choices.Add('喂食')
249
+ $choices.Add('隐藏')
250
+ $choices.Add('关闭')
251
+ $choices.Add('余额')
252
+ $choices.Add('吐槽')
253
+ $choices.Add('设置')
254
+ $grammar = New-Object System.Speech.Recognition.Grammar($choices)
255
+ $recognizer.LoadGrammar($grammar)
256
+ $result = $recognizer.Recognize()
257
+ if ($result -ne $null) { $result.Text } else { '' }
258
+ } catch {
259
+ 'ERROR: ' + $_.Exception.Message
260
+ }
261
+ `
262
+ execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], {
263
+ timeout: 15000,
264
+ windowsHide: true,
265
+ encoding: 'utf8',
266
+ }, (error, stdout) => {
267
+ if (error) {
268
+ callback('')
269
+ return
270
+ }
271
+ const text = String(stdout || '').trim()
272
+ if (text.startsWith('ERROR:')) {
273
+ callback('')
274
+ return
275
+ }
276
+ callback(text)
277
+ })
278
+ }
279
+
280
+ function compareVersions(a, b) {
281
+ const pa = String(a || '').split('.').map((n) => Number(n) || 0)
282
+ const pb = String(b || '').split('.').map((n) => Number(n) || 0)
283
+ for (let i = 0; i < 3; i++) {
284
+ const x = pa[i] || 0
285
+ const y = pb[i] || 0
286
+ if (x !== y) return x < y ? -1 : 1
287
+ }
288
+ return 0
289
+ }
290
+
291
+ function checkForUpdate(callback) {
292
+ let current = '0.0.0'
293
+ try {
294
+ const pkg = JSON.parse(readFileSync(path.join(__dirname, '..', '..', 'package.json'), 'utf8'))
295
+ current = pkg.version || current
296
+ } catch {
297
+ // 读取失败时用 0.0.0
298
+ }
299
+ const registries = [
300
+ 'https://registry.npmjs.org/better-dsh-pet/latest',
301
+ 'https://registry.npmmirror.com/better-dsh-pet/latest',
302
+ ]
303
+ const tryFetch = async (index) => {
304
+ if (index >= registries.length) {
305
+ callback({ current, latest: current, hasUpdate: false, error: '无法连接更新服务器' })
306
+ return
307
+ }
308
+ try {
309
+ const controller = new AbortController()
310
+ const timer = setTimeout(() => controller.abort(), 8000)
311
+ const response = await fetch(registries[index], { signal: controller.signal })
312
+ clearTimeout(timer)
313
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
314
+ const data = await response.json()
315
+ const latest = data?.version || current
316
+ callback({ current, latest, hasUpdate: compareVersions(latest, current) > 0, error: '' })
317
+ } catch {
318
+ await tryFetch(index + 1)
319
+ }
320
+ }
321
+ void tryFetch(0)
322
+ }
323
+
324
+ function sendVoiceResult(text) {
325
+ if (mainWindow && !mainWindow.isDestroyed()) {
326
+ mainWindow.webContents.send('pet:voice-result', text || '')
327
+ }
328
+ }
329
+
330
+ function startVoiceDictation(callback) {
331
+ const script = `
332
+ [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
333
+ Add-Type -AssemblyName System.Speech
334
+ try {
335
+ $culture = [System.Globalization.CultureInfo]::GetCultureInfo('zh-CN')
336
+ $recognizer = New-Object System.Speech.Recognition.SpeechRecognitionEngine($culture)
337
+ $recognizer.SetInputToDefaultAudioDevice()
338
+ $recognizer.LoadGrammar((New-Object System.Speech.Recognition.DictationGrammar))
339
+ $result = $recognizer.Recognize()
340
+ if ($result -ne $null) { $result.Text } else { '' }
341
+ } catch {
342
+ 'ERROR: ' + $_.Exception.Message
343
+ }
344
+ `
345
+ execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], {
346
+ timeout: 15000,
347
+ windowsHide: true,
348
+ encoding: 'utf8',
349
+ }, (error, stdout) => {
350
+ if (error) {
351
+ callback('')
352
+ return
353
+ }
354
+ const text = String(stdout || '').trim()
355
+ if (text.startsWith('ERROR:')) {
356
+ callback('')
357
+ return
358
+ }
359
+ callback(text)
360
+ })
361
+ }
362
+
363
+ function speakText(text) {
364
+ const safeText = String(text || '').slice(0, 200)
365
+ if (!safeText) return
366
+ const script = `
367
+ Add-Type -AssemblyName System.Speech
368
+ try {
369
+ $synth = New-Object System.Speech.Synthesis.SpeechSynthesizer
370
+ $synth.Speak($env:DICT_TEXT)
371
+ } catch { }
372
+ `
373
+ execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], {
374
+ timeout: 15000,
375
+ windowsHide: true,
376
+ env: { ...process.env, DICT_TEXT: safeText },
377
+ }, () => {})
378
+ }
379
+
380
+ function sendVoiceResult(text) {
381
+ if (mainWindow && !mainWindow.isDestroyed()) {
382
+ mainWindow.webContents.send('pet:voice-result', text || '')
383
+ }
384
+ }
385
+
386
+ function startWakeWordListener() {
387
+ if (wakeWordProcess) return
388
+ const script = `
389
+ [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
390
+ Add-Type -AssemblyName System.Speech
391
+ try {
392
+ $culture = [System.Globalization.CultureInfo]::GetCultureInfo('zh-CN')
393
+ $recognizer = New-Object System.Speech.Recognition.SpeechRecognitionEngine($culture)
394
+ $recognizer.SetInputToDefaultAudioDevice()
395
+ $wake = $env:DSH_PET_WAKE_WORD
396
+ if (-not $wake) { $wake = '大肥鱼' }
397
+ $choices = New-Object System.Speech.Recognition.Choices
398
+ $choices.Add("\${wake}开始番茄钟")
399
+ $choices.Add("嗨\${wake}开始番茄钟")
400
+ $choices.Add("\${wake}开始休息")
401
+ $choices.Add("嗨\${wake}开始休息")
402
+ $choices.Add("\${wake}停止番茄钟")
403
+ $choices.Add("\${wake}喂食")
404
+ $choices.Add("\${wake}隐藏")
405
+ $choices.Add("\${wake}关闭")
406
+ $choices.Add("\${wake}余额")
407
+ $choices.Add("\${wake}吐槽")
408
+ $choices.Add("\${wake}设置")
409
+ $choices.Add("\${wake}你在吗")
410
+ $choices.Add("\${wake}在吗")
411
+ $choices.Add("嗨\${wake}你在吗")
412
+ $choices.Add("\${wake}出来")
413
+ $choices.Add("\${wake}")
414
+ $choices.Add("嗨\${wake}")
415
+ $grammar = New-Object System.Speech.Recognition.Grammar($choices)
416
+ $recognizer.LoadGrammar($grammar)
417
+ while ($true) {
418
+ $result = $recognizer.Recognize()
419
+ if ($result -ne $null) {
420
+ 'CMD:' + $result.Text
421
+ }
422
+ }
423
+ } catch {
424
+ 'ERROR: ' + $_.Exception.Message
425
+ }
426
+ `
427
+ const child = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], {
428
+ windowsHide: true,
429
+ env: { ...process.env, DSH_PET_WAKE_WORD: currentWakeWord },
430
+ })
431
+ let buffer = ''
432
+ child.stdout.on('data', (chunk) => {
433
+ buffer += chunk.toString('utf8')
434
+ const lines = buffer.split(/\r?\n/)
435
+ buffer = lines.pop() || ''
436
+ for (const line of lines) {
437
+ const text = line.trim()
438
+ if (text.startsWith('CMD:')) {
439
+ sendVoiceResult(text.slice(4))
440
+ } else if (text.startsWith('ERROR:')) {
441
+ stopWakeWordListener()
442
+ sendVoiceResult('')
443
+ }
444
+ }
445
+ })
446
+ child.on('exit', () => {
447
+ if (wakeWordProcess === child) wakeWordProcess = null
448
+ })
449
+ wakeWordProcess = child
450
+ }
451
+
452
+ function stopWakeWordListener() {
453
+ if (wakeWordProcess) {
454
+ wakeWordProcess.kill()
455
+ wakeWordProcess = null
456
+ }
457
+ }
458
+
459
+ function createWindow() {
460
+ const scale = Number(process.env.DSH_PET_SCALE || '1')
461
+ const bubbleScale = Number(process.env.DSH_PET_BUBBLE_SCALE || '1')
462
+ // 使用主屏工作区作为透明画布,宠物在画布内自由移动,不移动窗口本身。
463
+ const display = screen.getPrimaryDisplay()
464
+ const area = display.workArea
465
+ const width = area.width
466
+ const height = area.height
467
+
468
+ mainWindow = new BrowserWindow({
469
+ width,
470
+ height,
471
+ x: area.x,
472
+ y: area.y,
473
+ show: false,
474
+ useContentSize: true,
475
+ transparent: true,
476
+ frame: false,
477
+ alwaysOnTop: true,
478
+ skipTaskbar: true,
479
+ resizable: false,
480
+ hasShadow: false,
481
+
482
+ webPreferences: {
483
+ preload: path.join(__dirname, 'preload.js'),
484
+ contextIsolation: true,
485
+ nodeIntegration: false,
486
+ sandbox: false,
487
+ paintWhenInitiallyHidden: false,
488
+ },
489
+ })
490
+
491
+ mainWindow.once('ready-to-show', () => {
492
+ mainWindow.show()
493
+ })
494
+
495
+ mainWindow.setAlwaysOnTop(true, 'screen-saver')
496
+ mainWindow.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true })
497
+ setClickThrough(true)
498
+
499
+ mainWindow.loadFile('index.html', {
500
+ query: {
501
+ scale: String(scale),
502
+ bubbleScale: String(bubbleScale),
503
+ activityLevel: process.env.DSH_PET_ACTIVITY_LEVEL || 'normal',
504
+ reducedMotion: process.env.DSH_PET_REDUCED_MOTION === '1' ? '1' : '0',
505
+ bubbleMode: process.env.DSH_PET_BUBBLE_MODE || 'always',
506
+ bubbleStates: process.env.DSH_PET_BUBBLE_STATES || 'SUCCESS,ERROR,WAITING',
507
+ webuiUrl: process.env.DSH_PET_WEBUI_URL || 'http://127.0.0.1:3080/',
508
+ playbackRate: process.env.DSH_PET_PLAYBACK_RATE || '1',
509
+ voiceEnabled: process.env.DSH_PET_VOICE_ENABLED === '0' ? '0' : '1',
510
+ voiceWakeAutoStart: process.env.DSH_PET_VOICE_WAKE_AUTO_START === '1' ? '1' : '0',
511
+ voiceSilenceMs: process.env.DSH_PET_VOICE_SILENCE_MS || '1200',
512
+ voiceAutoSend: process.env.DSH_PET_VOICE_AUTO_SEND === '0' ? '0' : '1',
513
+ voiceAutoRecord: process.env.DSH_PET_VOICE_AUTO_RECORD === '0' ? '0' : '1',
514
+ holidayEnabled: process.env.DSH_PET_HOLIDAY_ENABLED === '1' ? '1' : '0',
515
+ wakeWord: process.env.DSH_PET_WAKE_WORD || '大肥鱼',
516
+ taskCwd: process.env.DSH_PET_TASK_CWD || '',
517
+ },
518
+ }).then(() => {
519
+ startPolling()
520
+ }).catch((error) => {
521
+ console.error('[better-dsh-pet-helper] page load failed:', error)
522
+ app.quit()
523
+ })
524
+
525
+ mainWindow.on('closed', () => {
526
+ mainWindow = null
527
+ if (pollTimer) clearInterval(pollTimer)
528
+ pollTimer = null
529
+ })
530
+ }
531
+
532
+ async function notifyHostClosed() {
533
+ const statusUrl = process.env.DSH_PET_STATUS_URL
534
+ if (!statusUrl) return
535
+ try {
536
+ const closeUrl = statusUrl.replace(/\/plugins\/better-dsh-pet\/status$/, '/plugins/better-dsh-pet/close')
537
+ await fetch(closeUrl, { method: 'POST', cache: 'no-store' })
538
+ } catch {
539
+ // 宿主不可达时无法通知,仍继续退出;宿主侧可能按崩溃重启处理。
540
+ }
541
+ }
542
+
543
+ function startPolling() {
544
+ const statusUrl = process.env.DSH_PET_STATUS_URL
545
+ if (!statusUrl) {
546
+ console.error('[better-dsh-pet-helper] DSH_PET_STATUS_URL is not set')
547
+ return
548
+ }
549
+ const poll = async () => {
550
+ if (!mainWindow || mainWindow.isDestroyed()) return
551
+ try {
552
+ const response = await fetch(statusUrl, { cache: 'no-store' })
553
+ if (!response.ok) return
554
+ const status = await response.json()
555
+ if (mainWindow && !mainWindow.isDestroyed()) {
556
+ mainWindow.webContents.send('pet:status', status)
557
+ }
558
+ } catch (error) {
559
+ // DSH 尚未就绪或临时不可达时静默跳过,下个周期再试。
560
+ }
561
+ }
562
+ poll()
563
+ pollTimer = setInterval(poll, 1000)
564
+ if (pollTimer.unref) pollTimer.unref()
565
+ }
566
+
567
+ app.whenReady().then(() => {
568
+ // 允许渲染进程使用麦克风(语音闲聊/唤醒需要)
569
+ session.defaultSession.setPermissionRequestHandler((_webContents, permission, callback) => {
570
+ callback(permission === 'media')
571
+ })
572
+ session.defaultSession.setPermissionCheckHandler(() => true)
573
+ createWindow()
574
+ createTray()
575
+ startTopmostWatchdog()
576
+ startFullscreenWatchdog()
577
+ ipcMain.on('pet:closed', (_event, reason) => {
578
+ void notifyHostClosed().finally(() => app.quit())
579
+ })
580
+ ipcMain.on('pet:hide', () => {
581
+ if (mainWindow) mainWindow.hide()
582
+ userHidden = true
583
+ })
584
+ ipcMain.on('pet:open-webui', (_event, url) => {
585
+ if (url) shell.openExternal(String(url)).catch(() => {})
586
+ })
587
+ ipcMain.on('pet:open-desktop', () => {
588
+ openDesktop()
589
+ })
590
+ ipcMain.on('pet:set-ignore-mouse', (_event, { ignore }) => {
591
+ setClickThrough(ignore === true)
592
+ })
593
+ ipcMain.on('pet:beep', () => {
594
+ try { shell.beep() } catch { /* 系统不支持时忽略 */ }
595
+ })
596
+ ipcMain.on('pet:voice-start', (event) => {
597
+ startVoiceRecognition((text) => {
598
+ if (!event.sender.isDestroyed()) {
599
+ event.sender.send('pet:voice-result', text || '')
600
+ }
601
+ })
602
+ })
603
+ ipcMain.on('pet:dictation-start', (event) => {
604
+ startVoiceDictation((text) => {
605
+ if (!event.sender.isDestroyed()) {
606
+ event.sender.send('pet:dictation-result', text || '')
607
+ }
608
+ })
609
+ })
610
+ ipcMain.on('pet:speak', (_event, text) => {
611
+ speakText(text)
612
+ })
613
+ ipcMain.on('pet:check-update', (event) => {
614
+ checkForUpdate((result) => {
615
+ if (!event.sender.isDestroyed()) {
616
+ event.sender.send('pet:update-result', result)
617
+ }
618
+ })
619
+ })
620
+ ipcMain.on('pet:wake-word-toggle', (event) => {
621
+ if (wakeWordProcess) {
622
+ stopWakeWordListener()
623
+ event.sender.send('pet:wake-state', false)
624
+ } else {
625
+ startWakeWordListener()
626
+ event.sender.send('pet:wake-state', true)
627
+ }
628
+ })
629
+ ipcMain.on('pet:set-wake-word', (event, word) => {
630
+ currentWakeWord = String(word || '大肥鱼').trim() || '大肥鱼'
631
+ if (wakeWordProcess) {
632
+ stopWakeWordListener()
633
+ startWakeWordListener()
144
634
  }
145
- }
146
- poll()
147
- pollTimer = setInterval(poll, 1000)
148
- if (pollTimer.unref) pollTimer.unref()
149
- }
150
-
151
- app.whenReady().then(() => {
152
- createWindow()
153
- ipcMain.on('pet:closed', (_event, reason) => {
154
- void notifyHostClosed().finally(() => app.quit())
155
- })
156
- ipcMain.on('pet:hide', () => {
157
- if (mainWindow) mainWindow.hide()
158
- })
159
- ipcMain.on('pet:open-webui', (_event, url) => {
160
- if (url) shell.openExternal(String(url)).catch(() => {})
161
- })
162
- ipcMain.on('pet:open-desktop', () => {
163
- openDesktop()
164
- })
165
- ipcMain.on('pet:set-ignore-mouse', (_event, { ignore }) => {
166
- setClickThrough(ignore === true)
635
+ event.sender.send('pet:wake-state', Boolean(wakeWordProcess))
167
636
  })
168
- ipcMain.on('pet:beep', () => {
169
- try { shell.beep() } catch { /* 系统不支持时忽略 */ }
170
- })
171
- ipcMain.on('pet:save-config', async (_event, patch) => {
637
+ ipcMain.handle('pet:chat', async (_event, message) => {
638
+ const statusUrl = process.env.DSH_PET_STATUS_URL
639
+ if (!statusUrl || !message) return { ok: false, reply: '消息不能为空~' }
640
+ try {
641
+ const chatUrl = statusUrl.replace(/\/plugins\/better-dsh-pet\/status$/, '/plugins/better-dsh-pet/chat')
642
+ const response = await fetch(chatUrl, {
643
+ method: 'POST',
644
+ headers: { 'content-type': 'application/json' },
645
+ body: JSON.stringify({ message }),
646
+ })
647
+ const data = await response.json()
648
+ return data
649
+ } catch {
650
+ return { ok: false, reply: '网络开小差了,等会儿再聊吧~' }
651
+ }
652
+ })
653
+ ipcMain.handle('pet:intent', async (_event, text) => {
172
654
  const statusUrl = process.env.DSH_PET_STATUS_URL
173
- if (!statusUrl || !patch || typeof patch !== 'object') return
655
+ if (!statusUrl || !text) return { ok: false, type: 'chat' }
174
656
  try {
175
- const configUrl = statusUrl.replace(/\/plugins\/better-dsh-pet\/status$/, '/plugins/better-dsh-pet/config')
176
- const response = await fetch(configUrl, {
177
- method: 'PATCH',
657
+ const intentUrl = statusUrl.replace(/\/plugins\/better-dsh-pet\/status$/, '/plugins/better-dsh-pet/intent')
658
+ const response = await fetch(intentUrl, {
659
+ method: 'POST',
178
660
  headers: { 'content-type': 'application/json' },
179
- body: JSON.stringify(patch),
661
+ body: JSON.stringify({ text }),
180
662
  })
181
- if (!response.ok) {
182
- console.error('[better-dsh-pet-helper] save config failed:', response.status)
183
- }
184
- } catch (error) {
185
- console.error('[better-dsh-pet-helper] save config error:', error)
186
- }
187
- })
188
- ipcMain.on('pet:request-roast', async () => {
189
- const statusUrl = process.env.DSH_PET_STATUS_URL
190
- if (!statusUrl) return
191
- try {
192
- const roastUrl = statusUrl.replace(/\/plugins\/better-dsh-pet\/status$/, '/plugins/better-dsh-pet/roast')
193
- await fetch(roastUrl, { method: 'POST', cache: 'no-store' })
194
- } catch (error) {
195
- console.error('[better-dsh-pet-helper] request roast error:', error)
663
+ const data = await response.json()
664
+ return data
665
+ } catch {
666
+ return { ok: false, type: 'chat' }
196
667
  }
197
668
  })
198
- ipcMain.on('pet:refresh-balance', async () => {
669
+ ipcMain.handle('pet:task', async (_event, task) => {
199
670
  const statusUrl = process.env.DSH_PET_STATUS_URL
200
- if (!statusUrl) return
671
+ if (!statusUrl || !task) return { ok: false, result: '任务内容为空~' }
201
672
  try {
202
- const refreshUrl = statusUrl.replace(/\/plugins\/better-dsh-pet\/status$/, '/plugins/better-dsh-pet/refresh-balance')
203
- await fetch(refreshUrl, { method: 'POST', cache: 'no-store' })
204
- } catch (error) {
205
- console.error('[better-dsh-pet-helper] refresh balance error:', error)
673
+ const taskUrl = statusUrl.replace(/\/plugins\/better-dsh-pet\/status$/, '/plugins/better-dsh-pet/task')
674
+ const response = await fetch(taskUrl, {
675
+ method: 'POST',
676
+ headers: { 'content-type': 'application/json' },
677
+ body: JSON.stringify({ task }),
678
+ })
679
+ const data = await response.json()
680
+ return data
681
+ } catch {
682
+ return { ok: false, result: '任务执行时网络开小差了~' }
206
683
  }
207
684
  })
208
- ipcMain.on('pet:move-by', () => {
209
- // 已改为全屏画布内移动宠物 DOM,不再移动窗口。
210
- })
211
- ipcMain.on('pet:drag-end', () => {
212
- // 保留此通道,后续可用来做拖拽结束后的持久化。
213
- })
214
- })
215
-
216
- app.on('window-all-closed', () => {
217
- app.quit()
218
- })
685
+ ipcMain.handle('pet:transcribe', async (_event, wavBuffer) => {
686
+ const statusUrl = process.env.DSH_PET_STATUS_URL
687
+ if (!statusUrl || !wavBuffer) return { ok: false, text: '' }
688
+ try {
689
+ const transcribeUrl = statusUrl.replace(/\/plugins\/better-dsh-pet\/status$/, '/plugins/better-dsh-pet/transcribe')
690
+ const response = await fetch(transcribeUrl, {
691
+ method: 'POST',
692
+ headers: { 'content-type': 'audio/wav' },
693
+ body: Buffer.from(wavBuffer),
694
+ })
695
+ const data = await response.json()
696
+ return data
697
+ } catch {
698
+ return { ok: false, text: '' }
699
+ }
700
+ })
701
+ ipcMain.on('pet:save-config', async (_event, patch) => {
702
+ const statusUrl = process.env.DSH_PET_STATUS_URL
703
+ if (!statusUrl || !patch || typeof patch !== 'object') return
704
+ try {
705
+ const configUrl = statusUrl.replace(/\/plugins\/better-dsh-pet\/status$/, '/plugins/better-dsh-pet/config')
706
+ const response = await fetch(configUrl, {
707
+ method: 'PATCH',
708
+ headers: { 'content-type': 'application/json' },
709
+ body: JSON.stringify(patch),
710
+ })
711
+ if (!response.ok) {
712
+ console.error('[better-dsh-pet-helper] save config failed:', response.status)
713
+ }
714
+ } catch (error) {
715
+ console.error('[better-dsh-pet-helper] save config error:', error)
716
+ }
717
+ })
718
+ ipcMain.on('pet:request-roast', async () => {
719
+ const statusUrl = process.env.DSH_PET_STATUS_URL
720
+ if (!statusUrl) return
721
+ try {
722
+ const roastUrl = statusUrl.replace(/\/plugins\/better-dsh-pet\/status$/, '/plugins/better-dsh-pet/roast')
723
+ await fetch(roastUrl, { method: 'POST', cache: 'no-store' })
724
+ } catch (error) {
725
+ console.error('[better-dsh-pet-helper] request roast error:', error)
726
+ }
727
+ })
728
+ ipcMain.on('pet:refresh-balance', async () => {
729
+ const statusUrl = process.env.DSH_PET_STATUS_URL
730
+ if (!statusUrl) return
731
+ try {
732
+ const refreshUrl = statusUrl.replace(/\/plugins\/better-dsh-pet\/status$/, '/plugins/better-dsh-pet/refresh-balance')
733
+ await fetch(refreshUrl, { method: 'POST', cache: 'no-store' })
734
+ } catch (error) {
735
+ console.error('[better-dsh-pet-helper] refresh balance error:', error)
736
+ }
737
+ })
738
+ ipcMain.on('pet:move-by', () => {
739
+ // 已改为全屏画布内移动宠物 DOM,不再移动窗口。
740
+ })
741
+ ipcMain.on('pet:drag-end', () => {
742
+ // 保留此通道,后续可用来做拖拽结束后的持久化。
743
+ })
744
+ })
745
+
746
+ app.on('before-quit', () => {
747
+ stopWakeWordListener()
748
+ })
749
+
750
+ app.on('window-all-closed', () => {
751
+ app.quit()
752
+ })