dsh-notify-tray 0.1.11 → 0.1.13
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 +9 -9
- package/README.md +9 -9
- package/README.zh-CN.md +9 -9
- package/assets/mascot-peeking.prompt.txt +6 -6
- package/assets/notify-icon.png +0 -0
- package/assets/tray-darwin.js +283 -283
- package/cordis.patch.yml +6 -6
- package/lib/ToastActivator.cs +33 -0
- package/lib/catalog.js +448 -448
- package/lib/client.js +65 -132
- package/lib/format.js +284 -284
- package/lib/host/context.js +11 -3
- package/lib/host/notify.js +26 -21
- package/lib/host/routes.js +9 -42
- package/lib/host/spend.js +190 -190
- package/lib/host/tray.js +120 -120
- package/lib/icon.js +159 -159
- package/lib/index.js +2 -7
- package/lib/ledger.js +285 -285
- package/lib/models-dev.json +2684 -2684
- package/lib/notices.js +3 -4
- package/lib/pricing.js +302 -302
- package/lib/quota.js +290 -290
- package/lib/system.js +11 -22
- package/lib/tracker.js +250 -250
- package/lib/tray/index.js +142 -142
- package/lib/tray/linux.js +393 -393
- package/lib/voice.js +76 -76
- package/lib/whale.js +396 -396
- package/lib/windows-toast.js +92 -0
- package/locale/en.json +7 -7
- package/locale/zh.json +7 -7
- package/package.json +2 -1
package/lib/host/notify.js
CHANGED
|
@@ -1,18 +1,11 @@
|
|
|
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
|
-
*/
|
|
1
|
+
/** Filter session events, fold completion bursts, then deliver through the native OS notifier. */
|
|
8
2
|
import { join } from 'node:path'
|
|
9
3
|
import { DONE_HOLD_MS } from '../format.js'
|
|
10
4
|
import { Notices } from '../notices.js'
|
|
11
5
|
import { consumeClicks, systemNotify, systemWithdraw, terminalNotifier } from '../system.js'
|
|
6
|
+
import { readWindowsClicks } from '../windows-toast.js'
|
|
12
7
|
import { speak } from '../voice.js'
|
|
13
8
|
|
|
14
|
-
/** A window that polled within this window counts as "listening". */
|
|
15
|
-
export const CLIENT_FRESH_MS = 8000
|
|
16
9
|
/** The whale's colour on a notification of each kind. */
|
|
17
10
|
const EVENT_STATE = { completed: 'done', failed: 'error', approval: 'attention', choice: 'attention', input: 'attention' }
|
|
18
11
|
export const EVENT_SWITCH = {
|
|
@@ -23,7 +16,7 @@ export const EVENT_SWITCH = {
|
|
|
23
16
|
input: 'notifyInput',
|
|
24
17
|
}
|
|
25
18
|
|
|
26
|
-
export function setupNotifications(ctx, host) {
|
|
19
|
+
export function setupNotifications(ctx, host, { send = systemNotify, withdraw = systemWithdraw } = {}) {
|
|
27
20
|
const { cfg, logger, tracker, debug } = host
|
|
28
21
|
const burstMs = Number(process.env.DSH_NOTIFY_TRAY_BURST_MS)
|
|
29
22
|
const notices = new Notices(Number.isFinite(burstMs) && burstMs >= 0 ? { windowMs: burstMs } : {})
|
|
@@ -44,6 +37,14 @@ export function setupNotifications(ctx, host) {
|
|
|
44
37
|
}, 'notify-tray: notification clicks')
|
|
45
38
|
}
|
|
46
39
|
|
|
40
|
+
if (process.platform === 'win32') ctx.effect(() => {
|
|
41
|
+
const clean = () => readWindowsClicks(host.dir, { prune: true })
|
|
42
|
+
clean()
|
|
43
|
+
const timer = setInterval(clean, 24 * 3600_000)
|
|
44
|
+
timer.unref?.()
|
|
45
|
+
return () => clearInterval(timer)
|
|
46
|
+
}, 'notify-tray: expire native notification tickets')
|
|
47
|
+
|
|
47
48
|
tracker.onEvent(event => {
|
|
48
49
|
debug('event', event)
|
|
49
50
|
// The celebration / error pose expires on its own: refresh once it does.
|
|
@@ -56,24 +57,24 @@ export function setupNotifications(ctx, host) {
|
|
|
56
57
|
|
|
57
58
|
/** Keys the OS currently shows a notification of ours for. */
|
|
58
59
|
const shownBySystem = new Set()
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
60
|
+
// Serialize replacement and withdrawal even while the sender is registering.
|
|
61
|
+
const pending = new Map()
|
|
62
|
+
function enqueue(key, action) {
|
|
63
|
+
const next = (pending.get(key) || Promise.resolve()).then(action).catch(error => logger.warn('系统通知失败', error))
|
|
64
|
+
pending.set(key, next)
|
|
65
|
+
next.then(() => { if (pending.get(key) === next) pending.delete(key) })
|
|
63
66
|
}
|
|
64
67
|
notices.onNotice(notice => {
|
|
65
68
|
if (notice.kind === 'withdraw') {
|
|
66
69
|
if (!shownBySystem.delete(notice.key)) return
|
|
67
|
-
|
|
70
|
+
enqueue(notice.key, () => withdraw(notice.key))
|
|
68
71
|
return
|
|
69
72
|
}
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
if (!side) return // the window picks it up from the notice queue
|
|
73
|
+
if (cfg.channel === 'off') return
|
|
74
|
+
if (cfg.suppressWhenFocused && host.isViewing(notice.sessionId)) return
|
|
73
75
|
const said = speak(notice)
|
|
74
|
-
if (process.platform === 'win32') host.toastPending = { sessionId: notice.sessionId, at: Date.now() }
|
|
75
76
|
shownBySystem.add(notice.key)
|
|
76
|
-
|
|
77
|
+
enqueue(notice.key, () => send({
|
|
77
78
|
title: said.title,
|
|
78
79
|
body: said.body,
|
|
79
80
|
sound: cfg.sound,
|
|
@@ -82,8 +83,12 @@ export function setupNotifications(ctx, host) {
|
|
|
82
83
|
iconDir: join(host.dir, 'icons'),
|
|
83
84
|
sessionId: notice.sessionId,
|
|
84
85
|
key: notice.key,
|
|
86
|
+
storageDir: host.dir,
|
|
85
87
|
clickDir,
|
|
86
88
|
onClick: () => host.onAction(`open:${notice.sessionId}`),
|
|
87
|
-
}).then(ok =>
|
|
89
|
+
}).then(ok => {
|
|
90
|
+
if (!ok) logger.warn('系统未接受通知')
|
|
91
|
+
else debug('system notify', true)
|
|
92
|
+
}))
|
|
88
93
|
})
|
|
89
94
|
}
|
package/lib/host/routes.js
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
* Routes for the browser half.
|
|
3
3
|
*
|
|
4
4
|
* `GET notify-tray/state` has two weights:
|
|
5
|
-
* - `?lite=1` — what every DSH window polls every two seconds:
|
|
6
|
-
*
|
|
5
|
+
* - `?lite=1` — what every DSH window polls every two seconds: session presence
|
|
6
|
+
* and explicit notification / tray clicks. Nothing about money is computed.
|
|
7
7
|
* - the full state for the settings page, with a `rev`: a page that sends
|
|
8
8
|
* back the `rev` it holds gets `unchanged: true` instead of the same
|
|
9
9
|
* snapshot again.
|
|
@@ -12,21 +12,13 @@ import { createHash } from 'node:crypto'
|
|
|
12
12
|
import { readFileSync } from 'node:fs'
|
|
13
13
|
import { publicCatalog } from '../catalog.js'
|
|
14
14
|
import { spendOf, TITLES } from '../format.js'
|
|
15
|
-
import {
|
|
16
|
-
import { speak } from '../voice.js'
|
|
15
|
+
import { readWindowsClicks } from '../windows-toast.js'
|
|
17
16
|
|
|
18
17
|
const STATE_PATH = '/notify-tray/state'
|
|
19
18
|
const CATALOG_PATH = '/notify-tray/catalog'
|
|
20
19
|
const REFRESH_PATH = '/notify-tray/refresh'
|
|
21
20
|
const TRAY_PATH = '/notify-tray/tray'
|
|
22
|
-
const RAISE_PATH = '/notify-tray/raise'
|
|
23
21
|
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
22
|
|
|
31
23
|
/** Short content hash of a snapshot: equal snapshots, equal rev. */
|
|
32
24
|
export function revOf(snapshot) {
|
|
@@ -93,30 +85,18 @@ export function setupRoutes(ctx, host) {
|
|
|
93
85
|
handler: (req, res) => {
|
|
94
86
|
if (!guard(req, res, 'GET')) return
|
|
95
87
|
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
88
|
const lite = url.searchParams.get('lite') === '1'
|
|
101
|
-
const
|
|
102
|
-
|
|
103
|
-
if (
|
|
104
|
-
|
|
105
|
-
host.toastPending = undefined
|
|
106
|
-
}
|
|
107
|
-
const channel = cfg.channel
|
|
108
|
-
const clientSide = channel === 'auto' || channel === 'client' || channel === 'both'
|
|
89
|
+
const windowId = url.searchParams.get('window')
|
|
90
|
+
const foreground = url.searchParams.get('foreground') === '1'
|
|
91
|
+
if (lite && windowId) host.reportView(windowId, foreground ? url.searchParams.get('view') : undefined)
|
|
92
|
+
if (lite && foreground && process.platform === 'win32') host.focusQueue.push(...readWindowsClicks(host.dir))
|
|
109
93
|
const body = {
|
|
110
94
|
boot: host.boot,
|
|
111
95
|
seq: host.notices.seq,
|
|
112
|
-
|
|
113
|
-
// Each notice carries its wording, so the window shows exactly what the host would.
|
|
114
|
-
events: clientSide && after >= 0
|
|
115
|
-
? host.notices.after(after).map(n => (n.kind === 'show' ? { ...n, display: speak(n) } : n))
|
|
116
|
-
: [],
|
|
96
|
+
events: [], // Older clients must never duplicate host notifications.
|
|
117
97
|
titles: TITLES,
|
|
118
98
|
suppressWhenFocused: cfg.suppressWhenFocused,
|
|
119
|
-
focus: lite ||
|
|
99
|
+
focus: lite && (!windowId || foreground || process.platform !== 'win32') ? host.focusQueue.splice(0) : [],
|
|
120
100
|
}
|
|
121
101
|
if (lite) return void json(res, body)
|
|
122
102
|
const snap = snapshot()
|
|
@@ -143,19 +123,6 @@ export function setupRoutes(ctx, host) {
|
|
|
143
123
|
.catch(error => json(res, { quota: { ok: false, at: Date.now(), error: String(error?.message ?? error) }, plan: host.plan() }))
|
|
144
124
|
},
|
|
145
125
|
}), `notify-tray: POST ${REFRESH_PATH}`)
|
|
146
|
-
// A click on an in-window notification: the renderer cannot change the OS
|
|
147
|
-
// foreground, so in the Windows desktop app the host relaunches it, and the
|
|
148
|
-
// single-instance handler restores a minimized window (a visible window
|
|
149
|
-
// behind another one stays put: Windows' foreground lock, see issue #4).
|
|
150
|
-
ctx.effect(() => ctx.webServer.register({
|
|
151
|
-
kind: 'exact',
|
|
152
|
-
path: RAISE_PATH,
|
|
153
|
-
handler: (req, res) => {
|
|
154
|
-
if (!guard(req, res, 'POST')) return
|
|
155
|
-
const raise = process.platform === 'win32' && desktopHosted() ? host.open() : Promise.resolve(false)
|
|
156
|
-
raise.then(raised => json(res, { raised: Boolean(raised) }))
|
|
157
|
-
},
|
|
158
|
-
}), `notify-tray: POST ${RAISE_PATH}`)
|
|
159
126
|
// The settings page's "show the whale again": undoes the tray menu's hide.
|
|
160
127
|
ctx.effect(() => ctx.webServer.register({
|
|
161
128
|
kind: 'exact',
|
package/lib/host/spend.js
CHANGED
|
@@ -1,190 +1,190 @@
|
|
|
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
|
-
const save = () => ledger.save().catch(error => logger.warn('保存花费账本失败', error))
|
|
19
|
-
const timer = setInterval(save, 30_000)
|
|
20
|
-
return () => {
|
|
21
|
-
clearInterval(timer)
|
|
22
|
-
return save()
|
|
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 (polling?.signature !== signature) polling = undefined
|
|
66
|
-
if (host.quota !== undefined) { host.quota = undefined; host.refresh() }
|
|
67
|
-
return undefined
|
|
68
|
-
}
|
|
69
|
-
if (polling?.signature === signature) return polling.result
|
|
70
|
-
const request = { signature }
|
|
71
|
-
polling = request
|
|
72
|
-
request.result = (async () => {
|
|
73
|
-
// The key DSH's Models page saved first, then the environment variable of the same name.
|
|
74
|
-
let saved
|
|
75
|
-
const reading = await runQuotaPlan([
|
|
76
|
-
{
|
|
77
|
-
id: 'saved',
|
|
78
|
-
label: 'DSH 保存的 Key',
|
|
79
|
-
available: async () => {
|
|
80
|
-
const credentials = ctx.get('credentials')
|
|
81
|
-
if (!credentials) return '这个 DSH 没有 Key 存储'
|
|
82
|
-
try {
|
|
83
|
-
saved = (await credentials.resolve(ref))?.value
|
|
84
|
-
} catch (error) {
|
|
85
|
-
debug('credential', String(error))
|
|
86
|
-
return '读取失败'
|
|
87
|
-
}
|
|
88
|
-
return saved ? true : `没有保存 ${ref}`
|
|
89
|
-
},
|
|
90
|
-
fetch: () => fetchQuota(spec, saved),
|
|
91
|
-
},
|
|
92
|
-
{
|
|
93
|
-
id: 'env',
|
|
94
|
-
label: '环境变量',
|
|
95
|
-
available: () => {
|
|
96
|
-
const value = process.env[ref]
|
|
97
|
-
if (!value) return `没有设置 ${ref}`
|
|
98
|
-
return value === saved ? '和保存的 Key 相同,不再重试' : true
|
|
99
|
-
},
|
|
100
|
-
fetch: () => fetchQuota(spec, process.env[ref]),
|
|
101
|
-
},
|
|
102
|
-
], { noneError: `没找到 API Key:${ref} 没有保存,也没有设置为环境变量` })
|
|
103
|
-
if (polling !== request || host.quotaSignature() !== signature) return undefined
|
|
104
|
-
host.quota = { ...reading, signature, spec: { kind: spec.kind, url: spec.url } }
|
|
105
|
-
debug('quota', host.quota)
|
|
106
|
-
host.refresh()
|
|
107
|
-
return host.quota
|
|
108
|
-
})().finally(() => {
|
|
109
|
-
if (polling === request) polling = undefined
|
|
110
|
-
})
|
|
111
|
-
return request.result
|
|
112
|
-
}
|
|
113
|
-
ctx.effect(() => {
|
|
114
|
-
let timer
|
|
115
|
-
let lastSignature = host.quotaSignature()
|
|
116
|
-
let lastPoll = 0
|
|
117
|
-
const tick = () => {
|
|
118
|
-
const signature = host.quotaSignature()
|
|
119
|
-
const due = Date.now() - lastPoll >= Math.max(1, cfg.quotaPollMinutes) * 60_000
|
|
120
|
-
if (signature !== lastSignature || due) {
|
|
121
|
-
lastSignature = signature
|
|
122
|
-
lastPoll = Date.now()
|
|
123
|
-
host.pollQuota().catch(() => {})
|
|
124
|
-
}
|
|
125
|
-
timer = setTimeout(tick, 15_000)
|
|
126
|
-
}
|
|
127
|
-
tick()
|
|
128
|
-
return () => clearTimeout(timer)
|
|
129
|
-
}, 'notify-tray: quota poll')
|
|
130
|
-
|
|
131
|
-
// ---- DeepSeek account balance (optional service) ------------------------
|
|
132
|
-
ctx.inject(['deepseekAccount'], (ctx) => {
|
|
133
|
-
const client = {
|
|
134
|
-
// Mirrors DSH's own settings page: the installed harness version and the UI locale.
|
|
135
|
-
version: findDshVersion() ?? DSH_VERSION_FALLBACK,
|
|
136
|
-
locale: 'zh-CN',
|
|
137
|
-
timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60,
|
|
138
|
-
}
|
|
139
|
-
let disposed = false
|
|
140
|
-
let pollingBalance = false
|
|
141
|
-
let pollAgain = false
|
|
142
|
-
let idleTimer
|
|
143
|
-
const poll = async () => {
|
|
144
|
-
if (disposed) return
|
|
145
|
-
if (pollingBalance) {
|
|
146
|
-
pollAgain = true
|
|
147
|
-
return
|
|
148
|
-
}
|
|
149
|
-
pollingBalance = true
|
|
150
|
-
try {
|
|
151
|
-
const balance = await ctx.deepseekAccount.getBalance(client)
|
|
152
|
-
if (disposed) return
|
|
153
|
-
if (balance?.status === 'ready') ledger.balance(balance.value)
|
|
154
|
-
if (host.account.usageUrl === undefined) {
|
|
155
|
-
const state = await ctx.deepseekAccount.getState?.()
|
|
156
|
-
if (!disposed) host.account.usageUrl = state?.links?.usageUrl
|
|
157
|
-
}
|
|
158
|
-
} catch (error) {
|
|
159
|
-
logger.debug?.('读取账户余额失败', error)
|
|
160
|
-
} finally {
|
|
161
|
-
pollingBalance = false
|
|
162
|
-
if (pollAgain && !disposed) {
|
|
163
|
-
pollAgain = false
|
|
164
|
-
poll()
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
ctx.effect(() => {
|
|
169
|
-
let timer
|
|
170
|
-
const loop = () => {
|
|
171
|
-
poll()
|
|
172
|
-
timer = setTimeout(loop, Math.max(1, cfg.balancePollMinutes) * 60_000)
|
|
173
|
-
}
|
|
174
|
-
loop()
|
|
175
|
-
return () => {
|
|
176
|
-
disposed = true
|
|
177
|
-
clearTimeout(timer)
|
|
178
|
-
clearTimeout(idleTimer)
|
|
179
|
-
}
|
|
180
|
-
}, 'notify-tray: balance poll')
|
|
181
|
-
// A finished turn is when spend lands; refresh shortly after.
|
|
182
|
-
ctx.on('agent/status', ({ status }) => {
|
|
183
|
-
if (status !== 'idle' || idleTimer || disposed) return
|
|
184
|
-
idleTimer = setTimeout(() => {
|
|
185
|
-
idleTimer = undefined
|
|
186
|
-
poll()
|
|
187
|
-
}, 5000)
|
|
188
|
-
})
|
|
189
|
-
})
|
|
190
|
-
}
|
|
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
|
+
const save = () => ledger.save().catch(error => logger.warn('保存花费账本失败', error))
|
|
19
|
+
const timer = setInterval(save, 30_000)
|
|
20
|
+
return () => {
|
|
21
|
+
clearInterval(timer)
|
|
22
|
+
return save()
|
|
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 (polling?.signature !== signature) polling = undefined
|
|
66
|
+
if (host.quota !== undefined) { host.quota = undefined; host.refresh() }
|
|
67
|
+
return undefined
|
|
68
|
+
}
|
|
69
|
+
if (polling?.signature === signature) return polling.result
|
|
70
|
+
const request = { signature }
|
|
71
|
+
polling = request
|
|
72
|
+
request.result = (async () => {
|
|
73
|
+
// The key DSH's Models page saved first, then the environment variable of the same name.
|
|
74
|
+
let saved
|
|
75
|
+
const reading = await runQuotaPlan([
|
|
76
|
+
{
|
|
77
|
+
id: 'saved',
|
|
78
|
+
label: 'DSH 保存的 Key',
|
|
79
|
+
available: async () => {
|
|
80
|
+
const credentials = ctx.get('credentials')
|
|
81
|
+
if (!credentials) return '这个 DSH 没有 Key 存储'
|
|
82
|
+
try {
|
|
83
|
+
saved = (await credentials.resolve(ref))?.value
|
|
84
|
+
} catch (error) {
|
|
85
|
+
debug('credential', String(error))
|
|
86
|
+
return '读取失败'
|
|
87
|
+
}
|
|
88
|
+
return saved ? true : `没有保存 ${ref}`
|
|
89
|
+
},
|
|
90
|
+
fetch: () => fetchQuota(spec, saved),
|
|
91
|
+
},
|
|
92
|
+
{
|
|
93
|
+
id: 'env',
|
|
94
|
+
label: '环境变量',
|
|
95
|
+
available: () => {
|
|
96
|
+
const value = process.env[ref]
|
|
97
|
+
if (!value) return `没有设置 ${ref}`
|
|
98
|
+
return value === saved ? '和保存的 Key 相同,不再重试' : true
|
|
99
|
+
},
|
|
100
|
+
fetch: () => fetchQuota(spec, process.env[ref]),
|
|
101
|
+
},
|
|
102
|
+
], { noneError: `没找到 API Key:${ref} 没有保存,也没有设置为环境变量` })
|
|
103
|
+
if (polling !== request || host.quotaSignature() !== signature) return undefined
|
|
104
|
+
host.quota = { ...reading, signature, spec: { kind: spec.kind, url: spec.url } }
|
|
105
|
+
debug('quota', host.quota)
|
|
106
|
+
host.refresh()
|
|
107
|
+
return host.quota
|
|
108
|
+
})().finally(() => {
|
|
109
|
+
if (polling === request) polling = undefined
|
|
110
|
+
})
|
|
111
|
+
return request.result
|
|
112
|
+
}
|
|
113
|
+
ctx.effect(() => {
|
|
114
|
+
let timer
|
|
115
|
+
let lastSignature = host.quotaSignature()
|
|
116
|
+
let lastPoll = 0
|
|
117
|
+
const tick = () => {
|
|
118
|
+
const signature = host.quotaSignature()
|
|
119
|
+
const due = Date.now() - lastPoll >= Math.max(1, cfg.quotaPollMinutes) * 60_000
|
|
120
|
+
if (signature !== lastSignature || due) {
|
|
121
|
+
lastSignature = signature
|
|
122
|
+
lastPoll = Date.now()
|
|
123
|
+
host.pollQuota().catch(() => {})
|
|
124
|
+
}
|
|
125
|
+
timer = setTimeout(tick, 15_000)
|
|
126
|
+
}
|
|
127
|
+
tick()
|
|
128
|
+
return () => clearTimeout(timer)
|
|
129
|
+
}, 'notify-tray: quota poll')
|
|
130
|
+
|
|
131
|
+
// ---- DeepSeek account balance (optional service) ------------------------
|
|
132
|
+
ctx.inject(['deepseekAccount'], (ctx) => {
|
|
133
|
+
const client = {
|
|
134
|
+
// Mirrors DSH's own settings page: the installed harness version and the UI locale.
|
|
135
|
+
version: findDshVersion() ?? DSH_VERSION_FALLBACK,
|
|
136
|
+
locale: 'zh-CN',
|
|
137
|
+
timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60,
|
|
138
|
+
}
|
|
139
|
+
let disposed = false
|
|
140
|
+
let pollingBalance = false
|
|
141
|
+
let pollAgain = false
|
|
142
|
+
let idleTimer
|
|
143
|
+
const poll = async () => {
|
|
144
|
+
if (disposed) return
|
|
145
|
+
if (pollingBalance) {
|
|
146
|
+
pollAgain = true
|
|
147
|
+
return
|
|
148
|
+
}
|
|
149
|
+
pollingBalance = true
|
|
150
|
+
try {
|
|
151
|
+
const balance = await ctx.deepseekAccount.getBalance(client)
|
|
152
|
+
if (disposed) return
|
|
153
|
+
if (balance?.status === 'ready') ledger.balance(balance.value)
|
|
154
|
+
if (host.account.usageUrl === undefined) {
|
|
155
|
+
const state = await ctx.deepseekAccount.getState?.()
|
|
156
|
+
if (!disposed) host.account.usageUrl = state?.links?.usageUrl
|
|
157
|
+
}
|
|
158
|
+
} catch (error) {
|
|
159
|
+
logger.debug?.('读取账户余额失败', error)
|
|
160
|
+
} finally {
|
|
161
|
+
pollingBalance = false
|
|
162
|
+
if (pollAgain && !disposed) {
|
|
163
|
+
pollAgain = false
|
|
164
|
+
poll()
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
ctx.effect(() => {
|
|
169
|
+
let timer
|
|
170
|
+
const loop = () => {
|
|
171
|
+
poll()
|
|
172
|
+
timer = setTimeout(loop, Math.max(1, cfg.balancePollMinutes) * 60_000)
|
|
173
|
+
}
|
|
174
|
+
loop()
|
|
175
|
+
return () => {
|
|
176
|
+
disposed = true
|
|
177
|
+
clearTimeout(timer)
|
|
178
|
+
clearTimeout(idleTimer)
|
|
179
|
+
}
|
|
180
|
+
}, 'notify-tray: balance poll')
|
|
181
|
+
// A finished turn is when spend lands; refresh shortly after.
|
|
182
|
+
ctx.on('agent/status', ({ status }) => {
|
|
183
|
+
if (status !== 'idle' || idleTimer || disposed) return
|
|
184
|
+
idleTimer = setTimeout(() => {
|
|
185
|
+
idleTimer = undefined
|
|
186
|
+
poll()
|
|
187
|
+
}, 5000)
|
|
188
|
+
})
|
|
189
|
+
})
|
|
190
|
+
}
|