dsh-notify-tray 0.1.5 → 0.1.7

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.
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Routes for the browser half.
3
+ *
4
+ * `GET notify-tray/state` has two weights:
5
+ * - `?lite=1` — what every DSH window polls every two seconds: new notices,
6
+ * the cursor, and tray clicks to open. Nothing about money is computed.
7
+ * - the full state for the settings page, with a `rev`: a page that sends
8
+ * back the `rev` it holds gets `unchanged: true` instead of the same
9
+ * snapshot again.
10
+ */
11
+ import { createHash } from 'node:crypto'
12
+ import { publicCatalog } from '../catalog.js'
13
+ import { spendOf, TITLES } from '../format.js'
14
+ import { desktopHosted } from '../system.js'
15
+ import { speak } from '../voice.js'
16
+
17
+ const STATE_PATH = '/notify-tray/state'
18
+ const CATALOG_PATH = '/notify-tray/catalog'
19
+ const REFRESH_PATH = '/notify-tray/refresh'
20
+ const TRAY_PATH = '/notify-tray/tray'
21
+ const RAISE_PATH = '/notify-tray/raise'
22
+ /**
23
+ * A clicked Windows toast can only launch `dsh://open` (or the web GUI), so no
24
+ * session travels with it: a window that comes forward within this long after
25
+ * a toast opens the session that toast announced.
26
+ */
27
+ const TOAST_CLAIM_MS = 60_000
28
+
29
+ /** Short content hash of a snapshot: equal snapshots, equal rev. */
30
+ export function revOf(snapshot) {
31
+ return createHash('sha1').update(JSON.stringify(snapshot)).digest('base64url').slice(0, 12)
32
+ }
33
+
34
+ export function setupRoutes(ctx, host) {
35
+ const { cfg, tracker } = host
36
+ ctx.inject(['webServer', 'connection'], (ctx) => {
37
+ host.webOrigin = () => ctx.webServer.getOrigin?.()
38
+ const guard = (req, res, method) => {
39
+ const rejection = ctx.connection.requestRejection(req)
40
+ if (rejection !== undefined) {
41
+ res.statusCode = rejection
42
+ res.end()
43
+ return false
44
+ }
45
+ if (req.method !== method) {
46
+ res.statusCode = 405
47
+ res.setHeader('allow', method)
48
+ res.end()
49
+ return false
50
+ }
51
+ return true
52
+ }
53
+ const json = (res, body) => {
54
+ res.statusCode = 200
55
+ res.setHeader('content-type', 'application/json; charset=utf-8')
56
+ res.setHeader('cache-control', 'no-store')
57
+ res.end(JSON.stringify(body))
58
+ }
59
+ /** Everything the settings page shows; only computed when a page asks. */
60
+ const snapshot = () => {
61
+ const currentUsage = host.usage()
62
+ return {
63
+ // The settings page shows only what this OS has (no status-bar section on Windows).
64
+ platform: process.platform,
65
+ summary: tracker.summary(),
66
+ usage: currentUsage,
67
+ // Today's figure exactly as the tray shows it, for the settings page's spend card.
68
+ spend: spendOf(currentUsage, cfg.spendSource) ?? null,
69
+ pricing: host.pricing(),
70
+ plan: host.plan(),
71
+ catalogLoaded: Boolean(host.pi),
72
+ tray: host.trayStatus(),
73
+ }
74
+ }
75
+ ctx.effect(() => ctx.webServer.register({
76
+ kind: 'exact',
77
+ path: STATE_PATH,
78
+ handler: (req, res) => {
79
+ if (!guard(req, res, 'GET')) return
80
+ const url = new URL(String(req.url), 'http://localhost')
81
+ // Only a window that can actually show notifications counts as listening;
82
+ // a browser tab without permission must not silence the system channel.
83
+ if (url.searchParams.get('notify') === '1') host.lastClientPoll = Date.now()
84
+ const after = Number(url.searchParams.get('after') ?? '-1')
85
+ // A window that just came forward after a toast takes that toast's session, once.
86
+ if (url.searchParams.get('claim') === '1' && host.toastPending) {
87
+ if (Date.now() - host.toastPending.at < TOAST_CLAIM_MS) host.focusQueue.push(host.toastPending.sessionId)
88
+ host.toastPending = undefined
89
+ }
90
+ const channel = cfg.channel
91
+ const clientSide = channel === 'auto' || channel === 'client' || channel === 'both'
92
+ const body = {
93
+ boot: host.boot,
94
+ seq: host.notices.seq,
95
+ // A first poll (after = -1) only learns the cursor; history is never replayed.
96
+ // Each notice carries its wording, so the window shows exactly what the host would.
97
+ events: clientSide && after >= 0
98
+ ? host.notices.after(after).map(n => (n.kind === 'show' ? { ...n, display: speak(n) } : n))
99
+ : [],
100
+ titles: TITLES,
101
+ suppressWhenFocused: cfg.suppressWhenFocused,
102
+ focus: host.focusQueue,
103
+ }
104
+ host.focusQueue = []
105
+ if (url.searchParams.get('lite') === '1') return void json(res, body)
106
+ const snap = snapshot()
107
+ const rev = revOf(snap)
108
+ if (url.searchParams.get('rev') === rev) return void json(res, { ...body, rev, unchanged: true })
109
+ json(res, { ...body, ...snap, rev })
110
+ },
111
+ }), `notify-tray: GET ${STATE_PATH}`)
112
+ ctx.effect(() => ctx.webServer.register({
113
+ kind: 'exact',
114
+ path: CATALOG_PATH,
115
+ handler: (req, res) => {
116
+ if (!guard(req, res, 'GET')) return
117
+ json(res, { providers: publicCatalog(), piLoaded: Boolean(host.pi), piFile: host.pi?.file })
118
+ },
119
+ }), `notify-tray: GET ${CATALOG_PATH}`)
120
+ ctx.effect(() => ctx.webServer.register({
121
+ kind: 'exact',
122
+ path: REFRESH_PATH,
123
+ handler: (req, res) => {
124
+ if (!guard(req, res, 'POST')) return
125
+ host.pollQuota(true)
126
+ .then(result => json(res, { quota: result ?? null, plan: host.plan() }))
127
+ .catch(error => json(res, { quota: { ok: false, at: Date.now(), error: String(error?.message ?? error) }, plan: host.plan() }))
128
+ },
129
+ }), `notify-tray: POST ${REFRESH_PATH}`)
130
+ // A click on an in-window notification: the renderer cannot change the OS
131
+ // foreground, so in the Windows desktop app the host relaunches it, and the
132
+ // single-instance handler restores a minimized window (a visible window
133
+ // behind another one stays put: Windows' foreground lock, see issue #4).
134
+ ctx.effect(() => ctx.webServer.register({
135
+ kind: 'exact',
136
+ path: RAISE_PATH,
137
+ handler: (req, res) => {
138
+ if (!guard(req, res, 'POST')) return
139
+ const raise = process.platform === 'win32' && desktopHosted() ? host.open() : Promise.resolve(false)
140
+ raise.then(raised => json(res, { raised: Boolean(raised) }))
141
+ },
142
+ }), `notify-tray: POST ${RAISE_PATH}`)
143
+ // The settings page's "show the whale again": undoes the tray menu's hide.
144
+ ctx.effect(() => ctx.webServer.register({
145
+ kind: 'exact',
146
+ path: TRAY_PATH,
147
+ handler: (req, res) => {
148
+ if (!guard(req, res, 'POST')) return
149
+ Promise.resolve(host.showTrayAgain())
150
+ .catch(() => {})
151
+ .then(() => json(res, { tray: host.trayStatus() }))
152
+ },
153
+ }), `notify-tray: POST ${TRAY_PATH}`)
154
+ })
155
+ }
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Money: the spend ledger on disk, the price catalog it is priced with, the
3
+ * plan's quota reading, and the DeepSeek account balance.
4
+ */
5
+ import { findDshVersion, findPiCatalogFile, loadPiCatalog, npmGlobalDshDir } from '../pricing.js'
6
+ import { fetchQuota, runQuotaPlan } from '../quota.js'
7
+
8
+ /** Harness version sent as account client metadata when the installed one cannot be read. */
9
+ const DSH_VERSION_FALLBACK = '0.2.1-rc.2'
10
+ /** How often a price catalog that was not found is looked for again. */
11
+ const CATALOG_RETRY_MS = 10 * 60_000
12
+
13
+ export function setupSpend(ctx, host) {
14
+ const { cfg, logger, ledger, debug } = host
15
+
16
+ // ---- ledger persistence -------------------------------------------------
17
+ ctx.effect(() => {
18
+ ledger.load().then(host.refresh)
19
+ const timer = setInterval(() => ledger.save().catch(() => {}), 30_000)
20
+ return () => {
21
+ clearInterval(timer)
22
+ ledger.save().catch(() => {})
23
+ }
24
+ }, 'notify-tray: ledger')
25
+
26
+ // ---- pi-ai price catalog (the one DSH's model selector reads) -------------
27
+ // Not found at startup (an install layout we do not guess, npm still busy…):
28
+ // ask npm once, then keep looking every few minutes until it turns up.
29
+ ctx.effect(() => {
30
+ let disposed = false
31
+ let timer
32
+ let askedNpm = false
33
+ const attempt = async () => {
34
+ let loaded = await loadPiCatalog()
35
+ if (!loaded && !askedNpm) {
36
+ askedNpm = true
37
+ const dir = await npmGlobalDshDir()
38
+ const file = dir ? findPiCatalogFile([dir]) : undefined
39
+ if (file) loaded = await loadPiCatalog({ file })
40
+ }
41
+ if (disposed) return
42
+ if (!loaded) {
43
+ timer = setTimeout(() => attempt().catch(() => {}), CATALOG_RETRY_MS)
44
+ timer.unref?.()
45
+ return
46
+ }
47
+ host.pi = loaded
48
+ debug('pi catalog', loaded.file)
49
+ host.refresh()
50
+ }
51
+ attempt().catch(() => {})
52
+ return () => {
53
+ disposed = true
54
+ clearTimeout(timer)
55
+ }
56
+ }, 'notify-tray: price catalog')
57
+
58
+ // ---- plan quota polling ---------------------------------------------------
59
+ let polling
60
+ host.pollQuota = async (force = false) => {
61
+ const spec = host.quotaSpec()
62
+ const ref = (cfg.planApiKeyEnv ?? '').trim()
63
+ const signature = host.quotaSignature()
64
+ if (!spec || !ref || (!force && !cfg.planAutoQuota)) {
65
+ if (host.quota !== undefined) { host.quota = undefined; host.refresh() }
66
+ return undefined
67
+ }
68
+ if (polling) return polling
69
+ polling = (async () => {
70
+ // The key DSH's Models page saved first, then the environment variable of the same name.
71
+ let saved
72
+ const reading = await runQuotaPlan([
73
+ {
74
+ id: 'saved',
75
+ label: 'DSH 保存的 Key',
76
+ available: async () => {
77
+ const credentials = ctx.get('credentials')
78
+ if (!credentials) return '这个 DSH 没有 Key 存储'
79
+ try {
80
+ saved = (await credentials.resolve(ref))?.value
81
+ } catch (error) {
82
+ debug('credential', String(error))
83
+ return '读取失败'
84
+ }
85
+ return saved ? true : `没有保存 ${ref}`
86
+ },
87
+ fetch: () => fetchQuota(spec, saved),
88
+ },
89
+ {
90
+ id: 'env',
91
+ label: '环境变量',
92
+ available: () => {
93
+ const value = process.env[ref]
94
+ if (!value) return `没有设置 ${ref}`
95
+ return value === saved ? '和保存的 Key 相同,不再重试' : true
96
+ },
97
+ fetch: () => fetchQuota(spec, process.env[ref]),
98
+ },
99
+ ], { noneError: `没找到 API Key:${ref} 没有保存,也没有设置为环境变量` })
100
+ host.quota = { ...reading, signature, spec: { kind: spec.kind, url: spec.url } }
101
+ debug('quota', host.quota)
102
+ host.refresh()
103
+ return host.quota
104
+ })().finally(() => { polling = undefined })
105
+ return polling
106
+ }
107
+ ctx.effect(() => {
108
+ let timer
109
+ let lastSignature = host.quotaSignature()
110
+ let lastPoll = 0
111
+ const tick = () => {
112
+ const signature = host.quotaSignature()
113
+ const due = Date.now() - lastPoll >= Math.max(1, cfg.quotaPollMinutes) * 60_000
114
+ if (signature !== lastSignature || due) {
115
+ lastSignature = signature
116
+ lastPoll = Date.now()
117
+ host.pollQuota().catch(() => {})
118
+ }
119
+ timer = setTimeout(tick, 15_000)
120
+ }
121
+ tick()
122
+ return () => clearTimeout(timer)
123
+ }, 'notify-tray: quota poll')
124
+
125
+ // ---- DeepSeek account balance (optional service) ------------------------
126
+ ctx.inject(['deepseekAccount'], (ctx) => {
127
+ const client = {
128
+ // Mirrors DSH's own settings page: the installed harness version and the UI locale.
129
+ version: findDshVersion() ?? DSH_VERSION_FALLBACK,
130
+ locale: 'zh-CN',
131
+ timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60,
132
+ }
133
+ const poll = async () => {
134
+ try {
135
+ const balance = await ctx.deepseekAccount.getBalance(client)
136
+ if (balance?.status === 'ready') ledger.balance(balance.value)
137
+ if (host.account.usageUrl === undefined) {
138
+ const state = await ctx.deepseekAccount.getState?.()
139
+ host.account.usageUrl = state?.links?.usageUrl
140
+ }
141
+ } catch (error) {
142
+ logger.debug?.('读取账户余额失败', error)
143
+ }
144
+ }
145
+ ctx.effect(() => {
146
+ let timer
147
+ const loop = () => {
148
+ poll()
149
+ timer = setTimeout(loop, Math.max(1, cfg.balancePollMinutes) * 60_000)
150
+ }
151
+ loop()
152
+ return () => clearTimeout(timer)
153
+ }, 'notify-tray: balance poll')
154
+ // A finished turn is when spend lands; refresh shortly after.
155
+ ctx.on('agent/status', ({ status }) => {
156
+ if (status === 'idle') setTimeout(poll, 5000)
157
+ })
158
+ })
159
+ }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * The status-bar whale: keeps the per-platform tray helper running while the
3
+ * `tray` setting asks for it, feeds it views, and turns its menu clicks into
4
+ * actions. Windows has no status bar to live in (and the desktop app keeps a
5
+ * tray icon of its own): there the plugin is notifications only.
6
+ */
7
+ import { openUrl, showApp } from '../system.js'
8
+ import { startTray } from '../tray/index.js'
9
+ import { iconSpec } from '../whale.js'
10
+
11
+ /** Platforms with a status bar the whale can live in. */
12
+ export const TRAY_PLATFORMS = new Set(['darwin', 'linux', 'freebsd'])
13
+
14
+ export function setupTray(ctx, host) {
15
+ const { cfg, logger, tracker, ledger } = host
16
+ let tray
17
+ let refreshTimer
18
+ host.refresh = () => {
19
+ if (refreshTimer) return
20
+ // Coalesce bursts (streaming usage samples) into one tray update.
21
+ refreshTimer = setTimeout(() => {
22
+ refreshTimer = undefined
23
+ try { tray?.update(host.view()) } catch (error) { logger.warn('更新状态栏失败', error) }
24
+ }, 300)
25
+ }
26
+ tracker.onChange(host.refresh)
27
+ ledger.onChange(host.refresh)
28
+ // "已运行 n 分钟" in the menu ticks even when nothing else changes.
29
+ ctx.effect(() => {
30
+ const timer = setInterval(() => { if (tracker.summary().running > 0) host.refresh() }, 60_000)
31
+ return () => clearInterval(timer)
32
+ }, 'notify-tray: minute tick')
33
+
34
+ host.open = () => showApp({ webOrigin: host.webOrigin }).catch(() => false)
35
+ host.onAction = action => {
36
+ if (action === 'show-app') return void host.open()
37
+ if (action === 'usage-page' && host.account.usageUrl) return void openUrl(host.account.usageUrl)
38
+ if (action === 'refresh-quota') return void host.pollQuota(true)
39
+ if (action.startsWith('url:')) return void openUrl(action.slice(4))
40
+ if (action === 'hide-tray') {
41
+ // Hidden for this run only: the settings page offers to bring it back.
42
+ trayHidden = true
43
+ host.syncTray()
44
+ return
45
+ }
46
+ if (action.startsWith('open:')) {
47
+ host.focusQueue.push(action.slice(5))
48
+ host.open()
49
+ }
50
+ }
51
+
52
+ // The icon follows the `tray` setting live, and "隐藏状态栏图标" in its menu
53
+ // hides it until the settings page (or a restart) brings it back.
54
+ let trayHidden = false
55
+ let trayStarting
56
+ let trayDisposed = false
57
+ /** A start that failed (no D-Bus, no tray host…) is not retried until the setting or the page asks again. */
58
+ let trayFailed = false
59
+ const trayWanted = () => Boolean(cfg.tray) && !trayHidden && !trayDisposed && TRAY_PLATFORMS.has(process.platform)
60
+ const stopTray = () => {
61
+ const t = tray
62
+ tray = undefined
63
+ return t?.stop()
64
+ }
65
+ host.syncTray = () => {
66
+ if (trayStarting) return trayStarting
67
+ if (!trayWanted()) return stopTray()
68
+ if (tray) return undefined
69
+ trayStarting = startTray({ stateDir: host.dir, icon: iconSpec(), onAction: host.onAction, logger })
70
+ .then(t => {
71
+ if (!trayWanted()) return void t.stop()
72
+ tray = t
73
+ tray.update(host.view())
74
+ })
75
+ .catch(error => {
76
+ trayFailed = true
77
+ logger.warn('状态栏图标启动失败,只保留通知功能', error)
78
+ })
79
+ .finally(() => {
80
+ trayStarting = undefined
81
+ // The setting may have flipped while the helper was starting.
82
+ if (!trayFailed && Boolean(tray) !== trayWanted()) host.syncTray()
83
+ })
84
+ return trayStarting
85
+ }
86
+ /** The settings page's "show the whale again": undoes the tray menu's hide. */
87
+ host.showTrayAgain = () => {
88
+ trayHidden = false
89
+ trayFailed = false
90
+ return host.syncTray()
91
+ }
92
+ host.trayStatus = () => ({
93
+ supported: TRAY_PLATFORMS.has(process.platform),
94
+ enabled: Boolean(cfg.tray),
95
+ hidden: trayHidden,
96
+ shown: Boolean(tray),
97
+ failed: trayFailed,
98
+ })
99
+ ctx.effect(() => {
100
+ trayDisposed = false
101
+ host.syncTray()
102
+ // Settings fields are read live; a cheap check picks up a flipped toggle without a restart.
103
+ let enabled = Boolean(cfg.tray)
104
+ const timer = setInterval(() => {
105
+ if (Boolean(cfg.tray) !== enabled) {
106
+ enabled = Boolean(cfg.tray)
107
+ trayFailed = false
108
+ // Switching the setting back on also undoes a hide from the tray menu.
109
+ if (enabled) trayHidden = false
110
+ }
111
+ if (!trayFailed && !trayStarting && Boolean(tray) !== trayWanted()) host.syncTray()
112
+ }, 2000)
113
+ return () => {
114
+ trayDisposed = true
115
+ clearInterval(timer)
116
+ clearTimeout(refreshTimer)
117
+ stopTray()
118
+ }
119
+ }, 'notify-tray: tray')
120
+ }