dsh-notify-tray 0.1.3 → 0.1.5

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
@@ -35,7 +35,34 @@ const KIND_ICON = {
35
35
  failed: 'xmark.circle',
36
36
  aborted: 'stop.circle',
37
37
  }
38
- const LABEL_MAX = 56
38
+ /** First-level rows. */
39
+ const LABEL_MAX = 28
40
+ /** Submenu rows: kept short so a submenu opened toward the screen edge stays readable. */
41
+ const SUB_MAX = 24
42
+ /** Task rows on the first level; the rest are one "还有 n 个…" row. */
43
+ const TASK_ROWS = 5
44
+ /** Rows per submenu, separators included. */
45
+ const SUB_ROWS = 6
46
+
47
+ /** Long text as several short menu rows, broken at its own separators where it can be. */
48
+ export function wrapText(text, max = SUB_MAX) {
49
+ const pieces = String(text).split(/(?<=[;;,,。])|(?= · )/u).map(p => p.replace(/^ · /u, ''))
50
+ const rows = []
51
+ let current = ''
52
+ for (const piece of pieces) {
53
+ if (current && current.length + piece.length > max) {
54
+ rows.push(current)
55
+ current = ''
56
+ }
57
+ current += piece
58
+ while (current.length > max) {
59
+ rows.push(current.slice(0, max))
60
+ current = current.slice(max)
61
+ }
62
+ }
63
+ if (current.trim()) rows.push(current)
64
+ return rows.map(row => row.trim()).filter(Boolean)
65
+ }
39
66
 
40
67
  export function money(value, currency) {
41
68
  if (value === undefined || value === null) return undefined
@@ -64,6 +91,10 @@ function clock(time) {
64
91
  }
65
92
 
66
93
  const trim = (text, max = LABEL_MAX) => (text.length > max ? `${text.slice(0, max - 1)}…` : text)
94
+ /** "<name> <amount>" within SUB_MAX, shortening the name so the amount always shows. */
95
+ const trimEnd = (name, amount) => `${trim(name, Math.max(4, SUB_MAX - amount.length - 1))} ${amount}`
96
+ /** The spend figure's source, in a word or two. */
97
+ const spendHow = spend => (spend.mixed ? '含估算' : spend.label.startsWith('估算') ? '估算' : '余额扣费')
67
98
 
68
99
  /** A reset time: ISO strings become a clock, anything the user typed stays as typed. */
69
100
  function resetText(value) {
@@ -74,18 +105,37 @@ function resetText(value) {
74
105
  return `${sameDay ? '' : `${d.getMonth() + 1}/${d.getDate()} `}${clock(ms)}`
75
106
  }
76
107
 
77
- /** Pick which spend figure to show: real balance drops when available, else the price-table estimate. */
108
+ /**
109
+ * Pick which spend figure to show: real balance drops when available, else the
110
+ * price-table estimate.
111
+ *
112
+ * In `auto` the balance only stands for what it actually pays for (DeepSeek
113
+ * routes), and the platform books charges a while after a turn ends: when the
114
+ * DeepSeek routes' estimate is ahead of the balance drops, the estimate is
115
+ * shown until the balance catches up. Other providers' routes are always
116
+ * added on as an estimate.
117
+ */
78
118
  export function spendOf(usage, source) {
79
- const fromBalance = usage.balanceSpend !== undefined || usage.balance !== undefined
80
- ? { value: usage.balanceSpend ?? 0, label: '余额扣费' }
81
- : undefined
119
+ const hasBalance = usage.balanceSpend !== undefined || usage.balance !== undefined
120
+ const fromBalance = hasBalance ? { value: usage.balanceSpend ?? 0, label: '余额扣费' } : undefined
82
121
  const sources = (usage.estimateSources ?? []).map(key => SOURCE_LABEL[key] ?? key)
83
- const fromEstimate = usage.estimate !== undefined ? { value: usage.estimate, label: sources.length ? `估算 · ${sources.join('+')}` : '估算' } : undefined
122
+ const estimateLabel = sources.length ? `估算 · ${sources.join('+')}` : '估算'
123
+ const fromEstimate = usage.estimate !== undefined ? { value: usage.estimate, label: estimateLabel } : undefined
84
124
  if (source === 'balance') return fromBalance
85
125
  if (source === 'estimate') return fromEstimate
86
- return fromBalance ?? fromEstimate
126
+ if (!fromBalance) return fromEstimate
127
+ if (!fromEstimate) return fromBalance
128
+ const deepseek = usage.estimateDeepseek ?? 0
129
+ const others = Math.max(0, round4(usage.estimate - deepseek))
130
+ const lagging = deepseek > fromBalance.value
131
+ const value = round4((lagging ? deepseek : fromBalance.value) + others)
132
+ const parts = [lagging ? '余额未到账,暂按估算' : '余额扣费']
133
+ if (others > 0) parts.push('含其它平台估算')
134
+ return { value, label: parts.join(','), mixed: lagging || others > 0 }
87
135
  }
88
136
 
137
+ const round4 = value => Math.round(value * 10000) / 10000
138
+
89
139
  /** How long the whale celebrates after a finish before going back to idle. */
90
140
  export const DONE_HOLD_MS = 6000
91
141
 
@@ -123,7 +173,8 @@ export function buildView(tasks, usage, config, now = Date.now(), plan = undefin
123
173
  let headline
124
174
  let headIcon
125
175
  if (tasks.waiting.length > 0) {
126
- headline = `有 ${tasks.waiting.length} 件事等你处理`
176
+ const others = tasks.runningList.filter(item => !tasks.waiting.some(wait => wait.sessionId === item.sessionId)).length
177
+ headline = `${tasks.waiting.length} 件事等你${others > 0 ? ` · ${others} 个在跑` : ''}`
127
178
  headIcon = 'bell.badge'
128
179
  } else if (tasks.running > 0) {
129
180
  headline = `正在运行 ${tasks.running} 个任务`
@@ -135,81 +186,78 @@ export function buildView(tasks, usage, config, now = Date.now(), plan = undefin
135
186
  headline = '搞定啦~ 刚完成一个任务'
136
187
  headIcon = 'sparkles'
137
188
  } else {
138
- headline = today.completed + today.failed > 0 ? `空闲 · 今日已完成 ${today.completed} 个任务` : '空闲,等你派活'
189
+ headline = today.completed + today.failed > 0 ? `空闲 · 今天完成 ${today.completed} 个` : '空闲,等你派活'
139
190
  headIcon = 'moon.zzz'
140
191
  }
141
192
 
193
+ // The menu is kept short and shallow: Windows / Linux trays open submenus
194
+ // beside the panel, and long rows or deep submenus run off the screen edge.
195
+ // At most TASK_ROWS task rows, one level of submenus, SUB_ROWS rows each.
142
196
  const menu = []
143
197
  menu.push({ id: 'headline', label: headline, icon: headIcon, enabled: false })
144
198
 
145
199
  // ---- the tasks themselves --------------------------------------------------
146
- for (const wait of tasks.waiting.slice(0, 6)) {
200
+ const taskRows = []
201
+ for (const wait of tasks.waiting) {
147
202
  const detail = wait.text ? `:${wait.text}` : ''
148
- menu.push({ id: `open:${wait.sessionId}`, icon: KIND_ICON[wait.kind], label: trim(`${KIND_LABEL[wait.kind]} · ${wait.title}${detail}`) })
203
+ taskRows.push({ id: `open:${wait.sessionId}`, icon: KIND_ICON[wait.kind], label: trim(`${KIND_LABEL[wait.kind]} · ${wait.title}${detail}`) })
149
204
  }
150
- for (const item of tasks.runningList.slice(0, 6)) {
205
+ for (const item of tasks.runningList) {
151
206
  if (tasks.waiting.some(wait => wait.sessionId === item.sessionId)) continue
152
- const bits = [item.title]
153
207
  const age = elapsed(item.since, now)
154
- if (age) bits.push(age)
155
- if (item.tool) bits.push(item.tool)
156
- menu.push({ id: `open:${item.sessionId}`, icon: 'play.circle', label: trim(bits.join(' · ')) })
208
+ taskRows.push({ id: `open:${item.sessionId}`, icon: 'play.circle', label: trim([item.title, age].filter(Boolean).join(' · ')) })
157
209
  }
210
+ menu.push(...taskRows.slice(0, TASK_ROWS))
211
+ if (taskRows.length > TASK_ROWS) menu.push({ id: 'show-app', icon: 'ellipsis.circle', label: `还有 ${taskRows.length - TASK_ROWS} 个…` })
158
212
  menu.push({ separator: true })
159
213
 
160
- // ---- today ---------------------------------------------------------------------
161
- // Balance is the number people glance at most, and the official usage page
162
- // the link they reach for: both on the first level, one click away.
163
- if (usage.balance !== undefined) {
164
- menu.push({ id: 'info', enabled: false, icon: 'creditcard', label: `账户余额 ${money(usage.balance, usage.currency)}` })
165
- }
166
- if (usage.usageUrl) menu.push({ id: 'usage-page', icon: 'safari', label: '查看账户用量…' })
167
- const usageRows = []
168
- usageRows.push({ id: 'info', enabled: false, icon: 'checkmark.circle', label: `完成 ${today.completed} · 失败 ${today.failed}${today.aborted ? ` · 停止 ${today.aborted}` : ''}` })
169
- if (spend) usageRows.push({ id: 'info', enabled: false, icon: 'yensign.circle', label: `花费 ${spendText}(${spend.label})` })
170
- if (usage.estimate !== undefined && spend?.label !== undefined && !spend.label.startsWith('估算')) {
171
- usageRows.push({ id: 'info', enabled: false, icon: 'function', label: `按价格估算 ${money(usage.estimate, usage.currency)}` })
172
- }
173
- usageRows.push({ id: 'info', enabled: false, icon: 'number', label: `Token ${compactTokens(usage.tokens.total)}(输出 ${compactTokens(usage.tokens.output)})` })
174
- // One row per provider/model route used today, biggest first.
175
- for (const row of (usage.byModel ?? []).slice(0, 6)) {
176
- const bits = [row.key === 'unknown' ? '未知模型' : row.key, `${compactTokens(row.tokens.input + row.tokens.cacheRead + row.tokens.cacheWrite + row.tokens.output)} token`]
177
- if (row.cost !== undefined) bits.push(`${money(row.cost, usage.currency)}(${SOURCE_LABEL[row.source] ?? row.source})`)
178
- usageRows.push({ id: 'info', enabled: false, icon: 'cpu', label: trim(bits.join(' · '), 72) })
214
+ // ---- today -------------------------------------------------------------------
215
+ const todayRows = []
216
+ todayRows.push({ id: 'info', enabled: false, icon: 'checkmark.circle', label: `完成 ${today.completed} · 失败 ${today.failed}${today.aborted ? ` · 停止 ${today.aborted}` : ''}` })
217
+ if (spend) todayRows.push({ id: 'info', enabled: false, icon: 'yensign.circle', label: `花费 ${spendText} · ${spendHow(spend)}` })
218
+ todayRows.push({ id: 'info', enabled: false, icon: 'number', label: `Token ${compactTokens(usage.tokens.total)}` })
219
+ // The biggest routes used today; the provider only shows when two routes share a model id.
220
+ const routes = (usage.byModel ?? []).slice(0, SUB_ROWS - todayRows.length)
221
+ const modelCount = {}
222
+ for (const row of routes) modelCount[row.model] = (modelCount[row.model] ?? 0) + 1
223
+ for (const row of routes) {
224
+ const name = row.key === 'unknown' ? '未知模型' : modelCount[row.model] > 1 ? row.key : row.model
225
+ const amount = row.cost !== undefined ? money(row.cost, usage.currency) : compactTokens(row.tokens.input + row.tokens.cacheRead + row.tokens.cacheWrite + row.tokens.output)
226
+ todayRows.push({ id: 'info', enabled: false, icon: 'cpu', label: trimEnd(name, amount) })
179
227
  }
180
- if (usage.route?.model) {
181
- usageRows.push({ id: 'info', enabled: false, icon: 'point.3.connected.trianglepath.dotted', label: trim(`当前模型 ${usage.route.provider ? `${usage.route.provider}/` : ''}${usage.route.model}`, 72) })
182
- }
183
- const todayLabel = spendText ? `今日用量 · ${spendText}` : '今日用量'
184
- menu.push({ id: 'today', icon: 'chart.bar', label: todayLabel, children: usageRows })
228
+ const todayBits = ['今日']
229
+ if (spendText) todayBits.push(spendText)
230
+ menu.push({ id: 'today', icon: 'chart.bar', label: `${todayBits.join(' ')} · 完成 ${today.completed}`, children: todayRows })
185
231
 
186
- // ---- the plan ------------------------------------------------------------------
232
+ // ---- balance and plan: one submenu -------------------------------------------------
233
+ const accountRows = []
234
+ if (usage.balance !== undefined) accountRows.push({ id: 'info', enabled: false, icon: 'creditcard', label: `DeepSeek 余额 ${money(usage.balance, usage.currency)}` })
187
235
  if (plan) {
188
- const planRows = []
189
- const headBits = [plan.name]
190
- if (plan.priceText) headBits.push(plan.priceText)
191
- if (plan.remaining !== undefined) headBits.push(`剩余 ${plan.remaining}`)
192
- if (plan.balance !== undefined) planRows.push({ id: 'info', enabled: false, icon: 'wallet.pass', label: `套餐余额 ${money(plan.balance, plan.balanceCurrency)}` })
193
- if (plan.remaining !== undefined) planRows.push({ id: 'info', enabled: false, icon: 'gauge.with.dots.needle.33percent', label: `剩余额度 ${plan.remaining}${plan.remainingSource === 'manual' ? '(手填)' : ''}` })
194
- if (plan.resetAt) planRows.push({ id: 'info', enabled: false, icon: 'arrow.clockwise.circle', label: `重置 ${resetText(plan.resetAt)}` })
195
- for (const line of plan.lines.slice(0, 4)) planRows.push({ id: 'info', enabled: false, icon: 'line.3.horizontal.decrease.circle', label: trim(line, 72) })
196
- if (plan.quotaText) planRows.push({ id: 'info', enabled: false, icon: 'text.bubble', label: trim(plan.quotaText, 72) })
197
- if (plan.fetch) {
198
- planRows.push({ id: 'info', enabled: false, icon: plan.fetch.ok ? 'checkmark.icloud' : 'exclamationmark.icloud', label: plan.fetch.ok ? `额度更新于 ${clock(plan.fetch.at)}` : trim(`获取失败:${plan.fetch.error}`, 72) })
199
- } else if (plan.canFetch && !plan.apiKeyEnv) {
200
- planRows.push({ id: 'info', enabled: false, icon: 'key', label: '填入 API Key 引用后可自动获取额度' })
201
- }
202
- if (plan.canFetch && plan.apiKeyEnv) planRows.push({ id: 'refresh-quota', icon: 'arrow.triangle.2.circlepath', label: '刷新额度' })
203
- if (plan.links.console) planRows.push({ id: `url:${plan.links.console}`, icon: 'safari', label: `${plan.providerName} 用量页…` })
204
- if (plan.links.pricing) planRows.push({ id: `url:${plan.links.pricing}`, icon: 'tag', label: '价格页…' })
205
- menu.push({ id: 'plan', icon: 'creditcard.circle', label: trim(`套餐 · ${headBits.join(' · ')}`, 72), children: planRows })
236
+ accountRows.push({ id: 'info', enabled: false, icon: 'creditcard.circle', label: trim([plan.name, plan.priceText].filter(Boolean).join(' · '), SUB_MAX) })
237
+ const left = [plan.remaining !== undefined ? `剩余 ${plan.remaining}${plan.remainingSource === 'manual' ? '(手填)' : ''}` : undefined, plan.resetAt ? `${resetText(plan.resetAt)} 重置` : undefined].filter(Boolean)
238
+ if (left.length) accountRows.push({ id: 'info', enabled: false, icon: 'gauge.with.dots.needle.33percent', label: trim(left.join(' · '), SUB_MAX) })
239
+ if (plan.balance !== undefined) accountRows.push({ id: 'info', enabled: false, icon: 'wallet.pass', label: `套餐余额 ${money(plan.balance, plan.balanceCurrency)}` })
240
+ if (plan.fetch && !plan.fetch.ok) accountRows.push({ id: 'info', enabled: false, icon: 'exclamationmark.icloud', label: '额度获取失败,详见设置页' })
241
+ else if (plan.canFetch && !plan.apiKeyEnv) accountRows.push({ id: 'info', enabled: false, icon: 'key', label: '设置页填 API Key 后可查额度' })
242
+ }
243
+ const actions = []
244
+ if (plan?.canFetch && plan.apiKeyEnv) actions.push({ id: 'refresh-quota', icon: 'arrow.triangle.2.circlepath', label: '刷新额度' })
245
+ const consoles = [usage.usageUrl ? ['usage-page', 'DeepSeek'] : undefined, plan?.links.console ? [`url:${plan.links.console}`, plan.providerName] : undefined].filter(Boolean)
246
+ for (const [id, name] of consoles) actions.push({ id, icon: 'safari', label: consoles.length > 1 ? trim(`${name} 用量页…`, SUB_MAX) : '打开用量页…' })
247
+ if (accountRows.length || actions.length) {
248
+ const accountBits = []
249
+ if (usage.balance !== undefined) accountBits.push(`余额 ${money(usage.balance, usage.currency)}`)
250
+ if (plan?.remaining !== undefined) accountBits.push(`${plan.providerName ?? plan.name} 剩 ${plan.remaining}`)
251
+ else if (plan && usage.balance === undefined) accountBits.push(`套餐 · ${plan.name}`)
252
+ const children = [...accountRows.slice(0, SUB_ROWS - actions.length), ...(accountRows.length && actions.length ? [{ separator: true }] : []), ...actions]
253
+ menu.push({ id: 'account', icon: 'creditcard', label: trim(accountBits.join(' · ') || '账户与套餐'), children })
206
254
  }
207
255
 
208
256
  if (tasks.recent.length > 0) {
209
- const rows = tasks.recent.map(item => ({
257
+ const rows = tasks.recent.slice(0, SUB_ROWS).map(item => ({
210
258
  id: `open:${item.sessionId}`,
211
259
  icon: KIND_ICON[item.kind],
212
- label: trim(`${clock(item.at)} ${KIND_LABEL[item.kind]} · ${item.title}`),
260
+ label: trim(`${clock(item.at)} ${KIND_LABEL[item.kind]} · ${item.title}`, SUB_MAX),
213
261
  }))
214
262
  menu.push({ id: 'recent', icon: 'clock.arrow.circlepath', label: '最近结束', children: rows })
215
263
  }
package/lib/icon.js CHANGED
@@ -1,13 +1,15 @@
1
1
  /**
2
2
  * Software rasterizer for the Linux tray icon: the whale from lib/whale.js
3
3
  * filled with the state colour, emitted as StatusNotifierItem IconPixmap data
4
- * (ARGB32, network byte order). No image libraries needed.
4
+ * (ARGB32, network byte order), plus RGBA / PNG for the notification icon.
5
+ * No image libraries needed.
5
6
  *
6
7
  * Polygons are the flattened bezier outlines, filled by scanline with the
7
8
  * nonzero winding rule at 4×4 supersampling, so the eye and cap band holes
8
9
  * come out and edges stay smooth. It runs on the host's main thread, so it
9
10
  * has to be quick: a 48 px frame takes about a millisecond.
10
11
  */
12
+ import { deflateSync } from 'node:zlib'
11
13
  import { BOUNDS, STATE_RGB, flatten, whalePaths } from './whale.js'
12
14
 
13
15
  export { STATE_RGB }
@@ -96,3 +98,62 @@ export function asciiIcon(size, state, frame = 0) {
96
98
  }
97
99
  return rows.join('\n')
98
100
  }
101
+
102
+ /** RGBA pixels (straight alpha, row-major), the layout freedesktop's `image-data` hint wants. */
103
+ export function rgbaIcon(size, state, frame = 0) {
104
+ const argb = renderIcon(size, state, frame)
105
+ const out = Buffer.alloc(argb.length)
106
+ for (let p = 0; p < argb.length; p += 4) {
107
+ out[p] = argb[p + 1]
108
+ out[p + 1] = argb[p + 2]
109
+ out[p + 2] = argb[p + 3]
110
+ out[p + 3] = argb[p]
111
+ }
112
+ return out
113
+ }
114
+
115
+ const CRC_TABLE = (() => {
116
+ const table = new Uint32Array(256)
117
+ for (let n = 0; n < 256; n += 1) {
118
+ let c = n
119
+ for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
120
+ table[n] = c >>> 0
121
+ }
122
+ return table
123
+ })()
124
+
125
+ function crc32(buffer) {
126
+ let c = 0xffffffff
127
+ for (const byte of buffer) c = CRC_TABLE[(c ^ byte) & 0xff] ^ (c >>> 8)
128
+ return (c ^ 0xffffffff) >>> 0
129
+ }
130
+
131
+ function chunk(type, data) {
132
+ const head = Buffer.alloc(8)
133
+ head.writeUInt32BE(data.length, 0)
134
+ head.write(type, 4, 'ascii')
135
+ const crc = Buffer.alloc(4)
136
+ crc.writeUInt32BE(crc32(Buffer.concat([head.subarray(4), data])), 0)
137
+ return Buffer.concat([head, data, crc])
138
+ }
139
+
140
+ /** The whale as a PNG file's bytes (for notification servers that only take an icon path). */
141
+ export function pngIcon(size, state, frame = 0) {
142
+ const rgba = rgbaIcon(size, state, frame)
143
+ const raw = Buffer.alloc((size * 4 + 1) * size)
144
+ for (let y = 0; y < size; y += 1) {
145
+ raw[y * (size * 4 + 1)] = 0 // filter: none
146
+ rgba.copy(raw, y * (size * 4 + 1) + 1, y * size * 4, (y + 1) * size * 4)
147
+ }
148
+ const ihdr = Buffer.alloc(13)
149
+ ihdr.writeUInt32BE(size, 0)
150
+ ihdr.writeUInt32BE(size, 4)
151
+ ihdr[8] = 8 // bit depth
152
+ ihdr[9] = 6 // RGBA
153
+ return Buffer.concat([
154
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
155
+ chunk('IHDR', ihdr),
156
+ chunk('IDAT', deflateSync(raw)),
157
+ chunk('IEND', Buffer.alloc(0)),
158
+ ])
159
+ }
package/lib/index.js CHANGED
@@ -11,7 +11,7 @@
11
11
  * polls the provider's quota endpoint when it has one and an API key.
12
12
  * - Drives a status-bar icon on macOS (menu bar) and Linux (StatusNotifierItem).
13
13
  * Windows has no status bar of the kind: there the plugin only notifies.
14
- * - Serves `GET notify-tray/state` (+ `/catalog`, `POST /refresh`) to the
14
+ * - Serves `GET notify-tray/state` (+ `/catalog`, `POST /refresh`, `POST /tray`) to the
15
15
  * browser half, which shows native notifications from the DSH window and
16
16
  * renders the settings page; when no window is polling, the host falls
17
17
  * back to OS notifications itself.
@@ -21,7 +21,7 @@ import { appendFileSync, mkdirSync } from 'node:fs'
21
21
  import { homedir } from 'node:os'
22
22
  import { join } from 'node:path'
23
23
  import { planView, publicCatalog, quotaSpecFor } from './catalog.js'
24
- import { buildView, DONE_HOLD_MS, TITLES } from './format.js'
24
+ import { buildView, DONE_HOLD_MS, spendOf, TITLES } from './format.js'
25
25
  import { Ledger } from './ledger.js'
26
26
  import { describeRoute, loadPiCatalog, makeResolver } from './pricing.js'
27
27
  import { fetchQuota } from './quota.js'
@@ -37,12 +37,15 @@ export const inject = ['agents']
37
37
  const STATE_PATH = '/notify-tray/state'
38
38
  const CATALOG_PATH = '/notify-tray/catalog'
39
39
  const REFRESH_PATH = '/notify-tray/refresh'
40
+ const TRAY_PATH = '/notify-tray/tray'
40
41
  /** Harness version sent as account client metadata (what the built-in settings page sends). */
41
42
  const DSH_VERSION = '0.2.1-rc.2'
42
43
  /** A window that polled within this window counts as "listening". */
43
44
  const CLIENT_FRESH_MS = 8000
44
45
  /** Platforms with a status bar the whale can live in. */
45
46
  export const TRAY_PLATFORMS = new Set(['darwin', 'linux', 'freebsd'])
47
+ /** The whale's colour on a notification of each kind. */
48
+ const EVENT_STATE = { completed: 'done', failed: 'error', approval: 'attention', choice: 'attention', input: 'attention' }
46
49
  const EVENT_SWITCH = {
47
50
  completed: 'notifyCompleted',
48
51
  failed: 'notifyFailed',
@@ -74,7 +77,7 @@ export const Config = z.object({
74
77
  ]).default('auto').description('通知通道').volatile(),
75
78
  suppressWhenFocused: z.boolean().default(true).description('正在看这个会话时不弹').volatile(),
76
79
  sound: z.boolean().default(true).description('系统通知带提示音').volatile(),
77
- tray: z.boolean().default(true).description('显示状态栏图标(macOS / Linux,修改后重启 DSH 生效;Windows 没有状态栏,忽略此项)').volatile(),
80
+ tray: z.boolean().default(true).description('显示状态栏图标(macOS / Linux,立即生效;Windows 没有状态栏,忽略此项)').volatile(),
78
81
  titleStyle: z.union([
79
82
  z.const('text').description('文字:待处理 1 / 运行中 2'),
80
83
  z.const('count').description('只显示数字'),
@@ -209,9 +212,9 @@ export function apply(ctx, config) {
209
212
  if (action === 'refresh-quota') return void pollQuota(true)
210
213
  if (action.startsWith('url:')) return void openUrl(action.slice(4))
211
214
  if (action === 'hide-tray') {
212
- const t = tray
213
- tray = undefined
214
- t?.stop()
215
+ // Hidden for this run only: the settings page offers to bring it back.
216
+ trayHidden = true
217
+ syncTray()
215
218
  return
216
219
  }
217
220
  if (action.startsWith('open:')) {
@@ -222,25 +225,66 @@ export function apply(ctx, config) {
222
225
 
223
226
  // Windows has no status bar to live in (and the desktop app keeps a tray
224
227
  // icon of its own): there the plugin is notifications only.
225
- const trayWanted = cfg.tray && TRAY_PLATFORMS.has(process.platform)
228
+ // The icon follows the `tray` setting live, and "隐藏状态栏图标" in its menu
229
+ // hides it until the settings page (or a restart) brings it back.
230
+ let trayHidden = false
231
+ let trayStarting
232
+ let trayDisposed = false
233
+ /** A start that failed (no D-Bus, no tray host…) is not retried until the setting or the page asks again. */
234
+ let trayFailed = false
235
+ const trayWanted = () => Boolean(cfg.tray) && !trayHidden && !trayDisposed && TRAY_PLATFORMS.has(process.platform)
236
+ const stopTray = () => {
237
+ const t = tray
238
+ tray = undefined
239
+ return t?.stop()
240
+ }
241
+ const syncTray = () => {
242
+ if (trayStarting) return trayStarting
243
+ if (!trayWanted()) return stopTray()
244
+ if (tray) return undefined
245
+ trayStarting = startTray({ stateDir: dir, icon: iconSpec(), onAction, logger })
246
+ .then(t => {
247
+ if (!trayWanted()) return void t.stop()
248
+ tray = t
249
+ tray.update(view())
250
+ })
251
+ .catch(error => {
252
+ trayFailed = true
253
+ logger.warn('状态栏图标启动失败,只保留通知功能', error)
254
+ })
255
+ .finally(() => {
256
+ trayStarting = undefined
257
+ // The setting may have flipped while the helper was starting.
258
+ if (!trayFailed && Boolean(tray) !== trayWanted()) syncTray()
259
+ })
260
+ return trayStarting
261
+ }
262
+ const trayStatus = () => ({
263
+ supported: TRAY_PLATFORMS.has(process.platform),
264
+ enabled: Boolean(cfg.tray),
265
+ hidden: trayHidden,
266
+ shown: Boolean(tray),
267
+ failed: trayFailed,
268
+ })
226
269
  ctx.effect(() => {
227
- let disposed = false
228
- let started
229
- if (trayWanted) {
230
- started = startTray({ stateDir: dir, icon: iconSpec(), onAction, logger })
231
- .then(t => {
232
- if (disposed) return void t.stop()
233
- tray = t
234
- tray.update(view())
235
- })
236
- .catch(error => logger.warn('状态栏图标启动失败,只保留通知功能', error))
237
- }
270
+ trayDisposed = false
271
+ syncTray()
272
+ // Settings fields are read live; a cheap check picks up a flipped toggle without a restart.
273
+ let enabled = Boolean(cfg.tray)
274
+ const timer = setInterval(() => {
275
+ if (Boolean(cfg.tray) !== enabled) {
276
+ enabled = Boolean(cfg.tray)
277
+ trayFailed = false
278
+ // Switching the setting back on also undoes a hide from the tray menu.
279
+ if (enabled) trayHidden = false
280
+ }
281
+ if (!trayFailed && !trayStarting && Boolean(tray) !== trayWanted()) syncTray()
282
+ }, 2000)
238
283
  return () => {
239
- disposed = true
284
+ trayDisposed = true
285
+ clearInterval(timer)
240
286
  clearTimeout(refreshTimer)
241
- const t = tray
242
- tray = undefined
243
- t?.stop()
287
+ stopTray()
244
288
  }
245
289
  }, 'notify-tray: tray')
246
290
 
@@ -262,6 +306,8 @@ export function apply(ctx, config) {
262
306
  body: said.body,
263
307
  sound: cfg.sound,
264
308
  webOrigin,
309
+ state: EVENT_STATE[event.type],
310
+ iconDir: join(dir, 'icons'),
265
311
  onClick: () => onAction(`open:${event.sessionId}`),
266
312
  }).then(ok => debug('system notify', ok)).catch(error => logger.warn('系统通知失败', error))
267
313
  })
@@ -426,6 +472,7 @@ export function apply(ctx, config) {
426
472
  const after = Number(url.searchParams.get('after') ?? '-1')
427
473
  const channel = cfg.channel
428
474
  const clientSide = channel === 'auto' || channel === 'client' || channel === 'both'
475
+ const currentUsage = usage()
429
476
  const enabled = Object.fromEntries(Object.entries(EVENT_SWITCH).map(([type, key]) => [type, Boolean(cfg[key])]))
430
477
  const body = {
431
478
  boot,
@@ -441,10 +488,13 @@ export function apply(ctx, config) {
441
488
  suppressWhenFocused: cfg.suppressWhenFocused,
442
489
  focus: focusQueue,
443
490
  summary: tracker.summary(),
444
- usage: usage(),
491
+ usage: currentUsage,
492
+ // Today's figure exactly as the tray shows it, for the settings page's spend card.
493
+ spend: spendOf(currentUsage, cfg.spendSource) ?? null,
445
494
  pricing: pricing(),
446
495
  plan: plan(),
447
496
  catalogLoaded: Boolean(pi),
497
+ tray: trayStatus(),
448
498
  }
449
499
  focusQueue = []
450
500
  json(res, body)
@@ -468,5 +518,18 @@ export function apply(ctx, config) {
468
518
  .catch(error => json(res, { quota: { ok: false, at: Date.now(), error: String(error?.message ?? error) }, plan: plan() }))
469
519
  },
470
520
  }), `notify-tray: POST ${REFRESH_PATH}`)
521
+ // The settings page's "show the whale again": undoes the tray menu's hide.
522
+ ctx.effect(() => ctx.webServer.register({
523
+ kind: 'exact',
524
+ path: TRAY_PATH,
525
+ handler: (req, res) => {
526
+ if (!guard(req, res, 'POST')) return
527
+ trayHidden = false
528
+ trayFailed = false
529
+ Promise.resolve(syncTray())
530
+ .catch(() => {})
531
+ .then(() => json(res, { tray: trayStatus() }))
532
+ },
533
+ }), `notify-tray: POST ${TRAY_PATH}`)
471
534
  })
472
535
  }
package/lib/ledger.js CHANGED
@@ -12,6 +12,7 @@
12
12
  */
13
13
  import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
14
14
  import { dirname } from 'node:path'
15
+ import { providerForRoute } from './catalog.js'
15
16
  import { localDate } from './tracker.js'
16
17
 
17
18
  /** Days of history kept on disk. */
@@ -216,6 +217,7 @@ export class Ledger {
216
217
  return price ? { price, source: 'table' } : undefined
217
218
  }
218
219
  let estimate = 0
220
+ let deepseekEstimate = 0
219
221
  let priced = false
220
222
  const sources = new Set()
221
223
  const byModel = []
@@ -226,6 +228,7 @@ export class Ledger {
226
228
  priced = true
227
229
  sources.add(hit.source)
228
230
  estimate += cost
231
+ if (billedToDeepseek(key)) deepseekEstimate += cost
229
232
  }
230
233
  byModel.push({ ...splitRoute(key), key, tokens: buckets, cost, source: hit?.source })
231
234
  }
@@ -237,6 +240,8 @@ export class Ledger {
237
240
  byModel,
238
241
  estimate: priced ? round(estimate) : undefined,
239
242
  estimateSources: [...sources],
243
+ // The part of the estimate the DeepSeek account balance also pays for (DeepSeek routes).
244
+ estimateDeepseek: priced ? round(deepseekEstimate) : undefined,
240
245
  balance: day.balanceLast[currency],
241
246
  balanceSpend: day.balanceSpend[currency],
242
247
  currency,
@@ -245,6 +250,13 @@ export class Ledger {
245
250
  }
246
251
  }
247
252
 
253
+ /** Does usage filed under this route key come out of the DeepSeek account balance? */
254
+ export function billedToDeepseek(key) {
255
+ const { provider, model } = splitRoute(key)
256
+ if (provider) return providerForRoute(provider) === 'deepseek'
257
+ return /^deepseek/iu.test(model)
258
+ }
259
+
248
260
  const sumOf = t => t.input + t.cacheRead + t.cacheWrite + t.output
249
261
 
250
262
  function round(value) {
package/lib/pricing.js CHANGED
@@ -7,7 +7,8 @@
7
7
  * same catalog the model selector reads) → this plugin's own static catalog
8
8
  * (catalog.js). Everything comes out in the display currency.
9
9
  */
10
- import { existsSync, readdirSync } from 'node:fs'
10
+ import { existsSync, readdirSync, realpathSync } from 'node:fs'
11
+ import { homedir } from 'node:os'
11
12
  import { dirname, join } from 'node:path'
12
13
  import { pathToFileURL } from 'node:url'
13
14
  import { priceFor, splitRoute } from './ledger.js'
@@ -19,12 +20,53 @@ export const DEFAULT_RATE = 7.2
19
20
  /** Human labels for where a price came from. */
20
21
  export const SOURCE_LABEL = { table: '价格表', custom: '自定义价', catalog: '目录价', static: '内置价' }
21
22
 
23
+ const DSH_PACKAGE = join('@deepseek-ai', 'dsh')
24
+
25
+ /**
26
+ * Where a globally installed `@deepseek-ai/dsh` (the web / CLI profile) may
27
+ * live: npm's configured prefix, the common `~/.npm-global` user prefix, the
28
+ * prefix of the node running us, and pnpm's global store.
29
+ */
30
+ export function globalDshDirs(env = process.env, home = safeHome(), execPath = process.execPath) {
31
+ const prefixes = [env.npm_config_prefix, env.NPM_CONFIG_PREFIX, env.PREFIX]
32
+ if (home) prefixes.push(join(home, '.npm-global'), join(home, '.npm-packages'), join(home, '.local'))
33
+ if (execPath) prefixes.push(dirname(dirname(execPath)))
34
+ prefixes.push('/usr/local', '/usr', '/opt/homebrew')
35
+ const dirs = []
36
+ for (const prefix of prefixes) {
37
+ if (!prefix) continue
38
+ // POSIX prefixes keep packages under lib/; Windows prefixes keep them at the top.
39
+ dirs.push(join(prefix, 'lib', 'node_modules', DSH_PACKAGE), join(prefix, 'node_modules', DSH_PACKAGE))
40
+ }
41
+ const pnpmHome = env.PNPM_HOME || (home ? join(home, '.local', 'share', 'pnpm') : undefined)
42
+ if (pnpmHome) {
43
+ for (const store of safeReaddir(join(pnpmHome, 'global'))) dirs.push(join(pnpmHome, 'global', store, 'node_modules', DSH_PACKAGE))
44
+ }
45
+ return dirs
46
+ }
47
+
48
+ function safeHome() {
49
+ try { return homedir() } catch { return undefined }
50
+ }
51
+
52
+ function safeRealpath(path) {
53
+ try { return realpathSync(path) } catch { return undefined }
54
+ }
55
+
22
56
  /** Directories worth walking up from to find the pi-ai package DSH ships. */
23
57
  function defaultBases() {
24
58
  const bases = []
25
59
  if (process.env.DSH_NOTIFY_TRAY_PI_AI) bases.push(process.env.DSH_NOTIFY_TRAY_PI_AI)
26
- // Desktop host: argv[2] is the DSH runtime dir; CLI: argv[1] is the dsh entry script.
27
- for (const arg of [process.argv[2], process.argv[1]]) if (arg) bases.push(arg)
60
+ // Desktop host: argv[2] is the DSH runtime dir; CLI: argv[1] is the dsh entry script,
61
+ // usually a bin symlink (~/.npm-global/bin/dsh) whose real path sits inside the package.
62
+ for (const arg of [process.argv[2], process.argv[1]]) {
63
+ if (!arg) continue
64
+ const real = safeRealpath(arg)
65
+ if (real && real !== arg) bases.push(real)
66
+ bases.push(arg)
67
+ }
68
+ // `dsh web` started from a global install leaves neither argv entry pointing into the package.
69
+ bases.push(...globalDshDirs())
28
70
  bases.push(dirname(process.execPath), process.cwd())
29
71
  return bases
30
72
  }
@@ -39,6 +81,9 @@ export function findPiCatalogFile(bases = defaultBases()) {
39
81
  seen.add(dir)
40
82
  const direct = join(dir, 'node_modules', PI_AI_REL)
41
83
  if (safeExists(direct)) return direct
84
+ // A hoisted copy next to the package (global node_modules, pi-ai as a sibling).
85
+ const sibling = join(dir, PI_AI_REL)
86
+ if (safeExists(sibling)) return sibling
42
87
  const pnpm = join(dir, 'node_modules', '.pnpm')
43
88
  if (safeExists(pnpm)) {
44
89
  for (const entry of safeReaddir(pnpm)) {