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.
- package/README.md +12 -8
- package/README.zh-CN.md +12 -8
- package/lib/catalog.js +26 -3
- package/lib/client.js +62 -9
- 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 +155 -0
- package/lib/host/spend.js +159 -0
- package/lib/host/tray.js +120 -0
- package/lib/index.js +16 -423
- package/lib/ledger.js +15 -5
- package/lib/models-dev.json +2684 -0
- package/lib/notices.js +119 -0
- package/lib/pricing.js +121 -14
- package/lib/quota.js +46 -2
- package/lib/system.js +116 -10
- package/lib/tracker.js +7 -0
- package/lib/tray/linux.js +34 -7
- package/lib/voice.js +19 -1
- package/package.json +4 -2
package/lib/notices.js
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Notice queue: turns the tracker's per-session events into what the user is
|
|
3
|
+
* actually shown, on both channels (the DSH window and the OS).
|
|
4
|
+
*
|
|
5
|
+
* - One notification per session: every notice carries `key` (the session
|
|
6
|
+
* id), and each channel replaces the session's previous notification with
|
|
7
|
+
* the new one (freedesktop replaces_id, terminal-notifier -group, toast Tag,
|
|
8
|
+
* web Notification tag).
|
|
9
|
+
* - A "needs you" notification (approval / choice / input) is taken back
|
|
10
|
+
* once the session no longer waits on anything: `settle()` emits a
|
|
11
|
+
* `withdraw` notice for it.
|
|
12
|
+
* - A burst of completions does not ring once per task: the first one shows
|
|
13
|
+
* at once, the ones that follow within `windowMs` fold into a single
|
|
14
|
+
* "n more finished" notice at the end of the window. Failures and anything
|
|
15
|
+
* that needs you are never held back.
|
|
16
|
+
*
|
|
17
|
+
* Pure logic (timers injectable), no DSH imports.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/** How long completions after the first are gathered into one notice. */
|
|
21
|
+
export const BURST_MS = 4000
|
|
22
|
+
/** Notices kept for windows that poll late. */
|
|
23
|
+
const KEEP = 50
|
|
24
|
+
/** Event types that ask something of the user. */
|
|
25
|
+
export const ATTENTION = new Set(['approval', 'choice', 'input'])
|
|
26
|
+
|
|
27
|
+
export class Notices {
|
|
28
|
+
constructor({ windowMs = BURST_MS, now = () => Date.now(), setTimer = setTimeout, clearTimer = clearTimeout } = {}) {
|
|
29
|
+
this.windowMs = windowMs
|
|
30
|
+
this.now = now
|
|
31
|
+
this.setTimer = setTimer
|
|
32
|
+
this.clearTimer = clearTimer
|
|
33
|
+
this.seq = 0
|
|
34
|
+
this.list = []
|
|
35
|
+
this.listeners = new Set()
|
|
36
|
+
/** Keys whose latest shown notice asks something of the user. */
|
|
37
|
+
this.attention = new Set()
|
|
38
|
+
/** Open completion window: { timer, extra: event[] } */
|
|
39
|
+
this.burst = undefined
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
onNotice(listener) {
|
|
43
|
+
this.listeners.add(listener)
|
|
44
|
+
return () => this.listeners.delete(listener)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
emit(notice) {
|
|
48
|
+
const full = { seq: ++this.seq, at: this.now(), ...notice }
|
|
49
|
+
this.list.push(full)
|
|
50
|
+
if (this.list.length > KEEP) this.list.shift()
|
|
51
|
+
for (const listener of this.listeners) listener(full)
|
|
52
|
+
return full
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
show(event, extra = {}) {
|
|
56
|
+
const key = event.sessionId
|
|
57
|
+
if (ATTENTION.has(event.type)) this.attention.add(key)
|
|
58
|
+
else this.attention.delete(key)
|
|
59
|
+
return this.emit({ kind: 'show', key, type: event.type, sessionId: event.sessionId, title: event.title, body: event.body, ...extra })
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Feed one tracker event (already filtered by the user's per-type switches). */
|
|
63
|
+
push(event) {
|
|
64
|
+
if (event.type !== 'completed' || this.windowMs <= 0) return void this.show(event)
|
|
65
|
+
if (this.burst) {
|
|
66
|
+
this.burst.extra.push(event)
|
|
67
|
+
return
|
|
68
|
+
}
|
|
69
|
+
this.show(event)
|
|
70
|
+
this.openWindow()
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
openWindow() {
|
|
74
|
+
const burst = { extra: [] }
|
|
75
|
+
burst.timer = this.setTimer(() => this.closeWindow(burst), this.windowMs)
|
|
76
|
+
burst.timer?.unref?.()
|
|
77
|
+
this.burst = burst
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
closeWindow(burst) {
|
|
81
|
+
if (this.burst !== burst) return
|
|
82
|
+
this.burst = undefined
|
|
83
|
+
const { extra } = burst
|
|
84
|
+
if (extra.length === 0) return
|
|
85
|
+
if (extra.length === 1) this.show(extra[0])
|
|
86
|
+
else {
|
|
87
|
+
const last = extra[extra.length - 1]
|
|
88
|
+
// Newest first, one entry per session.
|
|
89
|
+
const sessions = []
|
|
90
|
+
for (const e of [...extra].reverse()) {
|
|
91
|
+
if (!sessions.some(s => s.sessionId === e.sessionId)) sessions.push({ sessionId: e.sessionId, title: e.title })
|
|
92
|
+
}
|
|
93
|
+
this.show(last, { count: extra.length, sessions })
|
|
94
|
+
}
|
|
95
|
+
// Completions keep coming: gather the next ones too instead of ringing for each.
|
|
96
|
+
this.openWindow()
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Take back "needs you" notifications of sessions that no longer wait.
|
|
101
|
+
* @param {Set<string>} waiting - session ids that still wait on the user.
|
|
102
|
+
*/
|
|
103
|
+
settle(waiting) {
|
|
104
|
+
for (const key of [...this.attention]) {
|
|
105
|
+
if (waiting.has(key)) continue
|
|
106
|
+
this.attention.delete(key)
|
|
107
|
+
this.emit({ kind: 'withdraw', key, sessionId: key })
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
after(seq) {
|
|
112
|
+
return this.list.filter(notice => notice.seq > seq)
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
dispose() {
|
|
116
|
+
if (this.burst) this.clearTimer(this.burst.timer)
|
|
117
|
+
this.burst = undefined
|
|
118
|
+
}
|
|
119
|
+
}
|
package/lib/pricing.js
CHANGED
|
@@ -5,46 +5,88 @@
|
|
|
5
5
|
* custom price typed on the settings page → the price list bundled with
|
|
6
6
|
* DSH's pi-ai adapter (`@earendil-works/pi-ai`, USD per million tokens, the
|
|
7
7
|
* same catalog the model selector reads) → this plugin's own static catalog
|
|
8
|
-
* (catalog.js
|
|
8
|
+
* (catalog.js, hand-kept, official CNY prices where there are some) → a
|
|
9
|
+
* snapshot of models.dev shipped with the plugin (lib/models-dev.json,
|
|
10
|
+
* refreshed by scripts/update-models-dev.mjs) for every model the first
|
|
11
|
+
* ones do not know. Everything comes out in the display currency.
|
|
9
12
|
*/
|
|
10
|
-
import {
|
|
13
|
+
import { execFile } from 'node:child_process'
|
|
14
|
+
import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs'
|
|
11
15
|
import { homedir } from 'node:os'
|
|
12
16
|
import { dirname, join } from 'node:path'
|
|
13
17
|
import { pathToFileURL } from 'node:url'
|
|
14
|
-
import { priceFor, splitRoute } from './ledger.js'
|
|
15
|
-
import { staticPriceFor } from './catalog.js'
|
|
18
|
+
import { billedToDeepseek, priceFor, splitRoute } from './ledger.js'
|
|
19
|
+
import { DEEPSEEK_OFF_PEAK, isDeepseekOffPeak, staticPriceFor } from './catalog.js'
|
|
16
20
|
|
|
17
21
|
const PI_AI_REL = join('@earendil-works', 'pi-ai', 'dist', 'models.generated.js')
|
|
18
22
|
/** Fallback CNY-per-USD rate when the user leaves the setting blank. */
|
|
19
23
|
export const DEFAULT_RATE = 7.2
|
|
20
24
|
/** Human labels for where a price came from. */
|
|
21
|
-
export const SOURCE_LABEL = { table: '价格表', custom: '自定义价', catalog: '目录价', static: '内置价' }
|
|
25
|
+
export const SOURCE_LABEL = { table: '价格表', custom: '自定义价', catalog: '目录价', static: '内置价', modelsDev: 'models.dev 价' }
|
|
22
26
|
|
|
23
27
|
const DSH_PACKAGE = join('@deepseek-ai', 'dsh')
|
|
24
28
|
|
|
25
29
|
/**
|
|
26
30
|
* Where a globally installed `@deepseek-ai/dsh` (the web / CLI profile) may
|
|
27
31
|
* live: npm's configured prefix, the common `~/.npm-global` user prefix, the
|
|
28
|
-
* prefix of the node running us,
|
|
32
|
+
* prefix of the node running us, npm's Windows prefix (`%APPDATA%\npm`),
|
|
33
|
+
* pnpm's global store, and every node a version manager (nvm, nvm-windows,
|
|
34
|
+
* fnm, volta) installed.
|
|
29
35
|
*/
|
|
30
36
|
export function globalDshDirs(env = process.env, home = safeHome(), execPath = process.execPath) {
|
|
31
37
|
const prefixes = [env.npm_config_prefix, env.NPM_CONFIG_PREFIX, env.PREFIX]
|
|
32
38
|
if (home) prefixes.push(join(home, '.npm-global'), join(home, '.npm-packages'), join(home, '.local'))
|
|
33
|
-
if (execPath) prefixes.push(dirname(dirname(execPath)))
|
|
39
|
+
if (execPath) prefixes.push(dirname(dirname(execPath)), dirname(execPath))
|
|
40
|
+
if (env.APPDATA) prefixes.push(join(env.APPDATA, 'npm'))
|
|
34
41
|
prefixes.push('/usr/local', '/usr', '/opt/homebrew')
|
|
42
|
+
// Version managers keep one prefix per installed node; DSH may sit under any of them.
|
|
43
|
+
const nvmDir = env.NVM_DIR || (home ? join(home, '.nvm') : undefined)
|
|
44
|
+
if (nvmDir) for (const v of safeReaddir(join(nvmDir, 'versions', 'node'))) prefixes.push(join(nvmDir, 'versions', 'node', v))
|
|
45
|
+
if (env.NVM_HOME) for (const v of safeReaddir(env.NVM_HOME)) prefixes.push(join(env.NVM_HOME, v))
|
|
46
|
+
const fnmDirs = [env.FNM_DIR, home && join(home, '.local', 'share', 'fnm'), home && join(home, '.fnm'), home && join(home, 'Library', 'Application Support', 'fnm'), env.APPDATA && join(env.APPDATA, 'fnm')]
|
|
47
|
+
for (const fnm of fnmDirs) {
|
|
48
|
+
if (!fnm) continue
|
|
49
|
+
for (const v of safeReaddir(join(fnm, 'node-versions'))) prefixes.push(join(fnm, 'node-versions', v, 'installation'))
|
|
50
|
+
}
|
|
35
51
|
const dirs = []
|
|
36
52
|
for (const prefix of prefixes) {
|
|
37
53
|
if (!prefix) continue
|
|
38
54
|
// POSIX prefixes keep packages under lib/; Windows prefixes keep them at the top.
|
|
39
55
|
dirs.push(join(prefix, 'lib', 'node_modules', DSH_PACKAGE), join(prefix, 'node_modules', DSH_PACKAGE))
|
|
40
56
|
}
|
|
41
|
-
|
|
42
|
-
|
|
57
|
+
// Volta installs each global package into its own image.
|
|
58
|
+
const volta = env.VOLTA_HOME || (home ? join(home, '.volta') : undefined)
|
|
59
|
+
if (volta) {
|
|
60
|
+
const image = join(volta, 'tools', 'image', 'packages', DSH_PACKAGE)
|
|
61
|
+
dirs.push(join(image, 'lib', 'node_modules', DSH_PACKAGE), join(image, 'node_modules', DSH_PACKAGE))
|
|
62
|
+
}
|
|
63
|
+
const pnpmHomes = [env.PNPM_HOME, home && join(home, '.local', 'share', 'pnpm'), home && join(home, 'Library', 'pnpm'), env.LOCALAPPDATA && join(env.LOCALAPPDATA, 'pnpm')]
|
|
64
|
+
for (const pnpmHome of pnpmHomes) {
|
|
65
|
+
if (!pnpmHome) continue
|
|
43
66
|
for (const store of safeReaddir(join(pnpmHome, 'global'))) dirs.push(join(pnpmHome, 'global', store, 'node_modules', DSH_PACKAGE))
|
|
44
67
|
}
|
|
45
68
|
return dirs
|
|
46
69
|
}
|
|
47
70
|
|
|
71
|
+
/**
|
|
72
|
+
* Last resort for an install no guess above covers: ask npm where its global
|
|
73
|
+
* packages live (`npm root -g`). Resolves to the dsh package dir or undefined.
|
|
74
|
+
*/
|
|
75
|
+
export function npmGlobalDshDir({ run = execFile, timeoutMs = 8000 } = {}) {
|
|
76
|
+
return new Promise(resolve => {
|
|
77
|
+
try {
|
|
78
|
+
const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm'
|
|
79
|
+
// npm.cmd is a batch file: Node only runs it through a shell.
|
|
80
|
+
run(npm, ['root', '-g'], { timeout: timeoutMs, windowsHide: true, shell: process.platform === 'win32' }, (error, stdout) => {
|
|
81
|
+
const root = String(stdout ?? '').trim()
|
|
82
|
+
resolve(error || !root ? undefined : join(root, DSH_PACKAGE))
|
|
83
|
+
})
|
|
84
|
+
} catch {
|
|
85
|
+
resolve(undefined)
|
|
86
|
+
}
|
|
87
|
+
})
|
|
88
|
+
}
|
|
89
|
+
|
|
48
90
|
function safeHome() {
|
|
49
91
|
try { return homedir() } catch { return undefined }
|
|
50
92
|
}
|
|
@@ -100,6 +142,36 @@ export function findPiCatalogFile(bases = defaultBases()) {
|
|
|
100
142
|
return undefined
|
|
101
143
|
}
|
|
102
144
|
|
|
145
|
+
/**
|
|
146
|
+
* The version of the `@deepseek-ai/dsh` package this host runs from, read
|
|
147
|
+
* from its package.json (the package itself, or one found in a
|
|
148
|
+
* node_modules on the way up), or undefined when none is found.
|
|
149
|
+
*/
|
|
150
|
+
export function findDshVersion(bases = defaultBases()) {
|
|
151
|
+
const seen = new Set()
|
|
152
|
+
const read = file => {
|
|
153
|
+
try {
|
|
154
|
+
const pkg = JSON.parse(readFileSync(file, 'utf8'))
|
|
155
|
+
return pkg?.name === '@deepseek-ai/dsh' && typeof pkg.version === 'string' ? pkg.version : undefined
|
|
156
|
+
} catch {
|
|
157
|
+
return undefined
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
for (const base of bases) {
|
|
161
|
+
let dir = base
|
|
162
|
+
for (let depth = 0; depth < 8 && dir; depth += 1) {
|
|
163
|
+
if (seen.has(dir)) break
|
|
164
|
+
seen.add(dir)
|
|
165
|
+
const version = read(join(dir, 'package.json')) ?? read(join(dir, 'node_modules', DSH_PACKAGE, 'package.json'))
|
|
166
|
+
if (version) return version
|
|
167
|
+
const parent = dirname(dir)
|
|
168
|
+
if (parent === dir) break
|
|
169
|
+
dir = parent
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
return undefined
|
|
173
|
+
}
|
|
174
|
+
|
|
103
175
|
function safeExists(path) {
|
|
104
176
|
try { return existsSync(path) } catch { return false }
|
|
105
177
|
}
|
|
@@ -134,6 +206,29 @@ export function catalogCost(models, provider, model) {
|
|
|
134
206
|
return { input, cacheRead, cacheWrite, output, currency: 'USD', name: hit.name ?? model, provider: hit.provider ?? provider }
|
|
135
207
|
}
|
|
136
208
|
|
|
209
|
+
let modelsDev
|
|
210
|
+
/** The bundled models.dev snapshot: `{ [provider]: { [model]: { name, input, output, cacheRead?, cacheWrite? } } }`. */
|
|
211
|
+
export function modelsDevModels() {
|
|
212
|
+
if (modelsDev === undefined) {
|
|
213
|
+
try {
|
|
214
|
+
modelsDev = JSON.parse(readFileSync(new URL('./models-dev.json', import.meta.url), 'utf8')).models ?? {}
|
|
215
|
+
} catch {
|
|
216
|
+
modelsDev = {}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
return modelsDev
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** The models.dev row for a route: the provider's own entry first, then any provider listing that model id. */
|
|
223
|
+
export function modelsDevCost(provider, model, models = modelsDevModels()) {
|
|
224
|
+
if (!model) return undefined
|
|
225
|
+
const own = provider ? models[provider]?.[model] : undefined
|
|
226
|
+
const hit = own ?? Object.values(models).map(list => list?.[model]).find(Boolean)
|
|
227
|
+
if (!hit) return undefined
|
|
228
|
+
const { input, output, cacheRead = input, cacheWrite = input } = hit
|
|
229
|
+
return { input, cacheRead, cacheWrite, output, currency: 'USD', name: hit.name ?? model, provider }
|
|
230
|
+
}
|
|
231
|
+
|
|
137
232
|
/** Convert a per-million price row between CNY and USD with `rate` CNY per USD. */
|
|
138
233
|
export function convert(price, from, to, rate = DEFAULT_RATE) {
|
|
139
234
|
if (!price || from === to) return price
|
|
@@ -155,6 +250,8 @@ export function customPrice(cfg) {
|
|
|
155
250
|
/**
|
|
156
251
|
* Build the resolver the ledger prices each `provider/model` route with.
|
|
157
252
|
* Returns rows already converted to `currency`, tagged with their source.
|
|
253
|
+
* Listed prices of DeepSeek routes are peak prices, so those hits carry the
|
|
254
|
+
* off-peak discount; prices the user typed are taken as they are.
|
|
158
255
|
*/
|
|
159
256
|
export function makeResolver({ cfg, models, currency = cfg.currency ?? 'CNY' }) {
|
|
160
257
|
const rate = typeof cfg.exchangeRate === 'number' && cfg.exchangeRate > 0 ? cfg.exchangeRate : DEFAULT_RATE
|
|
@@ -171,25 +268,35 @@ export function makeResolver({ cfg, models, currency = cfg.currency ?? 'CNY' })
|
|
|
171
268
|
if (table && mode === 'auto') return { price: table, source: 'table' }
|
|
172
269
|
if (custom && (mode === 'auto' || mode === 'custom')) return { price: toDisplay(custom, custom.currency), source: 'custom' }
|
|
173
270
|
if (mode === 'custom') return undefined
|
|
271
|
+
const offPeak = billedToDeepseek(key) ? { offPeakFactor: DEEPSEEK_OFF_PEAK.factor } : {}
|
|
174
272
|
const fromCatalog = catalogCost(models, provider, model)
|
|
175
|
-
if (fromCatalog) return { price: toDisplay(fromCatalog, 'USD'), source: 'catalog' }
|
|
273
|
+
if (fromCatalog) return { price: toDisplay(fromCatalog, 'USD'), source: 'catalog', ...offPeak }
|
|
176
274
|
const fallback = staticPriceFor(provider, model)
|
|
177
|
-
if (fallback) return { price: toDisplay(fallback, fallback.currency), source: 'static' }
|
|
275
|
+
if (fallback) return { price: toDisplay(fallback, fallback.currency), source: 'static', ...offPeak }
|
|
276
|
+
const snapshot = modelsDevCost(provider, model)
|
|
277
|
+
if (snapshot) return { price: toDisplay(snapshot, 'USD'), source: 'modelsDev', ...offPeak }
|
|
178
278
|
return undefined
|
|
179
279
|
}
|
|
180
280
|
}
|
|
181
281
|
|
|
182
282
|
/** What the settings page shows about the route in use: the listed price and where it comes from. */
|
|
183
|
-
export function describeRoute({ cfg, models, route }) {
|
|
283
|
+
export function describeRoute({ cfg, models, route, now = Date.now() }) {
|
|
184
284
|
if (!route?.model) return undefined
|
|
185
285
|
const resolve = makeResolver({ cfg, models })
|
|
186
286
|
const hit = resolve(`${route.provider ?? ''}/${route.model}`.replace(/^\//u, ''))
|
|
187
|
-
const listed = catalogCost(models, route.provider, route.model) ?? staticPriceFor(route.provider, route.model)
|
|
287
|
+
const listed = catalogCost(models, route.provider, route.model) ?? staticPriceFor(route.provider, route.model) ?? modelsDevCost(route.provider, route.model)
|
|
188
288
|
return {
|
|
189
289
|
provider: route.provider,
|
|
190
290
|
model: route.model,
|
|
191
291
|
name: listed?.name,
|
|
192
292
|
listed: listed ? { input: listed.input, cacheRead: listed.cacheRead, cacheWrite: listed.cacheWrite, output: listed.output, currency: listed.currency } : undefined,
|
|
193
|
-
effective: hit
|
|
293
|
+
effective: hit
|
|
294
|
+
? {
|
|
295
|
+
...hit.price,
|
|
296
|
+
currency: cfg.currency ?? 'CNY',
|
|
297
|
+
source: hit.source,
|
|
298
|
+
...(hit.offPeakFactor !== undefined ? { offPeakFactor: hit.offPeakFactor, offPeakNow: isDeepseekOffPeak(now) } : {}),
|
|
299
|
+
}
|
|
300
|
+
: undefined,
|
|
194
301
|
}
|
|
195
302
|
}
|
package/lib/quota.js
CHANGED
|
@@ -234,13 +234,57 @@ export async function fetchQuota(spec, key, { fetchImpl = globalThis.fetch, now
|
|
|
234
234
|
try { json = JSON.parse(text) } catch { json = undefined }
|
|
235
235
|
if (!res.ok) {
|
|
236
236
|
const detail = json?.error?.message ?? json?.message ?? json?.msg ?? text.slice(0, 120)
|
|
237
|
-
throw new Error(`HTTP ${res.status}${detail ? `:${detail}` : ''}`)
|
|
237
|
+
throw Object.assign(new Error(`HTTP ${res.status}${detail ? `:${detail}` : ''}`), { status: res.status })
|
|
238
238
|
}
|
|
239
239
|
if (json === undefined) throw new Error('响应不是 JSON')
|
|
240
240
|
return { ok: true, at, data: parse(json) }
|
|
241
241
|
} catch (error) {
|
|
242
|
-
|
|
242
|
+
const failed = { ok: false, at, error: error?.name === 'AbortError' ? '请求超时' : (error?.message ?? String(error)) }
|
|
243
|
+
return error?.status ? { ...failed, status: error.status } : failed
|
|
243
244
|
} finally {
|
|
244
245
|
clearTimeout(timer)
|
|
245
246
|
}
|
|
246
247
|
}
|
|
248
|
+
|
|
249
|
+
/** A plain-words reason for a failed reading, so the settings page can say what to fix. */
|
|
250
|
+
export function failureHint(reading) {
|
|
251
|
+
if (reading?.status === 401 || reading?.status === 403) return 'Key 不对、已过期,或没有查询额度的权限'
|
|
252
|
+
if (reading?.status === 404) return '查询地址不对,检查「额度查询地址」'
|
|
253
|
+
if (reading?.status === 429) return '查得太频繁,稍后会自动再试'
|
|
254
|
+
if (reading?.error === '请求超时' || /fetch failed|ENOTFOUND|ECONN/u.test(reading?.error ?? '')) return '连不上查询接口,检查网络或代理'
|
|
255
|
+
return undefined
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Run a quota fetch plan (after CodexBar's provider pipeline): strategies are
|
|
260
|
+
* tried in order; each says whether it can run here (`available` resolves to
|
|
261
|
+
* true, or to the reason it cannot), fetches, and whether its failure lets
|
|
262
|
+
* the next one try (`fallback`, default: always). Every step is recorded in
|
|
263
|
+
* `attempts`, so the settings page can say why nothing came back.
|
|
264
|
+
*
|
|
265
|
+
* @param {{ id: string, label: string, available: () => Promise<true | string> | true | string, fetch: () => Promise<object>, fallback?: (reading: object) => boolean }[]} strategies
|
|
266
|
+
* @param {{ now?: () => number, noneError?: string }} [options] - `noneError`: the error when no strategy could run.
|
|
267
|
+
* @returns {Promise<object>} the last reading (or a failure when nothing could run), plus `attempts`.
|
|
268
|
+
*/
|
|
269
|
+
export async function runQuotaPlan(strategies, { now = () => Date.now(), noneError } = {}) {
|
|
270
|
+
const attempts = []
|
|
271
|
+
let last
|
|
272
|
+
for (const strategy of strategies) {
|
|
273
|
+
let available
|
|
274
|
+
try { available = await strategy.available() } catch (error) { available = error?.message ?? String(error) }
|
|
275
|
+
if (available !== true) {
|
|
276
|
+
attempts.push({ id: strategy.id, label: strategy.label, outcome: 'skipped', detail: String(available || '不可用') })
|
|
277
|
+
continue
|
|
278
|
+
}
|
|
279
|
+
const reading = await strategy.fetch()
|
|
280
|
+
attempts.push(reading.ok
|
|
281
|
+
? { id: strategy.id, label: strategy.label, outcome: 'ok' }
|
|
282
|
+
: { id: strategy.id, label: strategy.label, outcome: 'failed', detail: reading.error, hint: failureHint(reading) })
|
|
283
|
+
last = reading
|
|
284
|
+
if (reading.ok || (strategy.fallback && !strategy.fallback(reading))) break
|
|
285
|
+
}
|
|
286
|
+
if (last === undefined) {
|
|
287
|
+
last = { ok: false, at: now(), error: noneError ?? attempts.map(a => `${a.label}:${a.detail}`).join(';') }
|
|
288
|
+
}
|
|
289
|
+
return { ...last, attempts }
|
|
290
|
+
}
|
package/lib/system.js
CHANGED
|
@@ -3,6 +3,9 @@
|
|
|
3
3
|
* when no DSH window is listening) and bringing the DSH window forward.
|
|
4
4
|
*/
|
|
5
5
|
import { spawn } from 'node:child_process'
|
|
6
|
+
import { createHash } from 'node:crypto'
|
|
7
|
+
import { existsSync, mkdirSync, readdirSync, unlinkSync } from 'node:fs'
|
|
8
|
+
import { delimiter, join, posix } from 'node:path'
|
|
6
9
|
|
|
7
10
|
function run(file, args, options = {}) {
|
|
8
11
|
return new Promise(resolve => {
|
|
@@ -60,28 +63,108 @@ export function toastXml({ title, body, launch, sound = true }) {
|
|
|
60
63
|
*/
|
|
61
64
|
const POWERSHELL_AUMID = '{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe'
|
|
62
65
|
|
|
63
|
-
/**
|
|
64
|
-
|
|
66
|
+
/** Toast group every notification of this plugin is filed under. */
|
|
67
|
+
const TOAST_GROUP = 'dsh-notify-tray'
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* A toast Tag for a key (session id). Windows caps tags at 16 characters on
|
|
71
|
+
* older Windows 10 builds, so the key is hashed down to that.
|
|
72
|
+
*/
|
|
73
|
+
export function toastTag(key) {
|
|
74
|
+
return createHash('sha1').update(String(key)).digest('base64url').slice(0, 16)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function runPowerShell(lines) {
|
|
65
78
|
const script = [
|
|
66
79
|
`$null = [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]`,
|
|
80
|
+
...lines,
|
|
81
|
+
].join('; ')
|
|
82
|
+
// -EncodedCommand sidesteps every command-line quoting rule (emoji, quotes, newlines).
|
|
83
|
+
const encoded = Buffer.from(script, 'utf16le').toString('base64')
|
|
84
|
+
return run(powershell(), ['-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-EncodedCommand', encoded])
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Show one toast through WinRT from a short-lived PowerShell; no tray icon
|
|
89
|
+
* involved. A toast with the same Tag + Group replaces the earlier one.
|
|
90
|
+
*/
|
|
91
|
+
function windowsToast(xml, key) {
|
|
92
|
+
return runPowerShell([
|
|
67
93
|
`$null = [Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime]`,
|
|
68
94
|
`$doc = New-Object Windows.Data.Xml.Dom.XmlDocument`,
|
|
69
95
|
`$doc.LoadXml(${ps(xml)})`,
|
|
70
96
|
`$toast = New-Object Windows.UI.Notifications.ToastNotification $doc`,
|
|
97
|
+
...(key !== undefined ? [`$toast.Tag = ${ps(toastTag(key))}`, `$toast.Group = ${ps(TOAST_GROUP)}`] : []),
|
|
71
98
|
`[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier(${ps(POWERSHELL_AUMID)}).Show($toast)`,
|
|
72
|
-
]
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
99
|
+
])
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** POSIX shell single-quoted literal. */
|
|
103
|
+
const sh = text => `'${String(text).replace(/'/gu, "'\\''")}'`
|
|
104
|
+
|
|
105
|
+
let notifierPath
|
|
106
|
+
/**
|
|
107
|
+
* `terminal-notifier` (Homebrew), when installed. Unlike `display notification`
|
|
108
|
+
* (attributed to Script Editor, whose click only opens Script Editor), it runs
|
|
109
|
+
* a command when its notification is clicked, which is how a click reaches the
|
|
110
|
+
* session it is about.
|
|
111
|
+
*/
|
|
112
|
+
export function terminalNotifier(env = process.env, exists = existsSync) {
|
|
113
|
+
if (notifierPath !== undefined && env === process.env) return notifierPath || undefined
|
|
114
|
+
const dirs = [...String(env.PATH ?? '').split(delimiter), '/opt/homebrew/bin', '/usr/local/bin']
|
|
115
|
+
const found = dirs.filter(Boolean).map(dir => join(dir, 'terminal-notifier')).find(file => {
|
|
116
|
+
try { return exists(file) } catch { return false }
|
|
117
|
+
})
|
|
118
|
+
if (env === process.env) notifierPath = found ?? ''
|
|
119
|
+
return found
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** A session id as a file name: anything outside [A-Za-z0-9._-] is dropped. */
|
|
123
|
+
const clickName = id => String(id).replace(/[^\w.-]/gu, '')
|
|
124
|
+
|
|
125
|
+
/** terminal-notifier group of a key (session): one notification per group is ever shown. */
|
|
126
|
+
export const notifierGroup = key => `dsh-notify-tray.${clickName(key)}`
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* The shell command a clicked macOS notification runs: it drops a file named
|
|
130
|
+
* after the session into `clickDir`, which the host picks up (consumeClicks).
|
|
131
|
+
*/
|
|
132
|
+
export function clickCommand(clickDir, sessionId) {
|
|
133
|
+
// A macOS shell command: always '/'-joined, whatever OS builds it (tests run everywhere).
|
|
134
|
+
return `/usr/bin/touch ${sh(posix.join(clickDir, clickName(sessionId)))}`
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Session ids whose notification was clicked since the last call; each file is removed as it is read. */
|
|
138
|
+
export function consumeClicks(clickDir) {
|
|
139
|
+
let names
|
|
140
|
+
try { names = readdirSync(clickDir) } catch { return [] }
|
|
141
|
+
const ids = []
|
|
142
|
+
for (const name of names) {
|
|
143
|
+
try {
|
|
144
|
+
unlinkSync(join(clickDir, name))
|
|
145
|
+
ids.push(name)
|
|
146
|
+
} catch {}
|
|
147
|
+
}
|
|
148
|
+
return ids
|
|
76
149
|
}
|
|
77
150
|
|
|
78
151
|
/**
|
|
79
152
|
* Show one native notification.
|
|
80
|
-
* @param {{title: string, body: string, sound?: boolean, onClick?: () => void, webOrigin?: () => string | undefined, state?: string, iconDir?: string}} n
|
|
81
|
-
* `state` picks the whale's colour and `iconDir` where its PNG is cached (Linux)
|
|
153
|
+
* @param {{title: string, body: string, sound?: boolean, onClick?: () => void, webOrigin?: () => string | undefined, state?: string, iconDir?: string, sessionId?: string, clickDir?: string, key?: string}} n
|
|
154
|
+
* `state` picks the whale's colour and `iconDir` where its PNG is cached (Linux);
|
|
155
|
+
* `sessionId` + `clickDir` make a macOS notification clickable when terminal-notifier is installed;
|
|
156
|
+
* `key` (the session) makes this notification replace that key's previous one.
|
|
82
157
|
*/
|
|
83
158
|
export async function systemNotify(n) {
|
|
84
159
|
if (process.platform === 'darwin') {
|
|
160
|
+
const notifier = n.clickDir && n.sessionId ? terminalNotifier() : undefined
|
|
161
|
+
if (notifier) {
|
|
162
|
+
try { mkdirSync(n.clickDir, { recursive: true }) } catch {}
|
|
163
|
+
const args = ['-title', n.title, '-message', n.body, '-execute', clickCommand(n.clickDir, n.sessionId)]
|
|
164
|
+
if (n.key !== undefined) args.push('-group', notifierGroup(n.key))
|
|
165
|
+
if (n.sound) args.push('-sound', 'Glass')
|
|
166
|
+
if (await run(notifier, args)) return true
|
|
167
|
+
}
|
|
85
168
|
const sound = n.sound ? ' sound name "Glass"' : ''
|
|
86
169
|
return run('/usr/bin/osascript', ['-e', `display notification ${as(n.body)} with title ${as(n.title)}${sound}`])
|
|
87
170
|
}
|
|
@@ -90,12 +173,12 @@ export async function systemNotify(n) {
|
|
|
90
173
|
// clicking it launches dsh://open, which the app answers by focusing its
|
|
91
174
|
// window; under `dsh web` it opens the web GUI.
|
|
92
175
|
const launch = desktopHosted() ? 'dsh://open' : safeOrigin(n.webOrigin)
|
|
93
|
-
return windowsToast(toastXml({ title: n.title, body: n.body, launch, sound: n.sound !== false }))
|
|
176
|
+
return windowsToast(toastXml({ title: n.title, body: n.body, launch, sound: n.sound !== false }), n.key)
|
|
94
177
|
}
|
|
95
178
|
// Linux / BSD: D-Bus first (clickable), notify-send as a fallback.
|
|
96
179
|
try {
|
|
97
180
|
const { linuxNotify } = await import('./tray/linux.js')
|
|
98
|
-
await linuxNotify({ title: n.title, body: n.body, sound: n.sound !== false, onClick: n.onClick, state: n.state, iconDir: n.iconDir })
|
|
181
|
+
await linuxNotify({ title: n.title, body: n.body, sound: n.sound !== false, onClick: n.onClick, state: n.state, iconDir: n.iconDir, key: n.key })
|
|
99
182
|
return true
|
|
100
183
|
} catch {
|
|
101
184
|
let icon = ''
|
|
@@ -107,6 +190,29 @@ export async function systemNotify(n) {
|
|
|
107
190
|
}
|
|
108
191
|
}
|
|
109
192
|
|
|
193
|
+
/**
|
|
194
|
+
* Take back the notification shown for `key` (a session that no longer needs
|
|
195
|
+
* you). macOS can do this only for notifications sent through
|
|
196
|
+
* terminal-notifier; `display notification` ones stay until dismissed.
|
|
197
|
+
*/
|
|
198
|
+
export async function systemWithdraw(key) {
|
|
199
|
+
if (process.platform === 'darwin') {
|
|
200
|
+
const notifier = terminalNotifier()
|
|
201
|
+
return notifier ? run(notifier, ['-remove', notifierGroup(key)]) : false
|
|
202
|
+
}
|
|
203
|
+
if (process.platform === 'win32') {
|
|
204
|
+
return runPowerShell([
|
|
205
|
+
`[Windows.UI.Notifications.ToastNotificationManager]::History.Remove(${ps(toastTag(key))}, ${ps(TOAST_GROUP)}, ${ps(POWERSHELL_AUMID)})`,
|
|
206
|
+
])
|
|
207
|
+
}
|
|
208
|
+
try {
|
|
209
|
+
const { linuxWithdraw } = await import('./tray/linux.js')
|
|
210
|
+
return await linuxWithdraw(key)
|
|
211
|
+
} catch {
|
|
212
|
+
return false
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
110
216
|
/**
|
|
111
217
|
* The DSH desktop executable when this host runs inside it. Desktop spawns
|
|
112
218
|
* the host as Electron in Node mode (ELECTRON_RUN_AS_NODE), so the binary is
|
package/lib/tracker.js
CHANGED
|
@@ -237,6 +237,13 @@ export class Tracker {
|
|
|
237
237
|
return { running, runningList, waiting, recent, today: { ...this.day } }
|
|
238
238
|
}
|
|
239
239
|
|
|
240
|
+
/** Ids of the sessions that wait on the user right now. */
|
|
241
|
+
waitingSessions() {
|
|
242
|
+
const ids = new Set()
|
|
243
|
+
for (const entry of this.sessions.values()) if (entry.pending.size > 0) ids.add(entry.id)
|
|
244
|
+
return ids
|
|
245
|
+
}
|
|
246
|
+
|
|
240
247
|
eventsAfter(seq) {
|
|
241
248
|
return this.events.filter(event => event.seq > seq)
|
|
242
249
|
}
|
package/lib/tray/linux.js
CHANGED
|
@@ -304,6 +304,8 @@ export async function startLinuxTray({ onAction, logger }) {
|
|
|
304
304
|
}
|
|
305
305
|
|
|
306
306
|
const notifyActions = new Map()
|
|
307
|
+
/** The id of the notification currently shown for each key (session), so the next one replaces it. */
|
|
308
|
+
const notifyIds = new Map()
|
|
307
309
|
/** Edge of the whale drawn into notifications. */
|
|
308
310
|
const NOTIFY_ICON_SIZE = 64
|
|
309
311
|
|
|
@@ -333,21 +335,31 @@ export function notifyIcon(state = 'idle', iconDir) {
|
|
|
333
335
|
return icon
|
|
334
336
|
}
|
|
335
337
|
|
|
336
|
-
|
|
337
|
-
export async function linuxNotify({ title, body, sound = true, onClick, state = 'idle', iconDir }) {
|
|
338
|
+
async function notifications() {
|
|
338
339
|
const link = await connect()
|
|
339
|
-
const { dbus, bus } = link
|
|
340
340
|
if (!link.notifications) {
|
|
341
|
-
const obj = await bus.getProxyObject('org.freedesktop.Notifications', '/org/freedesktop/Notifications')
|
|
341
|
+
const obj = await link.bus.getProxyObject('org.freedesktop.Notifications', '/org/freedesktop/Notifications')
|
|
342
342
|
const iface = obj.getInterface('org.freedesktop.Notifications')
|
|
343
343
|
// One listener per connection: a reconnected bus gets a fresh proxy.
|
|
344
344
|
iface.on('ActionInvoked', (id, key) => {
|
|
345
345
|
if (key === 'default') notifyActions.get(id)?.()
|
|
346
346
|
})
|
|
347
|
-
iface.on('NotificationClosed', id =>
|
|
347
|
+
iface.on('NotificationClosed', id => {
|
|
348
|
+
notifyActions.delete(id)
|
|
349
|
+
for (const [key, shown] of notifyIds) if (shown === id) notifyIds.delete(key)
|
|
350
|
+
})
|
|
348
351
|
link.notifications = iface
|
|
349
352
|
}
|
|
350
|
-
|
|
353
|
+
return { dbus: link.dbus, iface: link.notifications }
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* Show one freedesktop notification; `onClick` runs when its default action
|
|
358
|
+
* is invoked. A `key` (the session) replaces that key's previous notification
|
|
359
|
+
* in place (`replaces_id`), so a session never stacks up several.
|
|
360
|
+
*/
|
|
361
|
+
export async function linuxNotify({ title, body, sound = true, onClick, state = 'idle', iconDir, key }) {
|
|
362
|
+
const { dbus, iface } = await notifications()
|
|
351
363
|
const icon = notifyIcon(state, iconDir)
|
|
352
364
|
const image = new dbus.Variant('(iiibiiay)', [icon.size, icon.size, icon.size * 4, true, 8, 4, icon.rgba])
|
|
353
365
|
const hints = {
|
|
@@ -360,7 +372,22 @@ export async function linuxNotify({ title, body, sound = true, onClick, state =
|
|
|
360
372
|
// freedesktop sound-naming spec; servers that play sounds honour these hints.
|
|
361
373
|
if (sound) hints['sound-name'] = new dbus.Variant('s', 'message-new-instant')
|
|
362
374
|
else hints['suppress-sound'] = new dbus.Variant('b', true)
|
|
363
|
-
const
|
|
375
|
+
const replaces = key !== undefined ? (notifyIds.get(key) ?? 0) : 0
|
|
376
|
+
const id = await iface.Notify('DeepSeek Harness', replaces, icon.path, title, body, ['default', '打开'], hints, -1)
|
|
377
|
+
if (replaces && replaces !== id) notifyActions.delete(replaces)
|
|
364
378
|
if (onClick) notifyActions.set(id, onClick)
|
|
379
|
+
if (key !== undefined) notifyIds.set(key, id)
|
|
365
380
|
return id
|
|
366
381
|
}
|
|
382
|
+
|
|
383
|
+
/** Take back the notification shown for `key`, if it is still up. Resolves to whether one was closed. */
|
|
384
|
+
export async function linuxWithdraw(key) {
|
|
385
|
+
const id = notifyIds.get(key)
|
|
386
|
+
if (id === undefined) return false
|
|
387
|
+
notifyIds.delete(key)
|
|
388
|
+
notifyActions.delete(id)
|
|
389
|
+
const { iface } = await notifications()
|
|
390
|
+
// Already gone (dismissed by the user): the server answers with an error, which is fine.
|
|
391
|
+
try { await iface.CloseNotification(id) } catch { return false }
|
|
392
|
+
return true
|
|
393
|
+
}
|