agentworkshop 0.17.3 → 0.17.5

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.
Files changed (53) hide show
  1. package/.output/nitro.json +1 -1
  2. package/.output/public/_nuxt/{Bi7O7Fgd.js → BIyCQj6O.js} +10 -10
  3. package/.output/public/_nuxt/BM-sWDDD.js +1 -0
  4. package/.output/public/_nuxt/Cu6Hle_d.js +2 -0
  5. package/.output/public/_nuxt/{B_6jgkkO.js → D4fDMDMY.js} +4 -4
  6. package/.output/public/_nuxt/{TownView.CASu6sUI.css → TownView.CngAEG0H.css} +1 -1
  7. package/.output/public/_nuxt/{_wsId_.1Ai43iyE.css → _wsId_.CzdXTLVh.css} +1 -1
  8. package/.output/public/_nuxt/builds/latest.json +1 -1
  9. package/.output/public/_nuxt/builds/meta/147c0379-4e07-437d-a7d2-e700d633efad.json +1 -0
  10. package/.output/public/_nuxt/{entry.CxkSJUk3.css → entry.D9gnKVzx.css} +1 -1
  11. package/.output/public/_nuxt/town.D-vq2IRd.css +1 -0
  12. package/.output/server/chunks/_/nitro.mjs +1071 -1071
  13. package/.output/server/chunks/build/{TownView-BF_qaNTQ.mjs → TownView-BdwjWlnU.mjs} +61 -9
  14. package/.output/server/chunks/build/TownView-BdwjWlnU.mjs.map +1 -0
  15. package/.output/server/chunks/build/{_wsId_-DGynuNjs.mjs → _wsId_-CLBiQH5c.mjs} +10 -8
  16. package/.output/server/chunks/build/{_wsId_-DGynuNjs.mjs.map → _wsId_-CLBiQH5c.mjs.map} +1 -1
  17. package/.output/server/chunks/build/{town-Cx6Vny3m.mjs → town-Djy_zAJV.mjs} +10 -7
  18. package/.output/server/chunks/build/{town-Cx6Vny3m.mjs.map → town-Djy_zAJV.mjs.map} +1 -1
  19. package/.output/server/chunks/routes/renderer.mjs +1 -1
  20. package/.output/server/chunks/virtual/entry.mjs +6 -2
  21. package/.output/server/chunks/virtual/precomputed.mjs +1 -1
  22. package/.output/server/package.json +1 -1
  23. package/README-zh.md +20 -6
  24. package/README.md +20 -6
  25. package/app/components/AppBackToMain.vue +86 -0
  26. package/app/components/workshop/console/Topbar.vue +2 -0
  27. package/app/components/workshop/town/components/TownTopNav.vue +2 -0
  28. package/app/pages/town.vue +15 -0
  29. package/config.yml +1 -1
  30. package/desktop/chrome/contract.mjs +59 -3
  31. package/desktop/chrome/preload-splash.cjs +29 -0
  32. package/desktop/chrome/preload.cjs +2 -0
  33. package/desktop/chrome/settings.mjs +24 -0
  34. package/desktop/chrome/splash.html +629 -0
  35. package/desktop/chrome/titlebar.html +8 -1
  36. package/desktop/chrome/tray-menu.mjs +56 -0
  37. package/desktop/main.mjs +694 -42
  38. package/desktop/sidecar.mjs +12 -2
  39. package/docs/cli.en.md +1 -1
  40. package/docs/cli.md +1 -1
  41. package/docs/desktop.md +21 -3
  42. package/docs/plugins.en.md +1 -1
  43. package/docs/plugins.md +1 -1
  44. package/docs/sdk.en.md +1 -1
  45. package/docs/sdk.md +1 -1
  46. package/i18n/locales/en.ts +2 -0
  47. package/i18n/locales/zh-CN.ts +2 -0
  48. package/package.json +223 -219
  49. package/.output/public/_nuxt/CkTQQ28a.js +0 -1
  50. package/.output/public/_nuxt/DhFEApxl.js +0 -2
  51. package/.output/public/_nuxt/builds/meta/e534f0d1-3bc5-444b-a033-3e437b713fc0.json +0 -1
  52. package/.output/public/_nuxt/town.BZPLR4A_.css +0 -1
  53. package/.output/server/chunks/build/TownView-BF_qaNTQ.mjs.map +0 -1
package/desktop/main.mjs CHANGED
@@ -1,18 +1,24 @@
1
- import { app, BrowserWindow, WebContentsView, dialog, ipcMain, Menu, session } from 'electron'
1
+ import { app, BrowserWindow, WebContentsView, dialog, ipcMain, Menu, session, Tray, nativeImage, Notification, shell as electronShell } from 'electron'
2
2
  import { spawn } from 'node:child_process'
3
3
  import { createWriteStream, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
4
4
  import { tmpdir } from 'node:os'
5
5
  import { dirname, join, resolve } from 'node:path'
6
+ import { setTimeout as wait } from 'node:timers/promises'
6
7
  import { fileURLToPath, pathToFileURL } from 'node:url'
7
8
  import { isAppUrl, startSidecar } from './sidecar.mjs'
8
9
  import { checkForUpdate, downloadUpdate, buildInstallHelper, INSTALL_HELPER_SCRIPT, UPDATE_REPO } from './update.mjs'
9
10
  import {
10
11
  CHROME_CHANNELS,
12
+ SPLASH_CHANNELS,
11
13
  TITLEBAR_HEIGHT,
14
+ bootStage,
12
15
  cleanPageTitle,
13
16
  isChromeAction,
17
+ isSplashAction,
14
18
  normalizeTheme,
15
19
  } from './chrome/contract.mjs'
20
+ import { loadSettings, saveSettings } from './chrome/settings.mjs'
21
+ import { buildTrayMenuModel, TRAY_SETTING_KEYS, TRAY_SETTINGS } from './chrome/tray-menu.mjs'
16
22
 
17
23
  const here = dirname(fileURLToPath(import.meta.url))
18
24
  const backend = app.isPackaged ? join(process.resourcesPath, 'backend') : resolve(here, '..')
@@ -22,23 +28,40 @@ const node = app.isPackaged
22
28
  const { desktopHome } = await import(pathToFileURL(join(backend, 'shared', 'config', 'home.mjs')).href)
23
29
  const home = desktopHome()
24
30
  const profile = join(home, 'electron')
31
+ const settingsFile = join(profile, 'settings.json')
32
+ const statusFile = join(profile, 'desktop-status.json')
33
+ const logsDir = join(home, 'logs')
25
34
  mkdirSync(profile, { recursive: true })
35
+ mkdirSync(logsDir, { recursive: true })
26
36
  app.setPath('userData', profile)
27
37
  app.setAppUserModelId('com.agentworkshop.desktop')
28
38
 
39
+ let settings = loadSettings(settingsFile)
29
40
  let shell
30
41
  let contentView
42
+ let splashWindow
31
43
  let startup
32
44
  let sidecar
45
+ let sidecarGeneration = 0
46
+ let restarting = false
33
47
  let stopping = false
34
48
  let allowQuit = false
35
49
  let log
50
+ let tray
51
+ let hideNoticeShown = false
36
52
  let pageTitle = ''
37
53
  let theme = 'dark'
38
54
  let serviceState = 'connecting'
55
+ let statusPhase = 'booting'
56
+ let lastStartupError = null
57
+ let bootStartedAt = Date.now()
58
+ let splashState = null
39
59
  let themeTimer
60
+ const startedAt = new Date().toISOString()
40
61
  const UPDATE_INTERVAL_MS = 30 * 60 * 1000
62
+ const MIN_SPLASH_MS = 2_000
41
63
  let updateTimer
64
+ let updateStartTimer
42
65
  let updateRelease = null
43
66
  let updateInstaller = null
44
67
  let updateBusy = false
@@ -49,6 +72,10 @@ function sendToChrome(channel, payload) {
49
72
  shell.webContents.send(channel, payload)
50
73
  }
51
74
 
75
+ function sendPrefs() {
76
+ sendToChrome(CHROME_CHANNELS.prefs, { closeToTray: settings.closeToTray })
77
+ }
78
+
52
79
  function windowState() {
53
80
  return {
54
81
  maximized: shell?.isMaximized() ?? false,
@@ -121,6 +148,40 @@ function updateRepo() {
121
148
  return process.env.AW_UPDATE_REPO?.trim() || UPDATE_REPO
122
149
  }
123
150
 
151
+ function writeStatus() {
152
+ const snapshot = {
153
+ schema: 1,
154
+ product: 'AgentWorkShop',
155
+ pid: process.pid,
156
+ version: currentVersion(),
157
+ phase: statusPhase,
158
+ bootStage: splashState?.phase ?? null,
159
+ service: serviceState,
160
+ port: sidecar?.port ?? null,
161
+ origin: sidecar?.origin ?? null,
162
+ windowVisible: Boolean(shell && !shell.isDestroyed() && shell.isVisible()),
163
+ windowFocused: Boolean(shell && !shell.isDestroyed() && shell.isFocused()),
164
+ trayCreated: Boolean(tray && !tray.isDestroyed()),
165
+ settings,
166
+ startedAt,
167
+ updatedAt: new Date().toISOString(),
168
+ lastError: lastStartupError,
169
+ }
170
+ try {
171
+ writeFileSync(statusFile, `${JSON.stringify(snapshot, null, 2)}\n`, 'utf8')
172
+ }
173
+ catch (err) {
174
+ console.error('[desktop] could not write status:', err.message)
175
+ }
176
+ }
177
+
178
+ function setServiceState(next) {
179
+ serviceState = next
180
+ sendToChrome(CHROME_CHANNELS.status, serviceState)
181
+ refreshTray()
182
+ writeStatus()
183
+ }
184
+
124
185
  function sendUpdateState() {
125
186
  sendToChrome(CHROME_CHANNELS.updateState, {
126
187
  status: updateState.status,
@@ -134,10 +195,11 @@ function sendUpdateState() {
134
195
  function setUpdateState(patch) {
135
196
  updateState = { ...updateState, ...patch }
136
197
  sendUpdateState()
198
+ refreshTray()
137
199
  }
138
200
 
139
201
  let updateChecking = false
140
- async function checkUpdate() {
202
+ async function checkUpdate({ manual = false } = {}) {
141
203
  if (updateChecking || updateBusy) return
142
204
  if (['downloading', 'ready'].includes(updateState.status)) return
143
205
  updateChecking = true
@@ -152,15 +214,18 @@ async function checkUpdate() {
152
214
  error: null,
153
215
  notes: result.release.notes,
154
216
  })
217
+ if (manual) notify('发现新版本', `AgentWorkShop v${result.release.version} 可在标题栏安装。`)
155
218
  }
156
219
  else {
157
220
  updateRelease = null
158
221
  setUpdateState({ status: 'idle', version: null, progress: 0, error: null, notes: '' })
222
+ if (manual) notify('已是最新版本', `当前版本 v${currentVersion()}`)
159
223
  }
160
224
  }
161
225
  catch (err) {
162
226
  console.error('[update] check failed:', err.message)
163
227
  if (!['downloading', 'ready'].includes(updateState.status)) setUpdateState({ status: 'idle' })
228
+ if (manual) notify('检查更新失败', err.message)
164
229
  }
165
230
  finally {
166
231
  updateChecking = false
@@ -200,7 +265,7 @@ async function beginDownload() {
200
265
 
201
266
  async function installUpdate() {
202
267
  if (!app.isPackaged || process.platform !== 'win32') {
203
- await dialog.showMessageBox(shell, {
268
+ await showMessageBox({
204
269
  type: 'info',
205
270
  title: '自动更新',
206
271
  message: '自动安装仅支持 Windows 安装版',
@@ -212,17 +277,18 @@ async function installUpdate() {
212
277
  setUpdateState({ status: 'error', error: '更新包不存在,请重新下载' })
213
278
  return
214
279
  }
280
+ const options = {
281
+ type: 'question',
282
+ title: '安装更新',
283
+ message: `安装 AgentWorkShop v${updateRelease.version} 并重启?`,
284
+ detail: (updateRelease.notes || '更新完成后应用会自动重启。').slice(0, 1_200),
285
+ buttons: ['重启并安装', '稍后'],
286
+ defaultId: 0,
287
+ cancelId: 1,
288
+ }
215
289
  const choice = process.env.AW_UPDATE_AUTOINSTALL === '1'
216
290
  ? { response: 0 }
217
- : await dialog.showMessageBox(shell, {
218
- type: 'question',
219
- title: '安装更新',
220
- message: `安装 AgentWorkShop v${updateRelease.version} 并重启?`,
221
- detail: (updateRelease.notes || '更新完成后应用会自动重启。').slice(0, 1_200),
222
- buttons: ['重启并安装', '稍后'],
223
- defaultId: 0,
224
- cancelId: 1,
225
- })
291
+ : await showMessageBox(options)
226
292
  if (choice.response !== 0) return
227
293
  const installer = updateInstaller
228
294
  const exe = process.execPath
@@ -236,12 +302,262 @@ async function installUpdate() {
236
302
  }
237
303
 
238
304
  function scheduleUpdates() {
239
- if (process.env.AW_UPDATE_CHECK === '0' || updateTimer) return
240
- setTimeout(() => void checkUpdate(), 4_000).unref()
305
+ if (process.env.AW_UPDATE_CHECK === '0' || updateTimer || !settings.autoCheckUpdates) return
306
+ updateStartTimer = setTimeout(() => void checkUpdate(), 4_000)
307
+ updateStartTimer.unref()
241
308
  updateTimer = setInterval(() => void checkUpdate(), UPDATE_INTERVAL_MS)
242
309
  updateTimer.unref()
243
310
  }
244
311
 
312
+ function stopUpdates() {
313
+ clearTimeout(updateStartTimer)
314
+ clearInterval(updateTimer)
315
+ updateStartTimer = undefined
316
+ updateTimer = undefined
317
+ }
318
+
319
+ function showMessageBox(options) {
320
+ const parent = shell && !shell.isDestroyed() && shell.isVisible() ? shell : undefined
321
+ return parent ? dialog.showMessageBox(parent, options) : dialog.showMessageBox(options)
322
+ }
323
+
324
+ function notify(title, content) {
325
+ if (!settings.trayNotifications) return
326
+ try {
327
+ if (Notification.isSupported()) {
328
+ const notification = new Notification({
329
+ title,
330
+ body: content,
331
+ icon: join(here, 'build', 'icon.png'),
332
+ silent: true,
333
+ })
334
+ notification.on('click', () => showMain())
335
+ notification.show()
336
+ return
337
+ }
338
+ }
339
+ catch {
340
+ // Fall through to the tray balloon on systems without toast support.
341
+ }
342
+ if (tray && !tray.isDestroyed()) {
343
+ try {
344
+ tray.displayBalloon({ title, content, iconType: 'info', noSound: true })
345
+ }
346
+ catch {
347
+ // Notifications are best-effort; never break the shell for a balloon.
348
+ }
349
+ }
350
+ }
351
+
352
+ function showMain() {
353
+ if (splashWindow && !splashWindow.isDestroyed()) {
354
+ splashWindow.show()
355
+ splashWindow.focus()
356
+ return
357
+ }
358
+ if (!shell || shell.isDestroyed()) return
359
+ if (shell.isMinimized()) shell.restore()
360
+ shell.show()
361
+ shell.focus()
362
+ statusPhase = 'ready'
363
+ writeStatus()
364
+ refreshTray()
365
+ }
366
+
367
+ function hideToTray() {
368
+ if (!shell || shell.isDestroyed()) return
369
+ shell.hide()
370
+ statusPhase = 'hidden'
371
+ writeStatus()
372
+ refreshTray()
373
+ if (!hideNoticeShown) {
374
+ hideNoticeShown = true
375
+ notify('AgentWorkShop 仍在运行', '已最小化到托盘,本机服务继续运行。双击托盘图标可恢复窗口。')
376
+ }
377
+ }
378
+
379
+ function trayImage() {
380
+ const image = nativeImage.createFromPath(join(here, 'build', 'icon.png'))
381
+ if (image.isEmpty()) return nativeImage.createEmpty()
382
+ return image.resize({ width: 16, height: 16, quality: 'best' })
383
+ }
384
+
385
+ function trayMenuItem(descriptor) {
386
+ if (descriptor.type === 'separator') return { type: 'separator' }
387
+ const item = { label: descriptor.label, enabled: descriptor.enabled !== false }
388
+ if (descriptor.type === 'checkbox') {
389
+ item.type = 'checkbox'
390
+ item.checked = Boolean(descriptor.checked)
391
+ item.click = () => handleTrayAction(descriptor.id)
392
+ }
393
+ else if (Array.isArray(descriptor.submenu)) {
394
+ item.submenu = descriptor.submenu.map(trayMenuItem)
395
+ }
396
+ else {
397
+ item.click = () => handleTrayAction(descriptor.id)
398
+ }
399
+ return item
400
+ }
401
+
402
+ function refreshTray() {
403
+ if (!tray || tray.isDestroyed()) return
404
+ const model = buildTrayMenuModel({
405
+ settings,
406
+ service: serviceState,
407
+ port: sidecar?.port,
408
+ version: currentVersion(),
409
+ windowVisible: Boolean(shell && !shell.isDestroyed() && shell.isVisible()),
410
+ update: updateState,
411
+ })
412
+ tray.setContextMenu(Menu.buildFromTemplate(model.map(trayMenuItem)))
413
+ const service = serviceState === 'online'
414
+ ? '本机服务运行中'
415
+ : serviceState === 'offline' ? '本机服务已断开' : '正在启动本机服务'
416
+ tray.setToolTip(`AgentWorkShop v${currentVersion()} · ${service}`)
417
+ }
418
+
419
+ function createTray() {
420
+ if (tray && !tray.isDestroyed()) return
421
+ tray = new Tray(trayImage())
422
+ tray.on('click', () => showMain())
423
+ tray.on('double-click', () => showMain())
424
+ refreshTray()
425
+ writeStatus()
426
+ }
427
+
428
+ function openHome() {
429
+ void electronShell.openPath(home).catch(err => console.error('[desktop] open home:', err.message))
430
+ }
431
+
432
+ function openLogs() {
433
+ mkdirSync(logsDir, { recursive: true })
434
+ void electronShell.openPath(logsDir).catch(err => console.error('[desktop] open logs:', err.message))
435
+ }
436
+
437
+ function reloadContent() {
438
+ if (!contentView || contentView.webContents.isDestroyed()) return
439
+ contentView.webContents.reload()
440
+ }
441
+
442
+ async function showDiagnostics() {
443
+ const text = [
444
+ `版本:v${currentVersion()}`,
445
+ `本机服务:${serviceState === 'online' ? `运行中 · 127.0.0.1:${sidecar?.port ?? '?'}` : serviceState === 'offline' ? '已断开' : '启动中'}`,
446
+ `数据目录:${home}`,
447
+ `日志目录:${logsDir}`,
448
+ `运行状态:${statusPhase}`,
449
+ `关闭行为:${settings.closeToTray ? '最小化到托盘' : '退出应用'}`,
450
+ `开机自动启动:${settings.launchAtLogin ? '开启' : '关闭'}${app.isPackaged ? '' : '(源码模式不写入系统)'}`,
451
+ `启动后最小化:${settings.startHidden ? '开启' : '关闭'}`,
452
+ `自动检查更新:${settings.autoCheckUpdates ? '开启' : '关闭'}`,
453
+ ].join('\n')
454
+ const result = await showMessageBox({
455
+ type: 'info',
456
+ title: 'AgentWorkShop 诊断',
457
+ message: '桌面运行诊断',
458
+ detail: text,
459
+ buttons: ['打开数据目录', '打开日志目录', '关闭'],
460
+ defaultId: 2,
461
+ cancelId: 2,
462
+ })
463
+ if (result.response === 0) openHome()
464
+ if (result.response === 1) openLogs()
465
+ }
466
+
467
+ function applyLoginItem() {
468
+ if (!app.isPackaged) return false
469
+ try {
470
+ app.setLoginItemSettings({ openAtLogin: settings.launchAtLogin, path: process.execPath, args: [] })
471
+ return true
472
+ }
473
+ catch (err) {
474
+ console.error('[desktop] login item:', err.message)
475
+ return false
476
+ }
477
+ }
478
+
479
+ function toggleSetting(key) {
480
+ if (!TRAY_SETTING_KEYS.includes(key)) return
481
+ const next = { ...settings, [key]: !settings[key] }
482
+ try {
483
+ settings = saveSettings(settingsFile, next)
484
+ }
485
+ catch (err) {
486
+ console.error('[desktop] save settings:', err.message)
487
+ notify('设置未保存', err.message)
488
+ return
489
+ }
490
+ if (key === 'launchAtLogin') {
491
+ const applied = applyLoginItem()
492
+ if (!applied && settings.launchAtLogin) {
493
+ notify('开机自启动', '源码模式不写入系统登录项;安装版会立即生效。')
494
+ }
495
+ }
496
+ if (key === 'autoCheckUpdates') {
497
+ if (settings.autoCheckUpdates) scheduleUpdates()
498
+ else stopUpdates()
499
+ }
500
+ sendPrefs()
501
+ refreshTray()
502
+ writeStatus()
503
+ const label = TRAY_SETTINGS.find(item => item.key === key)?.label ?? key
504
+ notify('设置已更新', `${label}:${settings[key] ? '开启' : '关闭'}`)
505
+ }
506
+
507
+ function manualUpdateAction() {
508
+ if (updateState.status === 'ready') {
509
+ showMain()
510
+ void installUpdate()
511
+ return
512
+ }
513
+ if (updateState.status === 'downloading') {
514
+ showMain()
515
+ return
516
+ }
517
+ if (updateState.status === 'available') {
518
+ showMain()
519
+ notify('发现新版本', `AgentWorkShop v${updateState.version} 可在标题栏安装。`)
520
+ return
521
+ }
522
+ void checkUpdate({ manual: true })
523
+ }
524
+
525
+ function handleTrayAction(id) {
526
+ if (typeof id !== 'string') return
527
+ if (id.startsWith('setting:')) {
528
+ toggleSetting(id.slice('setting:'.length))
529
+ return
530
+ }
531
+ switch (id) {
532
+ case 'open':
533
+ showMain()
534
+ break
535
+ case 'reload':
536
+ reloadContent()
537
+ break
538
+ case 'restart-service':
539
+ void restartBackend()
540
+ break
541
+ case 'check-update':
542
+ manualUpdateAction()
543
+ break
544
+ case 'open-home':
545
+ openHome()
546
+ break
547
+ case 'open-logs':
548
+ openLogs()
549
+ break
550
+ case 'diagnostics':
551
+ void showDiagnostics()
552
+ break
553
+ case 'quit':
554
+ quit()
555
+ break
556
+ default:
557
+ break
558
+ }
559
+ }
560
+
245
561
  function registerChromeIpc() {
246
562
  ipcMain.on(CHROME_CHANNELS.action, (event, action) => {
247
563
  if (!shell || event.sender !== shell.webContents || !isChromeAction(action)) return
@@ -250,7 +566,8 @@ function registerChromeIpc() {
250
566
  if (shell.isMaximized()) shell.unmaximize()
251
567
  else shell.maximize()
252
568
  }
253
- else { shell.close() }
569
+ else if (settings.closeToTray) hideToTray()
570
+ else shell.close()
254
571
  })
255
572
  ipcMain.on(CHROME_CHANNELS.hello, (event) => {
256
573
  if (event.sender !== shell?.webContents) return
@@ -258,6 +575,7 @@ function registerChromeIpc() {
258
575
  sendToChrome(CHROME_CHANNELS.status, serviceState)
259
576
  sendToChrome(CHROME_CHANNELS.theme, theme)
260
577
  sendToChrome(CHROME_CHANNELS.title, pageTitle)
578
+ sendPrefs()
261
579
  sendUpdateState()
262
580
  })
263
581
  ipcMain.on(CHROME_CHANNELS.update, (event, action) => {
@@ -278,6 +596,8 @@ function watchTheme() {
278
596
  function quit() {
279
597
  if (stopping) return
280
598
  stopping = true
599
+ statusPhase = 'quitting'
600
+ writeStatus()
281
601
  void (async () => {
282
602
  try {
283
603
  await startup?.catch(() => {})
@@ -305,6 +625,190 @@ function harden(contents, { origin, chrome = false }) {
305
625
  contents.setWindowOpenHandler(() => ({ action: 'deny' }))
306
626
  }
307
627
 
628
+ function splashPayload() {
629
+ return {
630
+ ...splashState,
631
+ version: currentVersion(),
632
+ logPath: logsDir,
633
+ }
634
+ }
635
+
636
+ function sendSplashState() {
637
+ if (!splashWindow || splashWindow.isDestroyed() || !splashState) return
638
+ splashWindow.webContents.send(SPLASH_CHANNELS.state, splashPayload())
639
+ }
640
+
641
+ function resetSplashState() {
642
+ bootStartedAt = Date.now()
643
+ splashState = {
644
+ phase: 'prepare',
645
+ title: bootStage('prepare').title,
646
+ detail: bootStage('prepare').detail,
647
+ progress: bootStage('prepare').progress,
648
+ startedAt: bootStartedAt,
649
+ trace: [],
650
+ error: null,
651
+ leaving: false,
652
+ }
653
+ }
654
+
655
+ function setBootStage(id) {
656
+ const stage = bootStage(id)
657
+ const at = Date.now() - bootStartedAt
658
+ splashState = {
659
+ ...(splashState ?? {}),
660
+ phase: stage.id,
661
+ title: stage.title,
662
+ detail: stage.detail,
663
+ progress: Math.max(splashState?.progress ?? 0, stage.progress),
664
+ startedAt: bootStartedAt,
665
+ error: null,
666
+ leaving: false,
667
+ trace: [...(splashState?.trace ?? []), { at, text: stage.title }].slice(-6),
668
+ }
669
+ sendSplashState()
670
+ writeStatus()
671
+ }
672
+
673
+ function setSplashError(err) {
674
+ const message = String(err?.message || err || '未知错误').slice(0, 800)
675
+ lastStartupError = message
676
+ splashState = {
677
+ ...(splashState ?? {}),
678
+ phase: 'error',
679
+ title: '启动失败',
680
+ detail: '本机服务未能就绪',
681
+ error: message,
682
+ startedAt: bootStartedAt,
683
+ leaving: false,
684
+ trace: [...(splashState?.trace ?? []), { at: Date.now() - bootStartedAt, text: '启动失败' }].slice(-6),
685
+ }
686
+ statusPhase = 'error'
687
+ sendSplashState()
688
+ writeStatus()
689
+ refreshTray()
690
+ }
691
+
692
+ function createSplash() {
693
+ resetSplashState()
694
+ const browser = new BrowserWindow({
695
+ width: 660,
696
+ height: 440,
697
+ center: true,
698
+ show: false,
699
+ frame: false,
700
+ resizable: false,
701
+ minimizable: false,
702
+ maximizable: false,
703
+ fullscreenable: false,
704
+ skipTaskbar: true,
705
+ alwaysOnTop: true,
706
+ hasShadow: true,
707
+ roundedCorners: true,
708
+ backgroundColor: '#070c14',
709
+ title: 'AgentWorkShop',
710
+ icon: join(here, 'build', 'icon.png'),
711
+ webPreferences: {
712
+ preload: join(here, 'chrome', 'preload-splash.cjs'),
713
+ sandbox: true,
714
+ contextIsolation: true,
715
+ nodeIntegration: false,
716
+ webSecurity: true,
717
+ spellcheck: false,
718
+ devTools: false,
719
+ },
720
+ })
721
+ splashWindow = browser
722
+ harden(browser.webContents, { chrome: true })
723
+ browser.webContents.on('did-finish-load', () => sendSplashState())
724
+ browser.once('ready-to-show', () => {
725
+ if (!stopping) browser.show()
726
+ })
727
+ browser.on('closed', () => {
728
+ if (splashWindow === browser) splashWindow = undefined
729
+ if (!stopping && !shell) quit()
730
+ })
731
+ void browser.loadFile(join(here, 'chrome', 'splash.html')).catch((err) => {
732
+ console.error('[desktop] splash:', err.message)
733
+ const fallback = splashWindow
734
+ splashWindow = undefined
735
+ if (fallback && !fallback.isDestroyed()) fallback.destroy()
736
+ })
737
+ }
738
+
739
+ function registerSplashIpc() {
740
+ ipcMain.on(SPLASH_CHANNELS.hello, (event) => {
741
+ if (event.sender !== splashWindow?.webContents) return
742
+ sendSplashState()
743
+ })
744
+ ipcMain.on(SPLASH_CHANNELS.action, (event, action) => {
745
+ if (event.sender !== splashWindow?.webContents || !isSplashAction(action)) return
746
+ if (action === 'retry') void retryStartup()
747
+ else if (action === 'open-logs') openLogs()
748
+ else quit()
749
+ })
750
+ }
751
+
752
+ async function settleSplash() {
753
+ const remaining = MIN_SPLASH_MS - (Date.now() - bootStartedAt)
754
+ if (remaining > 0) await wait(remaining)
755
+ }
756
+
757
+ function destroySplash() {
758
+ const browser = splashWindow
759
+ splashWindow = undefined
760
+ if (browser && !browser.isDestroyed()) browser.destroy()
761
+ }
762
+
763
+ async function revealMain() {
764
+ setBootStage('ready')
765
+ await settleSplash()
766
+ if (stopping) return
767
+ if (settings.startHidden) {
768
+ statusPhase = 'hidden'
769
+ destroySplash()
770
+ notify('AgentWorkShop 已在托盘运行', '本机服务已就绪。双击托盘图标打开主窗口。')
771
+ writeStatus()
772
+ refreshTray()
773
+ }
774
+ else {
775
+ if (shell && !shell.isDestroyed()) {
776
+ shell.show()
777
+ shell.focus()
778
+ contentView?.webContents.focus()
779
+ }
780
+ statusPhase = 'ready'
781
+ splashState = { ...splashState, leaving: true }
782
+ sendSplashState()
783
+ await wait(300)
784
+ destroySplash()
785
+ writeStatus()
786
+ refreshTray()
787
+ }
788
+ scheduleUpdates()
789
+ scheduleTestAutoquit()
790
+ scheduleTestTrayMenu()
791
+ }
792
+
793
+ function scheduleTestAutoquit() {
794
+ const raw = Number(process.env.AW_DESKTOP_TEST_AUTOQUIT_MS)
795
+ if (!Number.isFinite(raw) || raw <= 0) return
796
+ const timer = setTimeout(() => {
797
+ console.log(`[desktop:test] auto quit after ${raw}ms`)
798
+ quit()
799
+ }, raw)
800
+ timer.unref()
801
+ }
802
+
803
+ function scheduleTestTrayMenu() {
804
+ const raw = Number(process.env.AW_DESKTOP_TEST_TRAY_MENU_MS)
805
+ if (!Number.isFinite(raw) || raw <= 0) return
806
+ const timer = setTimeout(() => {
807
+ if (tray && !tray.isDestroyed()) tray.popUpContextMenu()
808
+ }, raw)
809
+ timer.unref()
810
+ }
811
+
308
812
  async function createShell(origin) {
309
813
  const browser = new BrowserWindow({
310
814
  width: 1440,
@@ -363,13 +867,29 @@ async function createShell(origin) {
363
867
  }
364
868
  browser.on('focus', () => sendToChrome(CHROME_CHANNELS.state, windowState()))
365
869
  browser.on('blur', () => sendToChrome(CHROME_CHANNELS.state, windowState()))
870
+ browser.on('close', (event) => {
871
+ if (allowQuit || !settings.closeToTray) return
872
+ event.preventDefault()
873
+ hideToTray()
874
+ })
875
+ browser.on('show', () => {
876
+ if (statusPhase === 'hidden') statusPhase = 'ready'
877
+ writeStatus()
878
+ refreshTray()
879
+ })
880
+ browser.on('hide', () => {
881
+ if (!stopping && statusPhase === 'ready') statusPhase = 'hidden'
882
+ writeStatus()
883
+ refreshTray()
884
+ })
366
885
  browser.on('closed', () => {
367
886
  clearInterval(themeTimer)
368
887
  themeTimer = undefined
369
- clearInterval(updateTimer)
370
- updateTimer = undefined
888
+ stopUpdates()
371
889
  shell = undefined
372
890
  contentView = undefined
891
+ writeStatus()
892
+ refreshTray()
373
893
  })
374
894
 
375
895
  await browser.loadFile(join(here, 'chrome', 'titlebar.html'))
@@ -377,56 +897,188 @@ async function createShell(origin) {
377
897
  await refreshTheme()
378
898
  await syncThemeFromPage()
379
899
  layout()
380
- browser.show()
381
- contentView.webContents.focus()
382
- scheduleUpdates()
383
900
  themeTimer = setInterval(() => void syncThemeFromPage(), 2_000)
384
901
  themeTimer.unref()
385
902
  }
386
903
 
387
- async function open() {
388
- const logs = join(home, 'logs')
389
- mkdirSync(logs, { recursive: true })
390
- log = createWriteStream(join(logs, 'desktop-server.log'), { flags: 'a' })
904
+ function ensureLog() {
905
+ if (log) return log
906
+ log = createWriteStream(join(logsDir, 'desktop-server.log'), { flags: 'a' })
391
907
  log.on('error', err => console.error('Desktop log:', err.message))
392
- sidecar = await startSidecar({ node, backend, home, log })
393
- if (stopping) return
394
- serviceState = 'online'
395
- await createShell(sidecar.origin)
396
- if (stopping) return
397
- void sidecar.closed.then(() => {
398
- if (stopping) return
399
- serviceState = 'offline'
400
- sendToChrome(CHROME_CHANNELS.status, serviceState)
401
- shell?.destroy()
908
+ return log
909
+ }
910
+
911
+ function watchSidecarClosed(generation, instance) {
912
+ void instance.closed.then(() => {
913
+ if (stopping || generation !== sidecarGeneration) return
914
+ sidecar = undefined
915
+ setServiceState('offline')
402
916
  console.error('Desktop server supervisor stopped')
403
- quit()
917
+ if (splashWindow) {
918
+ setSplashError(new Error('本机服务在初始化后意外停止。'))
919
+ return
920
+ }
921
+ void showMessageBox({
922
+ type: 'error',
923
+ title: '本机服务已停止',
924
+ message: '本地服务意外退出。',
925
+ detail: '可以重启本地服务,或退出应用。数据已保存在本机。',
926
+ buttons: ['重启本地服务', '退出应用'],
927
+ defaultId: 0,
928
+ cancelId: 1,
929
+ }).then((choice) => {
930
+ if (choice.response === 0) void restartBackend({ confirm: false })
931
+ else quit()
932
+ })
404
933
  })
405
934
  }
406
935
 
936
+ async function open() {
937
+ ensureLog()
938
+ resetSplashState()
939
+ try {
940
+ setBootStage('prepare')
941
+ sidecarGeneration += 1
942
+ const generation = sidecarGeneration
943
+ sidecar = await startSidecar({
944
+ node,
945
+ backend,
946
+ home,
947
+ log,
948
+ onStage: (stage) => {
949
+ if (!stopping && generation === sidecarGeneration) setBootStage(stage)
950
+ },
951
+ })
952
+ if (stopping) return
953
+ watchSidecarClosed(generation, sidecar)
954
+ setServiceState('online')
955
+ setBootStage('workshop')
956
+ await createShell(sidecar.origin)
957
+ if (stopping) return
958
+ await revealMain()
959
+ }
960
+ catch (err) {
961
+ lastStartupError = String(err?.message || err)
962
+ console.error(err)
963
+ try {
964
+ await sidecar?.stop()
965
+ }
966
+ catch (stopError) {
967
+ console.error(stopError)
968
+ }
969
+ sidecar = undefined
970
+ if (shell && !shell.isDestroyed()) shell.destroy()
971
+ setSplashError(err)
972
+ throw err
973
+ }
974
+ }
975
+
976
+ async function retryStartup() {
977
+ if (stopping || restarting) return
978
+ restarting = true
979
+ try {
980
+ await startup?.catch(() => {})
981
+ if (sidecar) {
982
+ const previous = sidecar
983
+ sidecar = undefined
984
+ sidecarGeneration += 1
985
+ await previous.stop().catch(() => {})
986
+ }
987
+ if (shell && !shell.isDestroyed()) shell.destroy()
988
+ resetSplashState()
989
+ sendSplashState()
990
+ startup = open()
991
+ await startup.catch(() => {})
992
+ }
993
+ finally {
994
+ restarting = false
995
+ }
996
+ }
997
+
998
+ async function restartBackend({ confirm = true } = {}) {
999
+ if (restarting || stopping) return
1000
+ if (confirm) {
1001
+ const choice = await showMessageBox({
1002
+ type: 'question',
1003
+ title: '重启本地服务',
1004
+ message: '重启本机服务会短暂中断当前任务,确定继续?',
1005
+ detail: 'Channel、Session 与已保存的数据不会丢失。',
1006
+ buttons: ['重启服务', '取消'],
1007
+ defaultId: 0,
1008
+ cancelId: 1,
1009
+ })
1010
+ if (choice.response !== 0) return
1011
+ }
1012
+ restarting = true
1013
+ const previous = sidecar
1014
+ sidecarGeneration += 1
1015
+ setServiceState('connecting')
1016
+ try {
1017
+ if (previous) await previous.stop()
1018
+ sidecar = undefined
1019
+ ensureLog()
1020
+ const next = await startSidecar({ node, backend, home, log })
1021
+ if (stopping) {
1022
+ await next.stop()
1023
+ return
1024
+ }
1025
+ sidecar = next
1026
+ watchSidecarClosed(sidecarGeneration, next)
1027
+ if (contentView && !contentView.webContents.isDestroyed()) await contentView.webContents.loadURL(next.origin)
1028
+ setServiceState('online')
1029
+ statusPhase = shell?.isVisible() ? 'ready' : 'hidden'
1030
+ writeStatus()
1031
+ refreshTray()
1032
+ notify('本机服务已重启', `监听 127.0.0.1:${next.port}`)
1033
+ }
1034
+ catch (err) {
1035
+ console.error(err)
1036
+ sidecar = undefined
1037
+ setServiceState('offline')
1038
+ await showMessageBox({
1039
+ type: 'error',
1040
+ title: '重启失败',
1041
+ message: '本地服务未能重新启动。',
1042
+ detail: `${err.message}\n日志目录:${logsDir}`,
1043
+ buttons: ['确定'],
1044
+ })
1045
+ }
1046
+ finally {
1047
+ restarting = false
1048
+ writeStatus()
1049
+ refreshTray()
1050
+ }
1051
+ }
1052
+
407
1053
  if (!app.requestSingleInstanceLock()) app.quit()
408
1054
  else {
409
1055
  app.on('second-instance', () => {
410
- if (shell?.isMinimized()) shell.restore()
411
- shell?.show()
412
- shell?.focus()
1056
+ showMain()
413
1057
  })
1058
+ app.on('activate', () => showMain())
414
1059
  app.on('window-all-closed', quit)
415
1060
  app.on('before-quit', (event) => {
416
1061
  if (allowQuit) return
417
1062
  event.preventDefault()
418
1063
  quit()
419
1064
  })
1065
+ app.on('will-quit', () => {
1066
+ if (tray && !tray.isDestroyed()) tray.destroy()
1067
+ tray = undefined
1068
+ })
420
1069
  void app.whenReady().then(() => {
421
1070
  Menu.setApplicationMenu(null)
1071
+ applyLoginItem()
422
1072
  registerChromeIpc()
1073
+ registerSplashIpc()
423
1074
  watchTheme()
1075
+ createTray()
1076
+ writeStatus()
1077
+ createSplash()
424
1078
  if (stopping) return
425
1079
  startup = open()
426
- void startup.catch((err) => {
427
- console.error(err)
428
- if (!stopping) dialog.showErrorBox('AgentWorkShop', `无法启动桌面服务。\n${err.message}\n日志目录:${join(home, 'logs')}`)
429
- quit()
1080
+ void startup.catch(() => {
1081
+ // The splash already shows the error and offers retry/open-logs/quit.
430
1082
  })
431
1083
  })
432
1084
  }