dsh-notify-tray 0.1.6 → 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/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,7 +5,10 @@
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). Everything comes out in the display currency.
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
13
  import { execFile } from 'node:child_process'
11
14
  import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs'
@@ -19,7 +22,7 @@ const PI_AI_REL = join('@earendil-works', 'pi-ai', 'dist', 'models.generated.js'
19
22
  /** Fallback CNY-per-USD rate when the user leaves the setting blank. */
20
23
  export const DEFAULT_RATE = 7.2
21
24
  /** Human labels for where a price came from. */
22
- export const SOURCE_LABEL = { table: '价格表', custom: '自定义价', catalog: '目录价', static: '内置价' }
25
+ export const SOURCE_LABEL = { table: '价格表', custom: '自定义价', catalog: '目录价', static: '内置价', modelsDev: 'models.dev 价' }
23
26
 
24
27
  const DSH_PACKAGE = join('@deepseek-ai', 'dsh')
25
28
 
@@ -203,6 +206,29 @@ export function catalogCost(models, provider, model) {
203
206
  return { input, cacheRead, cacheWrite, output, currency: 'USD', name: hit.name ?? model, provider: hit.provider ?? provider }
204
207
  }
205
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
+
206
232
  /** Convert a per-million price row between CNY and USD with `rate` CNY per USD. */
207
233
  export function convert(price, from, to, rate = DEFAULT_RATE) {
208
234
  if (!price || from === to) return price
@@ -247,6 +273,8 @@ export function makeResolver({ cfg, models, currency = cfg.currency ?? 'CNY' })
247
273
  if (fromCatalog) return { price: toDisplay(fromCatalog, 'USD'), source: 'catalog', ...offPeak }
248
274
  const fallback = staticPriceFor(provider, model)
249
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 }
250
278
  return undefined
251
279
  }
252
280
  }
@@ -256,7 +284,7 @@ export function describeRoute({ cfg, models, route, now = Date.now() }) {
256
284
  if (!route?.model) return undefined
257
285
  const resolve = makeResolver({ cfg, models })
258
286
  const hit = resolve(`${route.provider ?? ''}/${route.model}`.replace(/^\//u, ''))
259
- 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)
260
288
  return {
261
289
  provider: route.provider,
262
290
  model: route.model,
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
- return { ok: false, at, error: error?.name === 'AbortError' ? '请求超时' : (error?.message ?? String(error)) }
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,7 @@
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'
6
7
  import { existsSync, mkdirSync, readdirSync, unlinkSync } from 'node:fs'
7
8
  import { delimiter, join, posix } from 'node:path'
8
9
 
@@ -62,19 +63,40 @@ export function toastXml({ title, body, launch, sound = true }) {
62
63
  */
63
64
  const POWERSHELL_AUMID = '{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe'
64
65
 
65
- /** Show one toast through WinRT from a short-lived PowerShell; no tray icon involved. */
66
- function windowsToast(xml) {
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) {
67
78
  const script = [
68
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([
69
93
  `$null = [Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime]`,
70
94
  `$doc = New-Object Windows.Data.Xml.Dom.XmlDocument`,
71
95
  `$doc.LoadXml(${ps(xml)})`,
72
96
  `$toast = New-Object Windows.UI.Notifications.ToastNotification $doc`,
97
+ ...(key !== undefined ? [`$toast.Tag = ${ps(toastTag(key))}`, `$toast.Group = ${ps(TOAST_GROUP)}`] : []),
73
98
  `[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier(${ps(POWERSHELL_AUMID)}).Show($toast)`,
74
- ].join('; ')
75
- // -EncodedCommand sidesteps every command-line quoting rule (emoji, quotes, newlines).
76
- const encoded = Buffer.from(script, 'utf16le').toString('base64')
77
- return run(powershell(), ['-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-EncodedCommand', encoded])
99
+ ])
78
100
  }
79
101
 
80
102
  /** POSIX shell single-quoted literal. */
@@ -100,6 +122,9 @@ export function terminalNotifier(env = process.env, exists = existsSync) {
100
122
  /** A session id as a file name: anything outside [A-Za-z0-9._-] is dropped. */
101
123
  const clickName = id => String(id).replace(/[^\w.-]/gu, '')
102
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
+
103
128
  /**
104
129
  * The shell command a clicked macOS notification runs: it drops a file named
105
130
  * after the session into `clickDir`, which the host picks up (consumeClicks).
@@ -125,9 +150,10 @@ export function consumeClicks(clickDir) {
125
150
 
126
151
  /**
127
152
  * Show one native notification.
128
- * @param {{title: string, body: string, sound?: boolean, onClick?: () => void, webOrigin?: () => string | undefined, state?: string, iconDir?: string, sessionId?: string, clickDir?: string}} n
153
+ * @param {{title: string, body: string, sound?: boolean, onClick?: () => void, webOrigin?: () => string | undefined, state?: string, iconDir?: string, sessionId?: string, clickDir?: string, key?: string}} n
129
154
  * `state` picks the whale's colour and `iconDir` where its PNG is cached (Linux);
130
- * `sessionId` + `clickDir` make a macOS notification clickable when terminal-notifier is installed.
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.
131
157
  */
132
158
  export async function systemNotify(n) {
133
159
  if (process.platform === 'darwin') {
@@ -135,6 +161,7 @@ export async function systemNotify(n) {
135
161
  if (notifier) {
136
162
  try { mkdirSync(n.clickDir, { recursive: true }) } catch {}
137
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))
138
165
  if (n.sound) args.push('-sound', 'Glass')
139
166
  if (await run(notifier, args)) return true
140
167
  }
@@ -146,12 +173,12 @@ export async function systemNotify(n) {
146
173
  // clicking it launches dsh://open, which the app answers by focusing its
147
174
  // window; under `dsh web` it opens the web GUI.
148
175
  const launch = desktopHosted() ? 'dsh://open' : safeOrigin(n.webOrigin)
149
- 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)
150
177
  }
151
178
  // Linux / BSD: D-Bus first (clickable), notify-send as a fallback.
152
179
  try {
153
180
  const { linuxNotify } = await import('./tray/linux.js')
154
- 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 })
155
182
  return true
156
183
  } catch {
157
184
  let icon = ''
@@ -163,6 +190,29 @@ export async function systemNotify(n) {
163
190
  }
164
191
  }
165
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
+
166
216
  /**
167
217
  * The DSH desktop executable when this host runs inside it. Desktop spawns
168
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
- /** Show one freedesktop notification; `onClick` runs when its default action is invoked. */
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 => notifyActions.delete(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
- const iface = link.notifications
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 id = await iface.Notify('DeepSeek Harness', 0, icon.path, title, body, ['default', '打开'], hints, -1)
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
+ }
package/lib/voice.js CHANGED
@@ -29,6 +29,11 @@ const LINES = {
29
29
  { title: '🐳 要不要放行?', body: '『{s}』想执行一个操作,等你点头:{q}' },
30
30
  { title: '🐳 这个可以做吗?', body: '『{s}』在等你的批准:{q}' },
31
31
  ],
32
+ // Several tasks finished within a few seconds of the first one: one notice for all of them.
33
+ completedMany: [
34
+ { title: '🐳 又搞定 {n} 个!', body: '{list}也都做完啦,一起来验收吧' },
35
+ { title: '🐳 连着做完 {n} 个~', body: '{list}都收工了,本鲸今天状态超好' },
36
+ ],
32
37
  failed: [
33
38
  { title: '🐳 呜…翻车了', body: '『{s}』没做完:{q} 要不要再试一次?' },
34
39
  { title: '🐳 沉下去了一下下', body: '『{s}』出了点状况:{q} 鲸鱼在等你救援' },
@@ -36,12 +41,25 @@ const LINES = {
36
41
  }
37
42
 
38
43
  const FALLBACK = { title: '🐳 DeepSeek Harness', body: '『{s}』{q}' }
44
+ /** Session names a merged notice spells out before saying "等 n 个". */
45
+ const LIST_MAX = 3
46
+
47
+ function listOf(sessions, count) {
48
+ const names = sessions.slice(0, LIST_MAX).map(s => `『${s.title || '会话'}』`).join('')
49
+ return sessions.length > LIST_MAX ? `${names}等 ${count} 个任务` : names
50
+ }
39
51
 
40
52
  /**
41
- * @param {{type: string, seq?: number, title: string, body?: string}} event
53
+ * @param {{type: string, seq?: number, title: string, body?: string, count?: number, sessions?: {title: string}[]}} event
54
+ * `count` + `sessions`: a merged notice for several completions (lib/notices.js).
42
55
  * @returns {{title: string, body: string}}
43
56
  */
44
57
  export function speak(event) {
58
+ if (event.type === 'completed' && event.count > 1 && Array.isArray(event.sessions)) {
59
+ const variants = LINES.completedMany
60
+ const line = variants[Math.abs(event.seq ?? 0) % variants.length]
61
+ return { title: line.title.replace('{n}', event.count), body: line.body.replace('{list}', listOf(event.sessions, event.count)) }
62
+ }
45
63
  const variants = LINES[event.type] ?? [FALLBACK]
46
64
  const line = variants[Math.abs(event.seq ?? 0) % variants.length]
47
65
  const session = event.title || '这个会话'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-notify-tray",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
4
4
  "description": "DeepSeek Harness 通知 + 状态栏插件:任务完成、需要输入、需要选择时弹系统通知(macOS / Windows / Linux);macOS 与 Linux(含 UOS、Deepin、麒麟)状态栏常驻小图标,显示任务进度与花费。Windows 没有状态栏,只弹通知。",
5
5
  "keywords": [
6
6
  "deepseek",
@@ -50,7 +50,8 @@
50
50
  },
51
51
  "scripts": {
52
52
  "test": "node --test --test-force-exit test/*.test.js",
53
- "version": "node scripts/sync-readme-version.mjs && git add README.md README.zh-CN.md"
53
+ "version": "node scripts/sync-readme-version.mjs && git add README.md README.zh-CN.md",
54
+ "update-prices": "node scripts/update-models-dev.mjs"
54
55
  },
55
56
  "dsh": {
56
57
  "bundle": {