dsh-app-controls 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -16,12 +16,12 @@
16
16
  * `quitRequested` flag, so the tray can close the window as well as stop the
17
17
  * service (and restart it later).
18
18
  */
19
- import { appendFileSync, chmodSync, mkdirSync, unlinkSync } from 'node:fs'
19
+ import { appendFileSync, chmodSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'
20
20
  import net from 'node:net'
21
21
  import os from 'node:os'
22
22
  import path from 'node:path'
23
23
  import { CACHE_CATEGORIES, cleanCache, packageManagerBusy, scanCache } from './cache.js'
24
- import { checkUpdates, locateInstall, updateTo } from './update.js'
24
+ import { checkUpdates, fetchReleaseNotes, locateInstall, updateTo } from './update.js'
25
25
  import { applyTraySettings, normalizeSettings, readSettings, writeSettings } from './settings.js'
26
26
 
27
27
  export const name = 'dsh-app-controls'
@@ -40,18 +40,27 @@ const CONTROL_DISABLED = process.env.DSH_APP_CONTROLS_DISABLE_SOCKET === '1'
40
40
  const QUIT_PATH = '/api/dsh-app-controls/quit'
41
41
  const UPDATE_PATH = '/api/dsh-app-controls/update'
42
42
  const PROGRESS_PATH = '/api/dsh-app-controls/update-progress'
43
+ const UPDATE_DEFER_PATH = '/api/dsh-app-controls/update/defer'
43
44
  const STATE_PATH = '/api/dsh-app-controls/state'
44
45
  const SETTINGS_PATH = '/api/dsh-app-controls/settings'
45
46
  const CACHE_PATH = '/api/dsh-app-controls/cache'
46
47
  const CACHE_CLEAN_PATH = '/api/dsh-app-controls/cache/clean'
48
+ const VIEW_HANDLED_PATH = '/api/dsh-app-controls/view-handled'
49
+ const UPDATE_DEFER_FILE = path.join(STATE_DIR, 'update-defer.json')
47
50
 
48
51
  const UPDATE_CACHE_TTL_MS = 5 * 60 * 1000
52
+ const AUTO_CHECK_INTERVAL_MS = 30 * 60 * 1000
53
+ const VIEW_TTL_MS = 30 * 1000
54
+ const AUTO_CHECK_DISABLED = process.env.DSH_APP_CONTROLS_DISABLE_AUTO_UPDATE === '1'
49
55
  const UPDATE_EXIT_DELAY_MS = 3000
50
56
  const TRAY_UPDATE_EXIT_DELAY_MS = 4500
51
57
  const QUIT_EXIT_DELAY_MS = 800
52
58
  const TRAY_QUIT_EXIT_DELAY_MS = 4500
53
59
  const SERVER_STARTED_AT = Date.now()
54
60
  let cacheRunning = false
61
+ let pendingView = null
62
+ let viewSequence = 0
63
+ let autoCheckTimer = null
55
64
 
56
65
  function describe(value) {
57
66
  if (typeof value === 'string') return value
@@ -168,8 +177,105 @@ function jobSnapshot() {
168
177
  }
169
178
 
170
179
  const updateCache = { checkedAt: 0, value: null }
180
+ const releaseNotesCache = new Map()
171
181
  const quitState = { requested: false }
172
182
 
183
+ /** Persist "remind me later" across the service restart/update flow. */
184
+ function readUpdateDefer() {
185
+ try {
186
+ const parsed = JSON.parse(readFileSync(UPDATE_DEFER_FILE, 'utf8'))
187
+ const until = Number(parsed.until)
188
+ return Number.isFinite(until) && until > Date.now() ? until : 0
189
+ } catch {
190
+ return 0
191
+ }
192
+ }
193
+
194
+ let updateDeferUntil = readUpdateDefer()
195
+
196
+ function setUpdateDefer(until) {
197
+ updateDeferUntil = Number.isFinite(until) && until > Date.now() ? Math.round(until) : 0
198
+ try {
199
+ mkdirSync(STATE_DIR, { recursive: true, mode: 0o700 })
200
+ const temporary = `${UPDATE_DEFER_FILE}.${process.pid}.tmp`
201
+ writeFileSync(temporary, `${JSON.stringify({ until: updateDeferUntil })}\n`, { mode: 0o600 })
202
+ renameSync(temporary, UPDATE_DEFER_FILE)
203
+ } catch (error) {
204
+ log('could not persist update deferral', error)
205
+ }
206
+ }
207
+
208
+ function clearUpdateDefer() {
209
+ setUpdateDefer(0)
210
+ }
211
+
212
+ function activeWorkSnapshot(ctx) {
213
+ const items = []
214
+ const seen = new Set()
215
+ let available = false
216
+ try {
217
+ const agents = ctx.get('agents')
218
+ if (agents !== undefined && agents !== null && typeof agents.list === 'function') {
219
+ available = true
220
+ for (const agent of agents.list()) {
221
+ if (agent === null || typeof agent !== 'object' || agent.status !== 'running') continue
222
+ const id = String(agent.id ?? 'turn')
223
+ if (seen.has(`turn:${id}`)) continue
224
+ seen.add(`turn:${id}`)
225
+ items.push({ kind: 'turn', id, label: '进行中的对话' })
226
+ }
227
+ }
228
+ } catch {
229
+ // the agent service is optional in embedded hosts
230
+ }
231
+ try {
232
+ const sessions = ctx.get('sessions')
233
+ const jobs = ctx.get('jobs')
234
+ if (jobs !== undefined && jobs !== null && typeof jobs.list === 'function') {
235
+ available = true
236
+ const callers = [undefined]
237
+ if (sessions !== undefined && sessions !== null && typeof sessions.list === 'function') {
238
+ for (const session of sessions.list()) callers.push(session.id)
239
+ }
240
+ for (const caller of callers) {
241
+ let rows
242
+ try {
243
+ rows = jobs.list(caller)
244
+ } catch {
245
+ continue
246
+ }
247
+ for (const row of rows) {
248
+ if (row === null || typeof row !== 'object') continue
249
+ if (row.status !== 'running' && row.status !== 'stopping') continue
250
+ const id = String(row.id ?? 'job')
251
+ if (seen.has(`job:${id}`)) continue
252
+ seen.add(`job:${id}`)
253
+ items.push({ kind: 'job', id, label: String(row.label ?? '后台任务') })
254
+ }
255
+ }
256
+ }
257
+ } catch {
258
+ // the jobs service is optional in embedded hosts
259
+ }
260
+ return {
261
+ available,
262
+ active: items.length > 0,
263
+ count: items.length,
264
+ turns: items.filter((item) => item.kind === 'turn').length,
265
+ jobs: items.filter((item) => item.kind === 'job').length,
266
+ items: items.slice(0, 8),
267
+ }
268
+ }
269
+
270
+ function updateStatusFor(ctx, value) {
271
+ if (value === null || typeof value !== 'object') return value
272
+ return {
273
+ ...value,
274
+ activity: activeWorkSnapshot(ctx),
275
+ updateDeferUntil: updateDeferUntil > Date.now() ? updateDeferUntil : null,
276
+ }
277
+ }
278
+
173
279
  function installedVersion() {
174
280
  try {
175
281
  return locateInstall(process.argv[1]).version
@@ -190,6 +296,25 @@ function serverFacts(ctx) {
190
296
  return { host: null, port: null }
191
297
  }
192
298
 
299
+ function currentPendingView() {
300
+ if (pendingView === null) return null
301
+ if (Date.now() - pendingView.at > VIEW_TTL_MS) {
302
+ pendingView = null
303
+ return null
304
+ }
305
+ return pendingView
306
+ }
307
+
308
+ function queueView(view) {
309
+ viewSequence += 1
310
+ pendingView = {
311
+ id: `view-${Date.now()}-${viewSequence}`,
312
+ view,
313
+ at: Date.now(),
314
+ }
315
+ return pendingView
316
+ }
317
+
193
318
  function statusSnapshot(ctx) {
194
319
  const facts = serverFacts(ctx)
195
320
  return {
@@ -202,19 +327,40 @@ function statusSnapshot(ctx) {
202
327
  uptimeMs: Math.max(0, Date.now() - SERVER_STARTED_AT),
203
328
  quitRequested: quitState.requested,
204
329
  job: jobSnapshot(),
205
- update: updateCache.value,
330
+ update: updateStatusFor(ctx, updateCache.value),
206
331
  updateCheckedAt: updateCache.checkedAt || null,
332
+ updateDeferUntil: updateDeferUntil > Date.now() ? updateDeferUntil : null,
333
+ activity: activeWorkSnapshot(ctx),
334
+ pendingView: currentPendingView(),
335
+ }
336
+ }
337
+
338
+ async function releaseNotesFor(version) {
339
+ if (typeof version !== 'string' || version === '') return null
340
+ const cached = releaseNotesCache.get(version)
341
+ if (cached !== undefined && Date.now() - cached.at < 6 * 60 * 60 * 1000) return cached.value
342
+ let value = null
343
+ try {
344
+ value = await fetchReleaseNotes({ to: version, timeoutMs: 2500 })
345
+ } catch {
346
+ value = null
207
347
  }
348
+ if (value !== null) releaseNotesCache.set(version, { at: Date.now(), value })
349
+ return value
208
350
  }
209
351
 
210
- async function getUpdateStatus(force) {
352
+ async function getUpdateStatus(ctx, force) {
211
353
  if (!force && updateCache.value !== null && Date.now() - updateCache.checkedAt < UPDATE_CACHE_TTL_MS) {
212
- return updateCache.value
354
+ return updateStatusFor(ctx, updateCache.value)
355
+ }
356
+ let value = await checkUpdates()
357
+ if (value !== null && typeof value === 'object' && value.updateAvailable === true && typeof value.candidate === 'string') {
358
+ const notes = await releaseNotesFor(value.candidate)
359
+ if (notes !== null) value = { ...value, releaseNotes: notes }
213
360
  }
214
- const value = await checkUpdates()
215
361
  updateCache.value = value
216
362
  updateCache.checkedAt = Date.now()
217
- return value
363
+ return updateStatusFor(ctx, value)
218
364
  }
219
365
 
220
366
  function requestQuit(ctx, appExit, source, delayMs) {
@@ -239,6 +385,7 @@ async function runUpdateJob(ctx, appExit, status, source) {
239
385
  from: status.current,
240
386
  to: status.candidate,
241
387
  })
388
+ clearUpdateDefer()
242
389
  let exitScheduled = false
243
390
  try {
244
391
  const result = await updateTo(status.candidate, undefined, (event) => {
@@ -294,9 +441,19 @@ async function handleControlCommand(ctx, appExit, request) {
294
441
  case 'status':
295
442
  return { ...base, ...statusSnapshot(ctx) }
296
443
  case 'check-update': {
297
- const value = await getUpdateStatus(true)
444
+ const value = await getUpdateStatus(ctx, true)
298
445
  return { ...base, ok: true, update: value }
299
446
  }
447
+ case 'defer-update': {
448
+ const minutes = Number(request.minutes ?? 60)
449
+ if (!Number.isFinite(minutes) || minutes < 5 || minutes > 7 * 24 * 60) {
450
+ return { ...base, ok: false, error: 'invalid-defer', message: '推迟时间必须在 5 分钟到 7 天之间。' }
451
+ }
452
+ const until = Date.now() + Math.round(minutes * 60 * 1000)
453
+ setUpdateDefer(until)
454
+ log(`update deferred for ${minutes} minutes`)
455
+ return { ...base, ok: true, updateDeferUntil: until }
456
+ }
300
457
  case 'update': {
301
458
  if (job.active) {
302
459
  return { ...base, ok: false, error: 'update-in-progress', message: '已有更新正在进行。' }
@@ -307,7 +464,7 @@ async function handleControlCommand(ctx, appExit, request) {
307
464
  if (appExit === undefined) {
308
465
  return { ...base, ok: false, error: 'no-exit-hook', message: '当前宿主没有退出接口。' }
309
466
  }
310
- const value = await getUpdateStatus(true)
467
+ const value = await getUpdateStatus(ctx, true)
311
468
  if (!value.updateAvailable) {
312
469
  return { ...base, ok: false, error: 'up-to-date', update: value, message: `已是最新版本(${value.current})。` }
313
470
  }
@@ -315,6 +472,15 @@ async function handleControlCommand(ctx, appExit, request) {
315
472
  void runUpdateJob(ctx, appExit, value, 'tray')
316
473
  return { ...base, ok: true, started: true, from: value.current, to: value.candidate }
317
474
  }
475
+ case 'open-view': {
476
+ const view = typeof request.view === 'string' ? request.view : ''
477
+ if (view !== 'plugins' && view !== 'settings') {
478
+ return { ...base, ok: false, error: 'invalid-view', message: `未知视图:${view}` }
479
+ }
480
+ const pending = queueView(view)
481
+ log(`tray requested view ${view}`)
482
+ return { ...base, ok: true, pendingView: pending }
483
+ }
318
484
  case 'quit': {
319
485
  if (job.active) {
320
486
  return { ...base, ok: false, error: 'update-in-progress', message: '正在更新,请等待完成。' }
@@ -406,7 +572,23 @@ function createControlServer(ctx, getAppExit) {
406
572
  }
407
573
  }
408
574
 
575
+ function startUpdateAutoCheck(ctx) {
576
+ if (AUTO_CHECK_DISABLED || autoCheckTimer !== null) return
577
+ const tick = async () => {
578
+ try {
579
+ if (readSettings().update.autoCheck) await getUpdateStatus(ctx, true)
580
+ } catch (error) {
581
+ log('background update check failed', error)
582
+ }
583
+ autoCheckTimer = setTimeout(tick, AUTO_CHECK_INTERVAL_MS)
584
+ if (typeof autoCheckTimer.unref === 'function') autoCheckTimer.unref()
585
+ }
586
+ autoCheckTimer = setTimeout(tick, 15 * 1000)
587
+ if (typeof autoCheckTimer.unref === 'function') autoCheckTimer.unref()
588
+ }
589
+
409
590
  export function apply(ctx) {
591
+ startUpdateAutoCheck(ctx)
410
592
  ctx.connection.fetch.register({
411
593
  path: QUIT_PATH,
412
594
  methods: ['POST'],
@@ -441,7 +623,7 @@ export function apply(ctx) {
441
623
  fetch: async (request) => {
442
624
  if (request.method === 'GET') {
443
625
  try {
444
- return json(200, await getUpdateStatus(false))
626
+ return json(200, await getUpdateStatus(ctx, false))
445
627
  } catch (error) {
446
628
  log('update check failed', error)
447
629
  return json(502, {
@@ -477,7 +659,7 @@ export function apply(ctx) {
477
659
  })
478
660
  }
479
661
  try {
480
- const status = await getUpdateStatus(true)
662
+ const status = await getUpdateStatus(ctx, true)
481
663
  if (!status.updateAvailable) {
482
664
  return json(409, {
483
665
  ok: false,
@@ -493,6 +675,7 @@ export function apply(ctx) {
493
675
  started: true,
494
676
  from: status.current,
495
677
  to: status.candidate,
678
+ activity: status.activity,
496
679
  })
497
680
  } catch (error) {
498
681
  log('update start failed', error)
@@ -505,6 +688,37 @@ export function apply(ctx) {
505
688
  },
506
689
  })
507
690
 
691
+ ctx.connection.fetch.register({
692
+ path: UPDATE_DEFER_PATH,
693
+ methods: ['POST'],
694
+ requestBody: 'buffered',
695
+ fetch: async (request) => {
696
+ const refusal = remoteRefusal(ctx)
697
+ if (refusal !== undefined) return refusal
698
+ if (job.active) {
699
+ return json(409, {
700
+ ok: false,
701
+ error: 'update-in-progress',
702
+ message: '更新已经开始,无法再推迟。',
703
+ })
704
+ }
705
+ let body
706
+ try {
707
+ body = await request.json()
708
+ } catch {
709
+ return json(400, { ok: false, error: 'invalid-json', message: '推迟请求不是合法 JSON。' })
710
+ }
711
+ const minutes = Number(body?.minutes ?? 60)
712
+ if (!Number.isFinite(minutes) || minutes < 5 || minutes > 7 * 24 * 60) {
713
+ return json(400, { ok: false, error: 'invalid-defer', message: '推迟时间必须在 5 分钟到 7 天之间。' })
714
+ }
715
+ const until = Date.now() + Math.round(minutes * 60 * 1000)
716
+ setUpdateDefer(until)
717
+ log(`web update deferred for ${minutes} minutes`)
718
+ return json(200, { ok: true, updateDeferUntil: until })
719
+ },
720
+ })
721
+
508
722
  ctx.connection.fetch.register({
509
723
  path: PROGRESS_PATH,
510
724
  methods: ['GET'],
@@ -514,6 +728,25 @@ export function apply(ctx) {
514
728
  },
515
729
  })
516
730
 
731
+ ctx.connection.fetch.register({
732
+ path: VIEW_HANDLED_PATH,
733
+ methods: ['POST'],
734
+ requestBody: 'buffered',
735
+ fetch: async (request) => {
736
+ const refusal = remoteRefusal(ctx)
737
+ if (refusal !== undefined) return refusal
738
+ let body
739
+ try {
740
+ body = await request.json()
741
+ } catch {
742
+ return json(400, { ok: false, error: 'invalid-json', message: '导航确认不是合法 JSON。' })
743
+ }
744
+ const id = body !== null && typeof body === 'object' && typeof body.id === 'string' ? body.id : ''
745
+ if (pendingView !== null && pendingView.id === id) pendingView = null
746
+ return json(200, { ok: true })
747
+ },
748
+ })
749
+
517
750
  ctx.connection.fetch.register({
518
751
  path: STATE_PATH,
519
752
  methods: ['GET'],
@@ -548,6 +781,8 @@ export function apply(ctx) {
548
781
  ...patch,
549
782
  features: { ...current.features, ...(patch.features ?? {}) },
550
783
  window: { ...current.window, ...(patch.window ?? {}) },
784
+ trayIcon: { ...current.trayIcon, ...(patch.trayIcon ?? {}) },
785
+ update: { ...current.update, ...(patch.update ?? {}) },
551
786
  })
552
787
  writeSettings(next)
553
788
  applyTraySettings(next, log)
package/lib/settings.js CHANGED
@@ -37,6 +37,14 @@ export const DEFAULT_SETTINGS = {
37
37
  width: 1400,
38
38
  height: 900,
39
39
  },
40
+ trayIcon: {
41
+ style: 'deepseek',
42
+ customPath: '',
43
+ },
44
+ update: {
45
+ autoCheck: true,
46
+ deferMinutes: 60,
47
+ },
40
48
  }
41
49
 
42
50
  function asBoolean(value, fallback) {
@@ -54,6 +62,14 @@ export function normalizeSettings(input) {
54
62
  const source = input !== null && typeof input === 'object' ? input : {}
55
63
  const features = source.features !== null && typeof source.features === 'object' ? source.features : {}
56
64
  const window = source.window !== null && typeof source.window === 'object' ? source.window : {}
65
+ const trayIcon = source.trayIcon !== null && typeof source.trayIcon === 'object' ? source.trayIcon : {}
66
+ const update = source.update !== null && typeof source.update === 'object' ? source.update : {}
67
+ const trayStyle = ['deepseek', 'classic', 'custom'].includes(trayIcon.style) ? trayIcon.style : DEFAULT_SETTINGS.trayIcon.style
68
+ const customPath = typeof trayIcon.customPath === 'string' ? trayIcon.customPath.trim().slice(0, 1024) : ''
69
+ const deferNumber = Number(update.deferMinutes)
70
+ const deferMinutes = Number.isFinite(deferNumber) && deferNumber >= 5 && deferNumber <= 7 * 24 * 60
71
+ ? Math.round(deferNumber)
72
+ : DEFAULT_SETTINGS.update.deferMinutes
57
73
  let width = asSize(window.width)
58
74
  let height = asSize(window.height)
59
75
  if (width === 0 || height === 0) {
@@ -70,6 +86,11 @@ export function normalizeSettings(input) {
70
86
  mainOverlay: asBoolean(features.mainOverlay, DEFAULT_SETTINGS.features.mainOverlay),
71
87
  },
72
88
  window: { width, height },
89
+ trayIcon: { style: trayStyle, customPath },
90
+ update: {
91
+ autoCheck: asBoolean(update.autoCheck, DEFAULT_SETTINGS.update.autoCheck),
92
+ deferMinutes,
93
+ },
73
94
  }
74
95
  }
75
96