dsh-notify-tray 0.1.6 → 0.1.8
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/README.en.md +109 -0
- package/README.md +78 -150
- package/README.zh-CN.md +85 -129
- package/assets/mascot-peeking.png +0 -0
- package/assets/mascot-peeking.prompt.txt +6 -0
- package/lib/catalog.js +11 -3
- package/lib/client.js +426 -57
- package/lib/format.js +1 -1
- package/lib/host/context.js +89 -0
- package/lib/host/notify.js +89 -0
- package/lib/host/routes.js +170 -0
- package/lib/host/spend.js +159 -0
- package/lib/host/tray.js +120 -0
- package/lib/index.js +16 -488
- package/lib/models-dev.json +2684 -0
- package/lib/notices.js +119 -0
- package/lib/pricing.js +31 -3
- package/lib/quota.js +46 -2
- package/lib/system.js +60 -10
- package/lib/tracker.js +7 -0
- package/lib/tray/linux.js +34 -7
- package/lib/voice.js +19 -1
- package/locale/en.json +2 -1
- package/locale/zh.json +2 -1
- package/package.json +10 -6
package/lib/index.js
CHANGED
|
@@ -15,54 +15,22 @@
|
|
|
15
15
|
* browser half, which shows native notifications from the DSH window and
|
|
16
16
|
* renders the settings page; when no window is polling, the host falls
|
|
17
17
|
* back to OS notifications itself.
|
|
18
|
+
*
|
|
19
|
+
* Each concern lives in lib/host/ and shares one `host` object (context.js):
|
|
20
|
+
* tray.js, notify.js, spend.js, routes.js.
|
|
18
21
|
*/
|
|
19
22
|
import z from '@deepseek-ai/schemastery'
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
24
|
-
import {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
import { fetchQuota } from './quota.js'
|
|
28
|
-
import { consumeClicks, desktopHosted, openUrl, showApp, systemNotify, terminalNotifier } from './system.js'
|
|
29
|
-
import { startTray } from './tray/index.js'
|
|
30
|
-
import { Tracker } from './tracker.js'
|
|
31
|
-
import { speak } from './voice.js'
|
|
32
|
-
import { iconSpec } from './whale.js'
|
|
23
|
+
import { createHost } from './host/context.js'
|
|
24
|
+
import { setupNotifications } from './host/notify.js'
|
|
25
|
+
import { setupRoutes } from './host/routes.js'
|
|
26
|
+
import { setupSpend } from './host/spend.js'
|
|
27
|
+
import { setupTray } from './host/tray.js'
|
|
28
|
+
|
|
29
|
+
export { TRAY_PLATFORMS } from './host/tray.js'
|
|
33
30
|
|
|
34
31
|
export const name = 'notify-tray'
|
|
35
32
|
export const inject = ['agents']
|
|
36
33
|
|
|
37
|
-
const STATE_PATH = '/notify-tray/state'
|
|
38
|
-
const CATALOG_PATH = '/notify-tray/catalog'
|
|
39
|
-
const REFRESH_PATH = '/notify-tray/refresh'
|
|
40
|
-
const TRAY_PATH = '/notify-tray/tray'
|
|
41
|
-
const RAISE_PATH = '/notify-tray/raise'
|
|
42
|
-
/**
|
|
43
|
-
* A clicked Windows toast can only launch `dsh://open` (or the web GUI), so no
|
|
44
|
-
* session travels with it: a window that comes forward within this long after
|
|
45
|
-
* a toast opens the session that toast announced.
|
|
46
|
-
*/
|
|
47
|
-
const TOAST_CLAIM_MS = 60_000
|
|
48
|
-
/** Harness version sent as account client metadata when the installed one cannot be read. */
|
|
49
|
-
const DSH_VERSION_FALLBACK = '0.2.1-rc.2'
|
|
50
|
-
/** How often a price catalog that was not found is looked for again. */
|
|
51
|
-
const CATALOG_RETRY_MS = 10 * 60_000
|
|
52
|
-
/** A window that polled within this window counts as "listening". */
|
|
53
|
-
const CLIENT_FRESH_MS = 8000
|
|
54
|
-
/** Platforms with a status bar the whale can live in. */
|
|
55
|
-
export const TRAY_PLATFORMS = new Set(['darwin', 'linux', 'freebsd'])
|
|
56
|
-
/** The whale's colour on a notification of each kind. */
|
|
57
|
-
const EVENT_STATE = { completed: 'done', failed: 'error', approval: 'attention', choice: 'attention', input: 'attention' }
|
|
58
|
-
const EVENT_SWITCH = {
|
|
59
|
-
completed: 'notifyCompleted',
|
|
60
|
-
failed: 'notifyFailed',
|
|
61
|
-
approval: 'notifyApproval',
|
|
62
|
-
choice: 'notifyChoice',
|
|
63
|
-
input: 'notifyInput',
|
|
64
|
-
}
|
|
65
|
-
|
|
66
34
|
const price = z.object({
|
|
67
35
|
input: z.number().min(0).description('未命中缓存输入,每百万 token 价格'),
|
|
68
36
|
cacheRead: z.number().min(0).description('缓存命中输入,每百万 token 价格'),
|
|
@@ -132,214 +100,13 @@ export const Config = z.object({
|
|
|
132
100
|
quotaPollMinutes: z.number().min(1).max(240).default(10).description('额度刷新间隔(分钟)').volatile(),
|
|
133
101
|
})
|
|
134
102
|
|
|
135
|
-
function storageDir() {
|
|
136
|
-
const home = process.env.DSH_HOME?.trim() || join(homedir(), '.dsh')
|
|
137
|
-
return join(home, 'storages', 'dsh-notify-tray')
|
|
138
|
-
}
|
|
139
|
-
|
|
140
103
|
export function apply(ctx, config) {
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
get: (_, key) => {
|
|
145
|
-
const value = config?.[key]
|
|
146
|
-
return value !== null && typeof value === 'object' && typeof value.get === 'function' ? value.get() : value
|
|
147
|
-
},
|
|
148
|
-
})
|
|
149
|
-
const logger = ctx.logger?.('notify-tray') ?? console
|
|
150
|
-
const dir = storageDir()
|
|
151
|
-
const tracker = new Tracker()
|
|
152
|
-
const ledger = new Ledger({ file: join(dir, 'ledger.json') })
|
|
153
|
-
const account = { usageUrl: undefined }
|
|
154
|
-
/** pi-ai's model catalog (prices), once loaded. */
|
|
155
|
-
let pi
|
|
156
|
-
/** Latest plan quota reading: { ok, at, data | error, signature }. */
|
|
157
|
-
let quota
|
|
158
|
-
/** The web GUI's origin, once the web server is up: where "open DSH" goes when there is no desktop window. */
|
|
159
|
-
let webOrigin = () => undefined
|
|
160
|
-
let tray
|
|
161
|
-
/** Identifies this host run, so clients reset their cursor after a restart. */
|
|
162
|
-
const boot = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`
|
|
163
|
-
let lastClientPoll = 0
|
|
164
|
-
/** Session ids a tray click asked the window to open, consumed by the next poll. */
|
|
165
|
-
let focusQueue = []
|
|
166
|
-
/** The session the latest Windows toast announced: { sessionId, at }. */
|
|
167
|
-
let toastPending
|
|
168
|
-
|
|
169
|
-
/** Set DSH_NOTIFY_TRAY_DEBUG=1 to trace tracked events into storages/dsh-notify-tray/debug.log. */
|
|
170
|
-
const debug = process.env.DSH_NOTIFY_TRAY_DEBUG
|
|
171
|
-
? (...parts) => {
|
|
172
|
-
try {
|
|
173
|
-
mkdirSync(dir, { recursive: true })
|
|
174
|
-
appendFileSync(join(dir, 'debug.log'), `${new Date().toISOString()} ${parts.map(p => typeof p === 'string' ? p : JSON.stringify(p)).join(' ')}\n`)
|
|
175
|
-
} catch {}
|
|
176
|
-
}
|
|
177
|
-
: () => {}
|
|
178
|
-
|
|
179
|
-
/** Which endpoint the plan's quota comes from, and what identifies one reading as current. */
|
|
180
|
-
const quotaSpec = () => quotaSpecFor(cfg.planProvider, cfg.planId, cfg.planQuotaUrl)
|
|
181
|
-
const quotaSignature = () => `${cfg.planProvider}|${cfg.planId}|${cfg.planApiKeyEnv ?? ''}|${cfg.planQuotaUrl ?? ''}`
|
|
182
|
-
/** The route in use: the latest request header anywhere, else DSH's default model selection. */
|
|
183
|
-
const currentRoute = () => {
|
|
184
|
-
if (ledger.lastRoute) return ledger.lastRoute
|
|
185
|
-
try {
|
|
186
|
-
const selection = ctx.get('agentDefaultModel')?.currentSelection?.()
|
|
187
|
-
if (selection?.model) return { provider: selection.provider, model: selection.model }
|
|
188
|
-
} catch {}
|
|
189
|
-
return undefined
|
|
190
|
-
}
|
|
191
|
-
const usage = () => ({
|
|
192
|
-
...ledger.summary(makeResolver({ cfg, models: pi?.models }), cfg.currency),
|
|
193
|
-
usageUrl: account.usageUrl,
|
|
194
|
-
route: currentRoute(),
|
|
195
|
-
})
|
|
196
|
-
// A reading taken for another provider / key is never shown as this one's.
|
|
197
|
-
const plan = () => planView(cfg, quota && quota.signature === quotaSignature() ? quota : undefined)
|
|
198
|
-
const pricing = () => describeRoute({ cfg, models: pi?.models, route: currentRoute() })
|
|
199
|
-
const view = () => buildView(tracker.summary(), usage(), cfg, Date.now(), plan())
|
|
200
|
-
|
|
201
|
-
// ---- tray -------------------------------------------------------------
|
|
202
|
-
let refreshTimer
|
|
203
|
-
const refresh = () => {
|
|
204
|
-
if (refreshTimer) return
|
|
205
|
-
// Coalesce bursts (streaming usage samples) into one tray update.
|
|
206
|
-
refreshTimer = setTimeout(() => {
|
|
207
|
-
refreshTimer = undefined
|
|
208
|
-
try { tray?.update(view()) } catch (error) { logger.warn('更新状态栏失败', error) }
|
|
209
|
-
}, 300)
|
|
210
|
-
}
|
|
211
|
-
tracker.onChange(refresh)
|
|
212
|
-
ledger.onChange(refresh)
|
|
213
|
-
// "已运行 n 分钟" in the menu ticks even when nothing else changes.
|
|
214
|
-
ctx.effect(() => {
|
|
215
|
-
const timer = setInterval(() => { if (tracker.summary().running > 0) refresh() }, 60_000)
|
|
216
|
-
return () => clearInterval(timer)
|
|
217
|
-
}, 'notify-tray: minute tick')
|
|
218
|
-
|
|
219
|
-
const open = () => showApp({ webOrigin }).catch(() => false)
|
|
220
|
-
const onAction = action => {
|
|
221
|
-
if (action === 'show-app') return void open()
|
|
222
|
-
if (action === 'usage-page' && account.usageUrl) return void openUrl(account.usageUrl)
|
|
223
|
-
if (action === 'refresh-quota') return void pollQuota(true)
|
|
224
|
-
if (action.startsWith('url:')) return void openUrl(action.slice(4))
|
|
225
|
-
if (action === 'hide-tray') {
|
|
226
|
-
// Hidden for this run only: the settings page offers to bring it back.
|
|
227
|
-
trayHidden = true
|
|
228
|
-
syncTray()
|
|
229
|
-
return
|
|
230
|
-
}
|
|
231
|
-
if (action.startsWith('open:')) {
|
|
232
|
-
focusQueue.push(action.slice(5))
|
|
233
|
-
open()
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
// Windows has no status bar to live in (and the desktop app keeps a tray
|
|
238
|
-
// icon of its own): there the plugin is notifications only.
|
|
239
|
-
// The icon follows the `tray` setting live, and "隐藏状态栏图标" in its menu
|
|
240
|
-
// hides it until the settings page (or a restart) brings it back.
|
|
241
|
-
let trayHidden = false
|
|
242
|
-
let trayStarting
|
|
243
|
-
let trayDisposed = false
|
|
244
|
-
/** A start that failed (no D-Bus, no tray host…) is not retried until the setting or the page asks again. */
|
|
245
|
-
let trayFailed = false
|
|
246
|
-
const trayWanted = () => Boolean(cfg.tray) && !trayHidden && !trayDisposed && TRAY_PLATFORMS.has(process.platform)
|
|
247
|
-
const stopTray = () => {
|
|
248
|
-
const t = tray
|
|
249
|
-
tray = undefined
|
|
250
|
-
return t?.stop()
|
|
251
|
-
}
|
|
252
|
-
const syncTray = () => {
|
|
253
|
-
if (trayStarting) return trayStarting
|
|
254
|
-
if (!trayWanted()) return stopTray()
|
|
255
|
-
if (tray) return undefined
|
|
256
|
-
trayStarting = startTray({ stateDir: dir, icon: iconSpec(), onAction, logger })
|
|
257
|
-
.then(t => {
|
|
258
|
-
if (!trayWanted()) return void t.stop()
|
|
259
|
-
tray = t
|
|
260
|
-
tray.update(view())
|
|
261
|
-
})
|
|
262
|
-
.catch(error => {
|
|
263
|
-
trayFailed = true
|
|
264
|
-
logger.warn('状态栏图标启动失败,只保留通知功能', error)
|
|
265
|
-
})
|
|
266
|
-
.finally(() => {
|
|
267
|
-
trayStarting = undefined
|
|
268
|
-
// The setting may have flipped while the helper was starting.
|
|
269
|
-
if (!trayFailed && Boolean(tray) !== trayWanted()) syncTray()
|
|
270
|
-
})
|
|
271
|
-
return trayStarting
|
|
272
|
-
}
|
|
273
|
-
const trayStatus = () => ({
|
|
274
|
-
supported: TRAY_PLATFORMS.has(process.platform),
|
|
275
|
-
enabled: Boolean(cfg.tray),
|
|
276
|
-
hidden: trayHidden,
|
|
277
|
-
shown: Boolean(tray),
|
|
278
|
-
failed: trayFailed,
|
|
279
|
-
})
|
|
280
|
-
ctx.effect(() => {
|
|
281
|
-
trayDisposed = false
|
|
282
|
-
syncTray()
|
|
283
|
-
// Settings fields are read live; a cheap check picks up a flipped toggle without a restart.
|
|
284
|
-
let enabled = Boolean(cfg.tray)
|
|
285
|
-
const timer = setInterval(() => {
|
|
286
|
-
if (Boolean(cfg.tray) !== enabled) {
|
|
287
|
-
enabled = Boolean(cfg.tray)
|
|
288
|
-
trayFailed = false
|
|
289
|
-
// Switching the setting back on also undoes a hide from the tray menu.
|
|
290
|
-
if (enabled) trayHidden = false
|
|
291
|
-
}
|
|
292
|
-
if (!trayFailed && !trayStarting && Boolean(tray) !== trayWanted()) syncTray()
|
|
293
|
-
}, 2000)
|
|
294
|
-
return () => {
|
|
295
|
-
trayDisposed = true
|
|
296
|
-
clearInterval(timer)
|
|
297
|
-
clearTimeout(refreshTimer)
|
|
298
|
-
stopTray()
|
|
299
|
-
}
|
|
300
|
-
}, 'notify-tray: tray')
|
|
301
|
-
|
|
302
|
-
// ---- notifications ----------------------------------------------------
|
|
303
|
-
// A clicked macOS notification (sent through terminal-notifier) drops a file
|
|
304
|
-
// named after its session here; the host opens that session.
|
|
305
|
-
const clickDir = join(dir, 'clicks')
|
|
306
|
-
if (process.platform === 'darwin') {
|
|
307
|
-
ctx.effect(() => {
|
|
308
|
-
consumeClicks(clickDir) // stale clicks from an earlier run open nothing
|
|
309
|
-
const timer = setInterval(() => {
|
|
310
|
-
if (!terminalNotifier()) return
|
|
311
|
-
for (const id of consumeClicks(clickDir)) onAction(`open:${id}`)
|
|
312
|
-
}, 1000)
|
|
313
|
-
return () => clearInterval(timer)
|
|
314
|
-
}, 'notify-tray: notification clicks')
|
|
315
|
-
}
|
|
316
|
-
tracker.onEvent(event => {
|
|
317
|
-
debug('event', event)
|
|
318
|
-
// The celebration / error pose expires on its own: refresh once it does.
|
|
319
|
-
if (event.type === 'completed') setTimeout(refresh, DONE_HOLD_MS + 200).unref?.()
|
|
320
|
-
if (event.type === 'failed') setTimeout(refresh, Math.max(0, cfg.errorHoldMinutes) * 60_000 + 200).unref?.()
|
|
321
|
-
if (!cfg[EVENT_SWITCH[event.type]]) return
|
|
322
|
-
const clientListening = Date.now() - lastClientPoll < CLIENT_FRESH_MS
|
|
323
|
-
const channel = cfg.channel
|
|
324
|
-
const systemSide = channel === 'system' || channel === 'both' || (channel === 'auto' && !clientListening)
|
|
325
|
-
debug('deliver', { channel, clientListening, systemSide })
|
|
326
|
-
if (!systemSide) return // the window picks it up from the event queue
|
|
327
|
-
const said = speak(event)
|
|
328
|
-
if (process.platform === 'win32') toastPending = { sessionId: event.sessionId, at: Date.now() }
|
|
329
|
-
systemNotify({
|
|
330
|
-
title: said.title,
|
|
331
|
-
body: said.body,
|
|
332
|
-
sound: cfg.sound,
|
|
333
|
-
webOrigin,
|
|
334
|
-
state: EVENT_STATE[event.type],
|
|
335
|
-
iconDir: join(dir, 'icons'),
|
|
336
|
-
sessionId: event.sessionId,
|
|
337
|
-
clickDir,
|
|
338
|
-
onClick: () => onAction(`open:${event.sessionId}`),
|
|
339
|
-
}).then(ok => debug('system notify', ok)).catch(error => logger.warn('系统通知失败', error))
|
|
340
|
-
})
|
|
104
|
+
const host = createHost(ctx, config)
|
|
105
|
+
setupTray(ctx, host)
|
|
106
|
+
setupNotifications(ctx, host)
|
|
341
107
|
|
|
342
108
|
// ---- DSH events -------------------------------------------------------
|
|
109
|
+
const { tracker, ledger, logger, debug } = host
|
|
343
110
|
tracker.seed(ctx.agents.list())
|
|
344
111
|
ctx.on('agent/status', ({ agent, status }) => tracker.agentStatus(agent, status))
|
|
345
112
|
ctx.on('agent/disposed', ({ agent }) => {
|
|
@@ -356,245 +123,6 @@ export function apply(ctx, config) {
|
|
|
356
123
|
}
|
|
357
124
|
})
|
|
358
125
|
|
|
359
|
-
|
|
360
|
-
ctx
|
|
361
|
-
ledger.load().then(refresh)
|
|
362
|
-
const timer = setInterval(() => ledger.save().catch(() => {}), 30_000)
|
|
363
|
-
return () => {
|
|
364
|
-
clearInterval(timer)
|
|
365
|
-
ledger.save().catch(() => {})
|
|
366
|
-
}
|
|
367
|
-
}, 'notify-tray: ledger')
|
|
368
|
-
|
|
369
|
-
// ---- pi-ai price catalog (the one DSH's model selector reads) -------------
|
|
370
|
-
// Not found at startup (an install layout we do not guess, npm still busy…):
|
|
371
|
-
// ask npm once, then keep looking every few minutes until it turns up.
|
|
372
|
-
ctx.effect(() => {
|
|
373
|
-
let disposed = false
|
|
374
|
-
let timer
|
|
375
|
-
let askedNpm = false
|
|
376
|
-
const attempt = async () => {
|
|
377
|
-
let loaded = await loadPiCatalog()
|
|
378
|
-
if (!loaded && !askedNpm) {
|
|
379
|
-
askedNpm = true
|
|
380
|
-
const dir = await npmGlobalDshDir()
|
|
381
|
-
const file = dir ? findPiCatalogFile([dir]) : undefined
|
|
382
|
-
if (file) loaded = await loadPiCatalog({ file })
|
|
383
|
-
}
|
|
384
|
-
if (disposed) return
|
|
385
|
-
if (!loaded) {
|
|
386
|
-
timer = setTimeout(() => attempt().catch(() => {}), CATALOG_RETRY_MS)
|
|
387
|
-
timer.unref?.()
|
|
388
|
-
return
|
|
389
|
-
}
|
|
390
|
-
pi = loaded
|
|
391
|
-
debug('pi catalog', loaded.file)
|
|
392
|
-
refresh()
|
|
393
|
-
}
|
|
394
|
-
attempt().catch(() => {})
|
|
395
|
-
return () => {
|
|
396
|
-
disposed = true
|
|
397
|
-
clearTimeout(timer)
|
|
398
|
-
}
|
|
399
|
-
}, 'notify-tray: price catalog')
|
|
400
|
-
|
|
401
|
-
// ---- plan quota polling ---------------------------------------------------
|
|
402
|
-
let polling
|
|
403
|
-
const pollQuota = async (force = false) => {
|
|
404
|
-
const spec = quotaSpec()
|
|
405
|
-
const ref = (cfg.planApiKeyEnv ?? '').trim()
|
|
406
|
-
const signature = quotaSignature()
|
|
407
|
-
if (!spec || !ref || (!force && !cfg.planAutoQuota)) {
|
|
408
|
-
if (quota !== undefined) { quota = undefined; refresh() }
|
|
409
|
-
return undefined
|
|
410
|
-
}
|
|
411
|
-
if (polling) return polling
|
|
412
|
-
polling = (async () => {
|
|
413
|
-
let key
|
|
414
|
-
try {
|
|
415
|
-
const credentials = ctx.get('credentials')
|
|
416
|
-
key = credentials ? (await credentials.resolve(ref))?.value : undefined
|
|
417
|
-
if (!key) key = process.env[ref]
|
|
418
|
-
} catch (error) {
|
|
419
|
-
key = process.env[ref]
|
|
420
|
-
debug('credential', String(error))
|
|
421
|
-
}
|
|
422
|
-
const at = Date.now()
|
|
423
|
-
const reading = key
|
|
424
|
-
? await fetchQuota(spec, key)
|
|
425
|
-
: { ok: false, at, error: `没找到 API Key:${ref} 没有保存,也没有设置为环境变量` }
|
|
426
|
-
quota = { ...reading, signature, spec: { kind: spec.kind, url: spec.url } }
|
|
427
|
-
debug('quota', quota)
|
|
428
|
-
refresh()
|
|
429
|
-
return quota
|
|
430
|
-
})().finally(() => { polling = undefined })
|
|
431
|
-
return polling
|
|
432
|
-
}
|
|
433
|
-
ctx.effect(() => {
|
|
434
|
-
let timer
|
|
435
|
-
let lastSignature = quotaSignature()
|
|
436
|
-
let lastPoll = 0
|
|
437
|
-
const tick = () => {
|
|
438
|
-
const signature = quotaSignature()
|
|
439
|
-
const due = Date.now() - lastPoll >= Math.max(1, cfg.quotaPollMinutes) * 60_000
|
|
440
|
-
if (signature !== lastSignature || due) {
|
|
441
|
-
lastSignature = signature
|
|
442
|
-
lastPoll = Date.now()
|
|
443
|
-
pollQuota().catch(() => {})
|
|
444
|
-
}
|
|
445
|
-
timer = setTimeout(tick, 15_000)
|
|
446
|
-
}
|
|
447
|
-
tick()
|
|
448
|
-
return () => clearTimeout(timer)
|
|
449
|
-
}, 'notify-tray: quota poll')
|
|
450
|
-
|
|
451
|
-
// ---- DeepSeek account balance (optional service) ------------------------
|
|
452
|
-
ctx.inject(['deepseekAccount'], (ctx) => {
|
|
453
|
-
const client = {
|
|
454
|
-
// Mirrors DSH's own settings page: the installed harness version and the UI locale.
|
|
455
|
-
version: findDshVersion() ?? DSH_VERSION_FALLBACK,
|
|
456
|
-
locale: 'zh-CN',
|
|
457
|
-
timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60,
|
|
458
|
-
}
|
|
459
|
-
const poll = async () => {
|
|
460
|
-
try {
|
|
461
|
-
const balance = await ctx.deepseekAccount.getBalance(client)
|
|
462
|
-
if (balance?.status === 'ready') ledger.balance(balance.value)
|
|
463
|
-
if (account.usageUrl === undefined) {
|
|
464
|
-
const state = await ctx.deepseekAccount.getState?.()
|
|
465
|
-
account.usageUrl = state?.links?.usageUrl
|
|
466
|
-
}
|
|
467
|
-
} catch (error) {
|
|
468
|
-
logger.debug?.('读取账户余额失败', error)
|
|
469
|
-
}
|
|
470
|
-
}
|
|
471
|
-
ctx.effect(() => {
|
|
472
|
-
let timer
|
|
473
|
-
const loop = () => {
|
|
474
|
-
poll()
|
|
475
|
-
timer = setTimeout(loop, Math.max(1, cfg.balancePollMinutes) * 60_000)
|
|
476
|
-
}
|
|
477
|
-
loop()
|
|
478
|
-
return () => clearTimeout(timer)
|
|
479
|
-
}, 'notify-tray: balance poll')
|
|
480
|
-
// A finished turn is when spend lands; refresh shortly after.
|
|
481
|
-
ctx.on('agent/status', ({ status }) => {
|
|
482
|
-
if (status === 'idle') setTimeout(poll, 5000)
|
|
483
|
-
})
|
|
484
|
-
})
|
|
485
|
-
|
|
486
|
-
// ---- routes for the browser half ------------------------------------------
|
|
487
|
-
ctx.inject(['webServer', 'connection'], (ctx) => {
|
|
488
|
-
webOrigin = () => ctx.webServer.getOrigin?.()
|
|
489
|
-
const guard = (req, res, method) => {
|
|
490
|
-
const rejection = ctx.connection.requestRejection(req)
|
|
491
|
-
if (rejection !== undefined) {
|
|
492
|
-
res.statusCode = rejection
|
|
493
|
-
res.end()
|
|
494
|
-
return false
|
|
495
|
-
}
|
|
496
|
-
if (req.method !== method) {
|
|
497
|
-
res.statusCode = 405
|
|
498
|
-
res.setHeader('allow', method)
|
|
499
|
-
res.end()
|
|
500
|
-
return false
|
|
501
|
-
}
|
|
502
|
-
return true
|
|
503
|
-
}
|
|
504
|
-
const json = (res, body) => {
|
|
505
|
-
res.statusCode = 200
|
|
506
|
-
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
507
|
-
res.setHeader('cache-control', 'no-store')
|
|
508
|
-
res.end(JSON.stringify(body))
|
|
509
|
-
}
|
|
510
|
-
ctx.effect(() => ctx.webServer.register({
|
|
511
|
-
kind: 'exact',
|
|
512
|
-
path: STATE_PATH,
|
|
513
|
-
handler: (req, res) => {
|
|
514
|
-
if (!guard(req, res, 'GET')) return
|
|
515
|
-
const url = new URL(String(req.url), 'http://localhost')
|
|
516
|
-
// Only a window that can actually show notifications counts as listening;
|
|
517
|
-
// a browser tab without permission must not silence the system channel.
|
|
518
|
-
if (url.searchParams.get('notify') === '1') lastClientPoll = Date.now()
|
|
519
|
-
const after = Number(url.searchParams.get('after') ?? '-1')
|
|
520
|
-
// A window that just came forward after a toast takes that toast's session, once.
|
|
521
|
-
if (url.searchParams.get('claim') === '1' && toastPending) {
|
|
522
|
-
if (Date.now() - toastPending.at < TOAST_CLAIM_MS) focusQueue.push(toastPending.sessionId)
|
|
523
|
-
toastPending = undefined
|
|
524
|
-
}
|
|
525
|
-
const channel = cfg.channel
|
|
526
|
-
const clientSide = channel === 'auto' || channel === 'client' || channel === 'both'
|
|
527
|
-
const currentUsage = usage()
|
|
528
|
-
const enabled = Object.fromEntries(Object.entries(EVENT_SWITCH).map(([type, key]) => [type, Boolean(cfg[key])]))
|
|
529
|
-
const body = {
|
|
530
|
-
boot,
|
|
531
|
-
// The settings page shows only what this OS has (no status-bar section on Windows).
|
|
532
|
-
platform: process.platform,
|
|
533
|
-
seq: tracker.seq,
|
|
534
|
-
// A first poll (after = -1) only learns the cursor; history is never replayed.
|
|
535
|
-
// Each event carries its wording, so the window shows exactly what the host would.
|
|
536
|
-
events: clientSide && after >= 0
|
|
537
|
-
? tracker.eventsAfter(after).filter(e => enabled[e.type]).map(e => ({ ...e, display: speak(e) }))
|
|
538
|
-
: [],
|
|
539
|
-
titles: TITLES,
|
|
540
|
-
suppressWhenFocused: cfg.suppressWhenFocused,
|
|
541
|
-
focus: focusQueue,
|
|
542
|
-
summary: tracker.summary(),
|
|
543
|
-
usage: currentUsage,
|
|
544
|
-
// Today's figure exactly as the tray shows it, for the settings page's spend card.
|
|
545
|
-
spend: spendOf(currentUsage, cfg.spendSource) ?? null,
|
|
546
|
-
pricing: pricing(),
|
|
547
|
-
plan: plan(),
|
|
548
|
-
catalogLoaded: Boolean(pi),
|
|
549
|
-
tray: trayStatus(),
|
|
550
|
-
}
|
|
551
|
-
focusQueue = []
|
|
552
|
-
json(res, body)
|
|
553
|
-
},
|
|
554
|
-
}), `notify-tray: GET ${STATE_PATH}`)
|
|
555
|
-
ctx.effect(() => ctx.webServer.register({
|
|
556
|
-
kind: 'exact',
|
|
557
|
-
path: CATALOG_PATH,
|
|
558
|
-
handler: (req, res) => {
|
|
559
|
-
if (!guard(req, res, 'GET')) return
|
|
560
|
-
json(res, { providers: publicCatalog(), piLoaded: Boolean(pi), piFile: pi?.file })
|
|
561
|
-
},
|
|
562
|
-
}), `notify-tray: GET ${CATALOG_PATH}`)
|
|
563
|
-
ctx.effect(() => ctx.webServer.register({
|
|
564
|
-
kind: 'exact',
|
|
565
|
-
path: REFRESH_PATH,
|
|
566
|
-
handler: (req, res) => {
|
|
567
|
-
if (!guard(req, res, 'POST')) return
|
|
568
|
-
pollQuota(true)
|
|
569
|
-
.then(result => json(res, { quota: result ?? null, plan: plan() }))
|
|
570
|
-
.catch(error => json(res, { quota: { ok: false, at: Date.now(), error: String(error?.message ?? error) }, plan: plan() }))
|
|
571
|
-
},
|
|
572
|
-
}), `notify-tray: POST ${REFRESH_PATH}`)
|
|
573
|
-
// A click on an in-window notification: the renderer cannot change the OS
|
|
574
|
-
// foreground, so in the Windows desktop app the host relaunches it, and the
|
|
575
|
-
// single-instance handler restores a minimized window (a visible window
|
|
576
|
-
// behind another one stays put: Windows' foreground lock, see issue #4).
|
|
577
|
-
ctx.effect(() => ctx.webServer.register({
|
|
578
|
-
kind: 'exact',
|
|
579
|
-
path: RAISE_PATH,
|
|
580
|
-
handler: (req, res) => {
|
|
581
|
-
if (!guard(req, res, 'POST')) return
|
|
582
|
-
const raise = process.platform === 'win32' && desktopHosted() ? open() : Promise.resolve(false)
|
|
583
|
-
raise.then(raised => json(res, { raised: Boolean(raised) }))
|
|
584
|
-
},
|
|
585
|
-
}), `notify-tray: POST ${RAISE_PATH}`)
|
|
586
|
-
// The settings page's "show the whale again": undoes the tray menu's hide.
|
|
587
|
-
ctx.effect(() => ctx.webServer.register({
|
|
588
|
-
kind: 'exact',
|
|
589
|
-
path: TRAY_PATH,
|
|
590
|
-
handler: (req, res) => {
|
|
591
|
-
if (!guard(req, res, 'POST')) return
|
|
592
|
-
trayHidden = false
|
|
593
|
-
trayFailed = false
|
|
594
|
-
Promise.resolve(syncTray())
|
|
595
|
-
.catch(() => {})
|
|
596
|
-
.then(() => json(res, { tray: trayStatus() }))
|
|
597
|
-
},
|
|
598
|
-
}), `notify-tray: POST ${TRAY_PATH}`)
|
|
599
|
-
})
|
|
126
|
+
setupSpend(ctx, host)
|
|
127
|
+
setupRoutes(ctx, host)
|
|
600
128
|
}
|