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/lib/format.js CHANGED
@@ -18,7 +18,7 @@ export const TITLES = {
18
18
 
19
19
  const SYMBOL = { CNY: '¥', USD: '$' }
20
20
  /** Where an estimate's price came from (mirrors pricing.js, kept here so this file stays DSH-free). */
21
- const SOURCE_LABEL = { table: '价格表', custom: '自定义价', catalog: '目录价', static: '内置价' }
21
+ const SOURCE_LABEL = { table: '价格表', custom: '自定义价', catalog: '目录价', static: '内置价', modelsDev: 'models.dev 价' }
22
22
  const KIND_LABEL = {
23
23
  approval: '待批准',
24
24
  choice: '待选择',
@@ -0,0 +1,89 @@
1
+ /**
2
+ * The state every part of the host half shares: live settings, the session
3
+ * tracker, the spend ledger, and the few mutable facts (price catalog, plan
4
+ * quota, web origin…) one part learns and another shows. Each part
5
+ * (tray.js, notify.js, spend.js, routes.js) gets this one object and adds
6
+ * the functions others call on it.
7
+ */
8
+ import { appendFileSync, mkdirSync } from 'node:fs'
9
+ import { homedir } from 'node:os'
10
+ import { join } from 'node:path'
11
+ import { planView, quotaSpecFor } from '../catalog.js'
12
+ import { buildView } from '../format.js'
13
+ import { Ledger } from '../ledger.js'
14
+ import { describeRoute, makeResolver } from '../pricing.js'
15
+ import { Tracker } from '../tracker.js'
16
+
17
+ export function storageDir() {
18
+ const home = process.env.DSH_HOME?.trim() || join(homedir(), '.dsh')
19
+ return join(home, 'storages', 'dsh-notify-tray')
20
+ }
21
+
22
+ export function createHost(ctx, config) {
23
+ // Settings-page fields are volatile references (read with `.get()`) so edits
24
+ // apply live; this proxy reads the current value of every field.
25
+ const cfg = new Proxy({}, {
26
+ get: (_, key) => {
27
+ const value = config?.[key]
28
+ return value !== null && typeof value === 'object' && typeof value.get === 'function' ? value.get() : value
29
+ },
30
+ })
31
+ const dir = storageDir()
32
+
33
+ const host = {
34
+ ctx,
35
+ cfg,
36
+ dir,
37
+ logger: ctx.logger?.('notify-tray') ?? console,
38
+ tracker: new Tracker(),
39
+ ledger: new Ledger({ file: join(dir, 'ledger.json') }),
40
+ account: { usageUrl: undefined },
41
+ /** pi-ai's model catalog (prices), once loaded. */
42
+ pi: undefined,
43
+ /** Latest plan quota reading: { ok, at, data | error, attempts, signature }. */
44
+ quota: undefined,
45
+ /** The web GUI's origin, once the web server is up: where "open DSH" goes when there is no desktop window. */
46
+ webOrigin: () => undefined,
47
+ /** Identifies this host run, so clients reset their cursor after a restart. */
48
+ boot: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
49
+ lastClientPoll: 0,
50
+ /** Session ids a tray click asked the window to open, consumed by the next poll. */
51
+ focusQueue: [],
52
+ /** The session the latest Windows toast announced: { sessionId, at }. */
53
+ toastPending: undefined,
54
+ }
55
+
56
+ /** Set DSH_NOTIFY_TRAY_DEBUG=1 to trace tracked events into storages/dsh-notify-tray/debug.log. */
57
+ host.debug = process.env.DSH_NOTIFY_TRAY_DEBUG
58
+ ? (...parts) => {
59
+ try {
60
+ mkdirSync(dir, { recursive: true })
61
+ appendFileSync(join(dir, 'debug.log'), `${new Date().toISOString()} ${parts.map(p => typeof p === 'string' ? p : JSON.stringify(p)).join(' ')}\n`)
62
+ } catch {}
63
+ }
64
+ : () => {}
65
+
66
+ /** Which endpoint the plan's quota comes from, and what identifies one reading as current. */
67
+ host.quotaSpec = () => quotaSpecFor(cfg.planProvider, cfg.planId, cfg.planQuotaUrl)
68
+ host.quotaSignature = () => `${cfg.planProvider}|${cfg.planId}|${cfg.planApiKeyEnv ?? ''}|${cfg.planQuotaUrl ?? ''}`
69
+ /** The route in use: the latest request header anywhere, else DSH's default model selection. */
70
+ host.currentRoute = () => {
71
+ if (host.ledger.lastRoute) return host.ledger.lastRoute
72
+ try {
73
+ const selection = ctx.get('agentDefaultModel')?.currentSelection?.()
74
+ if (selection?.model) return { provider: selection.provider, model: selection.model }
75
+ } catch {}
76
+ return undefined
77
+ }
78
+ host.usage = () => ({
79
+ ...host.ledger.summary(makeResolver({ cfg, models: host.pi?.models }), cfg.currency),
80
+ usageUrl: host.account.usageUrl,
81
+ route: host.currentRoute(),
82
+ })
83
+ // A reading taken for another provider / key is never shown as this one's.
84
+ host.plan = () => planView(cfg, host.quota && host.quota.signature === host.quotaSignature() ? host.quota : undefined)
85
+ host.pricing = () => describeRoute({ cfg, models: host.pi?.models, route: host.currentRoute() })
86
+ host.view = () => buildView(host.tracker.summary(), host.usage(), cfg, Date.now(), host.plan())
87
+
88
+ return host
89
+ }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Notifications: the user's per-type switches, then the notice queue
3
+ * (lib/notices.js: one notification per session, "needs you" taken back once
4
+ * answered, bursts of completions folded), then the channel. The DSH window
5
+ * picks notices up from `GET notify-tray/state`; when no window is listening
6
+ * (or the channel says so) the host shows them through the OS.
7
+ */
8
+ import { join } from 'node:path'
9
+ import { DONE_HOLD_MS } from '../format.js'
10
+ import { Notices } from '../notices.js'
11
+ import { consumeClicks, systemNotify, systemWithdraw, terminalNotifier } from '../system.js'
12
+ import { speak } from '../voice.js'
13
+
14
+ /** A window that polled within this window counts as "listening". */
15
+ export const CLIENT_FRESH_MS = 8000
16
+ /** The whale's colour on a notification of each kind. */
17
+ const EVENT_STATE = { completed: 'done', failed: 'error', approval: 'attention', choice: 'attention', input: 'attention' }
18
+ export const EVENT_SWITCH = {
19
+ completed: 'notifyCompleted',
20
+ failed: 'notifyFailed',
21
+ approval: 'notifyApproval',
22
+ choice: 'notifyChoice',
23
+ input: 'notifyInput',
24
+ }
25
+
26
+ export function setupNotifications(ctx, host) {
27
+ const { cfg, logger, tracker, debug } = host
28
+ const burstMs = Number(process.env.DSH_NOTIFY_TRAY_BURST_MS)
29
+ const notices = new Notices(Number.isFinite(burstMs) && burstMs >= 0 ? { windowMs: burstMs } : {})
30
+ host.notices = notices
31
+ ctx.effect(() => () => notices.dispose(), 'notify-tray: notice queue')
32
+
33
+ // A clicked macOS notification (sent through terminal-notifier) drops a file
34
+ // named after its session here; the host opens that session.
35
+ const clickDir = join(host.dir, 'clicks')
36
+ if (process.platform === 'darwin') {
37
+ ctx.effect(() => {
38
+ consumeClicks(clickDir) // stale clicks from an earlier run open nothing
39
+ const timer = setInterval(() => {
40
+ if (!terminalNotifier()) return
41
+ for (const id of consumeClicks(clickDir)) host.onAction(`open:${id}`)
42
+ }, 1000)
43
+ return () => clearInterval(timer)
44
+ }, 'notify-tray: notification clicks')
45
+ }
46
+
47
+ tracker.onEvent(event => {
48
+ debug('event', event)
49
+ // The celebration / error pose expires on its own: refresh once it does.
50
+ if (event.type === 'completed') setTimeout(host.refresh, DONE_HOLD_MS + 200).unref?.()
51
+ if (event.type === 'failed') setTimeout(host.refresh, Math.max(0, cfg.errorHoldMinutes) * 60_000 + 200).unref?.()
52
+ if (cfg[EVENT_SWITCH[event.type]]) notices.push(event)
53
+ })
54
+ // A question answered, an approval decided, a turn over: its "needs you" notification goes.
55
+ tracker.onChange(() => notices.settle(tracker.waitingSessions()))
56
+
57
+ /** Keys the OS currently shows a notification of ours for. */
58
+ const shownBySystem = new Set()
59
+ const systemSide = () => {
60
+ const clientListening = Date.now() - host.lastClientPoll < CLIENT_FRESH_MS
61
+ const channel = cfg.channel
62
+ return channel === 'system' || channel === 'both' || (channel === 'auto' && !clientListening)
63
+ }
64
+ notices.onNotice(notice => {
65
+ if (notice.kind === 'withdraw') {
66
+ if (!shownBySystem.delete(notice.key)) return
67
+ systemWithdraw(notice.key).then(ok => debug('system withdraw', notice.key, ok)).catch(() => {})
68
+ return
69
+ }
70
+ const side = systemSide()
71
+ debug('deliver', { channel: cfg.channel, systemSide: side })
72
+ if (!side) return // the window picks it up from the notice queue
73
+ const said = speak(notice)
74
+ if (process.platform === 'win32') host.toastPending = { sessionId: notice.sessionId, at: Date.now() }
75
+ shownBySystem.add(notice.key)
76
+ systemNotify({
77
+ title: said.title,
78
+ body: said.body,
79
+ sound: cfg.sound,
80
+ webOrigin: host.webOrigin,
81
+ state: EVENT_STATE[notice.type],
82
+ iconDir: join(host.dir, 'icons'),
83
+ sessionId: notice.sessionId,
84
+ key: notice.key,
85
+ clickDir,
86
+ onClick: () => host.onAction(`open:${notice.sessionId}`),
87
+ }).then(ok => debug('system notify', ok)).catch(error => logger.warn('系统通知失败', error))
88
+ })
89
+ }
@@ -0,0 +1,170 @@
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 { readFileSync } from 'node:fs'
13
+ import { publicCatalog } from '../catalog.js'
14
+ import { spendOf, TITLES } from '../format.js'
15
+ import { desktopHosted } from '../system.js'
16
+ import { speak } from '../voice.js'
17
+
18
+ const STATE_PATH = '/notify-tray/state'
19
+ const CATALOG_PATH = '/notify-tray/catalog'
20
+ const REFRESH_PATH = '/notify-tray/refresh'
21
+ const TRAY_PATH = '/notify-tray/tray'
22
+ const RAISE_PATH = '/notify-tray/raise'
23
+ const MASCOT_PATH = '/notify-tray/mascot'
24
+ /**
25
+ * A clicked Windows toast can only launch `dsh://open` (or the web GUI), so no
26
+ * session travels with it: a window that comes forward within this long after
27
+ * a toast opens the session that toast announced.
28
+ */
29
+ const TOAST_CLAIM_MS = 60_000
30
+
31
+ /** Short content hash of a snapshot: equal snapshots, equal rev. */
32
+ export function revOf(snapshot) {
33
+ return createHash('sha1').update(JSON.stringify(snapshot)).digest('base64url').slice(0, 12)
34
+ }
35
+
36
+ export function setupRoutes(ctx, host) {
37
+ const { cfg, tracker } = host
38
+ ctx.inject(['webServer', 'connection'], (ctx) => {
39
+ host.webOrigin = () => ctx.webServer.getOrigin?.()
40
+ const guard = (req, res, method) => {
41
+ const rejection = ctx.connection.requestRejection(req)
42
+ if (rejection !== undefined) {
43
+ res.statusCode = rejection
44
+ res.end()
45
+ return false
46
+ }
47
+ if (req.method !== method) {
48
+ res.statusCode = 405
49
+ res.setHeader('allow', method)
50
+ res.end()
51
+ return false
52
+ }
53
+ return true
54
+ }
55
+ const json = (res, body) => {
56
+ res.statusCode = 200
57
+ res.setHeader('content-type', 'application/json; charset=utf-8')
58
+ res.setHeader('cache-control', 'no-store')
59
+ res.end(JSON.stringify(body))
60
+ }
61
+ // The peeking sprite includes the neck, shoulders and hands.
62
+ const mascot = readFileSync(new URL('../../assets/mascot-peeking.png', import.meta.url))
63
+ ctx.effect(() => ctx.webServer.register({
64
+ kind: 'exact',
65
+ path: MASCOT_PATH,
66
+ handler: (req, res) => {
67
+ if (!guard(req, res, 'GET')) return
68
+ res.statusCode = 200
69
+ res.setHeader('content-type', 'image/png')
70
+ res.setHeader('cache-control', 'private, max-age=3600')
71
+ res.end(mascot)
72
+ },
73
+ }), `notify-tray: GET ${MASCOT_PATH}`)
74
+ /** Everything the settings page shows; only computed when a page asks. */
75
+ const snapshot = () => {
76
+ const currentUsage = host.usage()
77
+ return {
78
+ // The settings page shows only what this OS has (no status-bar section on Windows).
79
+ platform: process.platform,
80
+ summary: tracker.summary(),
81
+ usage: currentUsage,
82
+ // Today's figure exactly as the tray shows it, for the settings page's spend card.
83
+ spend: spendOf(currentUsage, cfg.spendSource) ?? null,
84
+ pricing: host.pricing(),
85
+ plan: host.plan(),
86
+ catalogLoaded: Boolean(host.pi),
87
+ tray: host.trayStatus(),
88
+ }
89
+ }
90
+ ctx.effect(() => ctx.webServer.register({
91
+ kind: 'exact',
92
+ path: STATE_PATH,
93
+ handler: (req, res) => {
94
+ if (!guard(req, res, 'GET')) return
95
+ const url = new URL(String(req.url), 'http://localhost')
96
+ // Only a window that can actually show notifications counts as listening;
97
+ // a browser tab without permission must not silence the system channel.
98
+ if (url.searchParams.get('notify') === '1') host.lastClientPoll = Date.now()
99
+ const after = Number(url.searchParams.get('after') ?? '-1')
100
+ // A window that just came forward after a toast takes that toast's session, once.
101
+ if (url.searchParams.get('claim') === '1' && host.toastPending) {
102
+ if (Date.now() - host.toastPending.at < TOAST_CLAIM_MS) host.focusQueue.push(host.toastPending.sessionId)
103
+ host.toastPending = undefined
104
+ }
105
+ const channel = cfg.channel
106
+ const clientSide = channel === 'auto' || channel === 'client' || channel === 'both'
107
+ const body = {
108
+ boot: host.boot,
109
+ seq: host.notices.seq,
110
+ // A first poll (after = -1) only learns the cursor; history is never replayed.
111
+ // Each notice carries its wording, so the window shows exactly what the host would.
112
+ events: clientSide && after >= 0
113
+ ? host.notices.after(after).map(n => (n.kind === 'show' ? { ...n, display: speak(n) } : n))
114
+ : [],
115
+ titles: TITLES,
116
+ suppressWhenFocused: cfg.suppressWhenFocused,
117
+ focus: host.focusQueue,
118
+ }
119
+ host.focusQueue = []
120
+ if (url.searchParams.get('lite') === '1') return void json(res, body)
121
+ const snap = snapshot()
122
+ const rev = revOf(snap)
123
+ if (url.searchParams.get('rev') === rev) return void json(res, { ...body, rev, unchanged: true })
124
+ json(res, { ...body, ...snap, rev })
125
+ },
126
+ }), `notify-tray: GET ${STATE_PATH}`)
127
+ ctx.effect(() => ctx.webServer.register({
128
+ kind: 'exact',
129
+ path: CATALOG_PATH,
130
+ handler: (req, res) => {
131
+ if (!guard(req, res, 'GET')) return
132
+ json(res, { providers: publicCatalog(), piLoaded: Boolean(host.pi), piFile: host.pi?.file })
133
+ },
134
+ }), `notify-tray: GET ${CATALOG_PATH}`)
135
+ ctx.effect(() => ctx.webServer.register({
136
+ kind: 'exact',
137
+ path: REFRESH_PATH,
138
+ handler: (req, res) => {
139
+ if (!guard(req, res, 'POST')) return
140
+ host.pollQuota(true)
141
+ .then(result => json(res, { quota: result ?? null, plan: host.plan() }))
142
+ .catch(error => json(res, { quota: { ok: false, at: Date.now(), error: String(error?.message ?? error) }, plan: host.plan() }))
143
+ },
144
+ }), `notify-tray: POST ${REFRESH_PATH}`)
145
+ // A click on an in-window notification: the renderer cannot change the OS
146
+ // foreground, so in the Windows desktop app the host relaunches it, and the
147
+ // single-instance handler restores a minimized window (a visible window
148
+ // behind another one stays put: Windows' foreground lock, see issue #4).
149
+ ctx.effect(() => ctx.webServer.register({
150
+ kind: 'exact',
151
+ path: RAISE_PATH,
152
+ handler: (req, res) => {
153
+ if (!guard(req, res, 'POST')) return
154
+ const raise = process.platform === 'win32' && desktopHosted() ? host.open() : Promise.resolve(false)
155
+ raise.then(raised => json(res, { raised: Boolean(raised) }))
156
+ },
157
+ }), `notify-tray: POST ${RAISE_PATH}`)
158
+ // The settings page's "show the whale again": undoes the tray menu's hide.
159
+ ctx.effect(() => ctx.webServer.register({
160
+ kind: 'exact',
161
+ path: TRAY_PATH,
162
+ handler: (req, res) => {
163
+ if (!guard(req, res, 'POST')) return
164
+ Promise.resolve(host.showTrayAgain())
165
+ .catch(() => {})
166
+ .then(() => json(res, { tray: host.trayStatus() }))
167
+ },
168
+ }), `notify-tray: POST ${TRAY_PATH}`)
169
+ })
170
+ }
@@ -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
+ }