dsh-notify-tray 0.1.4 → 0.1.6

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,9 +35,14 @@ const KIND_ICON = {
35
35
  failed: 'xmark.circle',
36
36
  aborted: 'stop.circle',
37
37
  }
38
- const LABEL_MAX = 44
38
+ /** First-level rows. */
39
+ const LABEL_MAX = 28
39
40
  /** Submenu rows: kept short so a submenu opened toward the screen edge stays readable. */
40
- const SUB_MAX = 36
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
41
46
 
42
47
  /** Long text as several short menu rows, broken at its own separators where it can be. */
43
48
  export function wrapText(text, max = SUB_MAX) {
@@ -86,6 +91,10 @@ function clock(time) {
86
91
  }
87
92
 
88
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('估算') ? '估算' : '余额扣费')
89
98
 
90
99
  /** A reset time: ISO strings become a clock, anything the user typed stays as typed. */
91
100
  function resetText(value) {
@@ -164,7 +173,8 @@ export function buildView(tasks, usage, config, now = Date.now(), plan = undefin
164
173
  let headline
165
174
  let headIcon
166
175
  if (tasks.waiting.length > 0) {
167
- 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} 个在跑` : ''}`
168
178
  headIcon = 'bell.badge'
169
179
  } else if (tasks.running > 0) {
170
180
  headline = `正在运行 ${tasks.running} 个任务`
@@ -176,94 +186,78 @@ export function buildView(tasks, usage, config, now = Date.now(), plan = undefin
176
186
  headline = '搞定啦~ 刚完成一个任务'
177
187
  headIcon = 'sparkles'
178
188
  } else {
179
- headline = today.completed + today.failed > 0 ? `空闲 · 今日已完成 ${today.completed} 个任务` : '空闲,等你派活'
189
+ headline = today.completed + today.failed > 0 ? `空闲 · 今天完成 ${today.completed} 个` : '空闲,等你派活'
180
190
  headIcon = 'moon.zzz'
181
191
  }
182
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.
183
196
  const menu = []
184
197
  menu.push({ id: 'headline', label: headline, icon: headIcon, enabled: false })
185
198
 
186
199
  // ---- the tasks themselves --------------------------------------------------
187
- for (const wait of tasks.waiting.slice(0, 6)) {
200
+ const taskRows = []
201
+ for (const wait of tasks.waiting) {
188
202
  const detail = wait.text ? `:${wait.text}` : ''
189
- 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}`) })
190
204
  }
191
- for (const item of tasks.runningList.slice(0, 6)) {
205
+ for (const item of tasks.runningList) {
192
206
  if (tasks.waiting.some(wait => wait.sessionId === item.sessionId)) continue
193
- const bits = [item.title]
194
207
  const age = elapsed(item.since, now)
195
- if (age) bits.push(age)
196
- if (item.tool) bits.push(item.tool)
197
- 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(' · ')) })
198
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} 个…` })
199
212
  menu.push({ separator: true })
200
213
 
201
- // ---- today ---------------------------------------------------------------------
202
- // Balance is the number people glance at most, and the official usage page
203
- // the link they reach for: both on the first level, one click away.
204
- if (usage.balance !== undefined) {
205
- menu.push({ id: 'info', enabled: false, icon: 'creditcard', label: `账户余额 ${money(usage.balance, usage.currency)}` })
206
- }
207
- if (usage.usageUrl) menu.push({ id: 'usage-page', icon: 'safari', label: '查看账户用量…' })
208
- const usageRows = []
209
- usageRows.push({ id: 'info', enabled: false, icon: 'checkmark.circle', label: `完成 ${today.completed} · 失败 ${today.failed}${today.aborted ? ` · 停止 ${today.aborted}` : ''}` })
210
- if (spend) usageRows.push({ id: 'info', enabled: false, icon: 'yensign.circle', label: `花费 ${spendText}(${spend.label})` })
211
- if (usage.estimate !== undefined && spend?.label !== undefined && !spend.label.startsWith('估算') && spend.value !== usage.estimate) {
212
- usageRows.push({ id: 'info', enabled: false, icon: 'function', label: `按价格估算 ${money(usage.estimate, usage.currency)}` })
213
- }
214
- if (spend?.mixed || (spend && usage.balanceSpend !== undefined && spend.label.startsWith('估算'))) {
215
- usageRows.push({ id: 'info', enabled: false, icon: 'creditcard', label: `余额已扣 ${money(usage.balanceSpend ?? 0, usage.currency)}` })
216
- }
217
- usageRows.push({ id: 'info', enabled: false, icon: 'number', label: `Token ${compactTokens(usage.tokens.total)}(输出 ${compactTokens(usage.tokens.output)})` })
218
- // One row per provider/model route used today, biggest first. Rows stay
219
- // short: Windows / Linux trays open submenus beside the panel and long rows
220
- // run off the screen edge, so the provider only shows when two routes share
221
- // a model id, and the route in use is split into model + provider rows.
222
- const routes = (usage.byModel ?? []).slice(0, 6)
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)
223
221
  const modelCount = {}
224
222
  for (const row of routes) modelCount[row.model] = (modelCount[row.model] ?? 0) + 1
225
223
  for (const row of routes) {
226
224
  const name = row.key === 'unknown' ? '未知模型' : modelCount[row.model] > 1 ? row.key : row.model
227
- const bits = [name, compactTokens(row.tokens.input + row.tokens.cacheRead + row.tokens.cacheWrite + row.tokens.output)]
228
- if (row.cost !== undefined) bits.push(`${money(row.cost, usage.currency)} ${SOURCE_LABEL[row.source] ?? row.source}`)
229
- usageRows.push({ id: 'info', enabled: false, icon: 'cpu', label: trim(bits.join(' · '), SUB_MAX) })
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) })
230
227
  }
231
- if (usage.route?.model) {
232
- usageRows.push({ id: 'info', enabled: false, icon: 'point.3.connected.trianglepath.dotted', label: trim(`当前模型 ${usage.route.model}`, SUB_MAX) })
233
- if (usage.route.provider) usageRows.push({ id: 'info', enabled: false, icon: 'network', label: trim(`通道 ${usage.route.provider}`, SUB_MAX) })
234
- }
235
- const todayLabel = spendText ? `今日用量 · ${spendText}` : '今日用量'
236
- 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 })
237
231
 
238
- // ---- 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)}` })
239
235
  if (plan) {
240
- const planRows = []
241
- const headBits = [plan.name]
242
- if (plan.priceText) headBits.push(plan.priceText)
243
- if (plan.remaining !== undefined) headBits.push(`剩余 ${plan.remaining}`)
244
- if (plan.balance !== undefined) planRows.push({ id: 'info', enabled: false, icon: 'wallet.pass', label: `套餐余额 ${money(plan.balance, plan.balanceCurrency)}` })
245
- if (plan.remaining !== undefined) planRows.push({ id: 'info', enabled: false, icon: 'gauge.with.dots.needle.33percent', label: `剩余额度 ${plan.remaining}${plan.remainingSource === 'manual' ? '(手填)' : ''}` })
246
- if (plan.resetAt) planRows.push({ id: 'info', enabled: false, icon: 'arrow.clockwise.circle', label: `重置 ${resetText(plan.resetAt)}` })
247
- const textRows = (text, icon) => wrapText(text).slice(0, 4).forEach(label => planRows.push({ id: 'info', enabled: false, icon, label }))
248
- for (const line of plan.lines.slice(0, 4)) textRows(line, 'line.3.horizontal.decrease.circle')
249
- if (plan.quotaText) textRows(plan.quotaText, 'text.bubble')
250
- if (plan.fetch) {
251
- if (plan.fetch.ok) planRows.push({ id: 'info', enabled: false, icon: 'checkmark.icloud', label: `额度更新于 ${clock(plan.fetch.at)}` })
252
- else textRows(`获取失败:${plan.fetch.error}`, 'exclamationmark.icloud')
253
- } else if (plan.canFetch && !plan.apiKeyEnv) {
254
- planRows.push({ id: 'info', enabled: false, icon: 'key', label: '填入 API Key 引用后可自动获取额度' })
255
- }
256
- if (plan.canFetch && plan.apiKeyEnv) planRows.push({ id: 'refresh-quota', icon: 'arrow.triangle.2.circlepath', label: '刷新额度' })
257
- if (plan.links.console) planRows.push({ id: `url:${plan.links.console}`, icon: 'safari', label: `${plan.providerName} 用量页…` })
258
- if (plan.links.pricing) planRows.push({ id: `url:${plan.links.pricing}`, icon: 'tag', label: '价格页…' })
259
- 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 })
260
254
  }
261
255
 
262
256
  if (tasks.recent.length > 0) {
263
- const rows = tasks.recent.map(item => ({
257
+ const rows = tasks.recent.slice(0, SUB_ROWS).map(item => ({
264
258
  id: `open:${item.sessionId}`,
265
259
  icon: KIND_ICON[item.kind],
266
- label: trim(`${clock(item.at)} ${KIND_LABEL[item.kind]} · ${item.title}`, SUB_MAX),
260
+ label: trim(`${clock(item.at)} ${KIND_LABEL[item.kind]} · ${item.title}`, SUB_MAX),
267
261
  }))
268
262
  menu.push({ id: 'recent', icon: 'clock.arrow.circlepath', label: '最近结束', children: rows })
269
263
  }
package/lib/index.js CHANGED
@@ -21,11 +21,11 @@ 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
- import { describeRoute, loadPiCatalog, makeResolver } from './pricing.js'
26
+ import { describeRoute, findDshVersion, findPiCatalogFile, loadPiCatalog, makeResolver, npmGlobalDshDir } from './pricing.js'
27
27
  import { fetchQuota } from './quota.js'
28
- import { openUrl, showApp, systemNotify } from './system.js'
28
+ import { consumeClicks, desktopHosted, openUrl, showApp, systemNotify, terminalNotifier } from './system.js'
29
29
  import { startTray } from './tray/index.js'
30
30
  import { Tracker } from './tracker.js'
31
31
  import { speak } from './voice.js'
@@ -38,8 +38,17 @@ const STATE_PATH = '/notify-tray/state'
38
38
  const CATALOG_PATH = '/notify-tray/catalog'
39
39
  const REFRESH_PATH = '/notify-tray/refresh'
40
40
  const TRAY_PATH = '/notify-tray/tray'
41
- /** Harness version sent as account client metadata (what the built-in settings page sends). */
42
- const DSH_VERSION = '0.2.1-rc.2'
41
+ const RAISE_PATH = '/notify-tray/raise'
42
+ /**
43
+ * A clicked Windows toast can only launch `dsh://open` (or the web GUI), so no
44
+ * session travels with it: a window that comes forward within this long after
45
+ * a toast opens the session that toast announced.
46
+ */
47
+ const TOAST_CLAIM_MS = 60_000
48
+ /** Harness version sent as account client metadata when the installed one cannot be read. */
49
+ const DSH_VERSION_FALLBACK = '0.2.1-rc.2'
50
+ /** How often a price catalog that was not found is looked for again. */
51
+ const CATALOG_RETRY_MS = 10 * 60_000
43
52
  /** A window that polled within this window counts as "listening". */
44
53
  const CLIENT_FRESH_MS = 8000
45
54
  /** Platforms with a status bar the whale can live in. */
@@ -154,6 +163,8 @@ export function apply(ctx, config) {
154
163
  let lastClientPoll = 0
155
164
  /** Session ids a tray click asked the window to open, consumed by the next poll. */
156
165
  let focusQueue = []
166
+ /** The session the latest Windows toast announced: { sessionId, at }. */
167
+ let toastPending
157
168
 
158
169
  /** Set DSH_NOTIFY_TRAY_DEBUG=1 to trace tracked events into storages/dsh-notify-tray/debug.log. */
159
170
  const debug = process.env.DSH_NOTIFY_TRAY_DEBUG
@@ -289,6 +300,19 @@ export function apply(ctx, config) {
289
300
  }, 'notify-tray: tray')
290
301
 
291
302
  // ---- notifications ----------------------------------------------------
303
+ // A clicked macOS notification (sent through terminal-notifier) drops a file
304
+ // named after its session here; the host opens that session.
305
+ const clickDir = join(dir, 'clicks')
306
+ if (process.platform === 'darwin') {
307
+ ctx.effect(() => {
308
+ consumeClicks(clickDir) // stale clicks from an earlier run open nothing
309
+ const timer = setInterval(() => {
310
+ if (!terminalNotifier()) return
311
+ for (const id of consumeClicks(clickDir)) onAction(`open:${id}`)
312
+ }, 1000)
313
+ return () => clearInterval(timer)
314
+ }, 'notify-tray: notification clicks')
315
+ }
292
316
  tracker.onEvent(event => {
293
317
  debug('event', event)
294
318
  // The celebration / error pose expires on its own: refresh once it does.
@@ -301,6 +325,7 @@ export function apply(ctx, config) {
301
325
  debug('deliver', { channel, clientListening, systemSide })
302
326
  if (!systemSide) return // the window picks it up from the event queue
303
327
  const said = speak(event)
328
+ if (process.platform === 'win32') toastPending = { sessionId: event.sessionId, at: Date.now() }
304
329
  systemNotify({
305
330
  title: said.title,
306
331
  body: said.body,
@@ -308,6 +333,8 @@ export function apply(ctx, config) {
308
333
  webOrigin,
309
334
  state: EVENT_STATE[event.type],
310
335
  iconDir: join(dir, 'icons'),
336
+ sessionId: event.sessionId,
337
+ clickDir,
311
338
  onClick: () => onAction(`open:${event.sessionId}`),
312
339
  }).then(ok => debug('system notify', ok)).catch(error => logger.warn('系统通知失败', error))
313
340
  })
@@ -340,15 +367,35 @@ export function apply(ctx, config) {
340
367
  }, 'notify-tray: ledger')
341
368
 
342
369
  // ---- pi-ai price catalog (the one DSH's model selector reads) -------------
370
+ // Not found at startup (an install layout we do not guess, npm still busy…):
371
+ // ask npm once, then keep looking every few minutes until it turns up.
343
372
  ctx.effect(() => {
344
373
  let disposed = false
345
- loadPiCatalog().then(loaded => {
346
- if (disposed || !loaded) return
374
+ let timer
375
+ let askedNpm = false
376
+ const attempt = async () => {
377
+ let loaded = await loadPiCatalog()
378
+ if (!loaded && !askedNpm) {
379
+ askedNpm = true
380
+ const dir = await npmGlobalDshDir()
381
+ const file = dir ? findPiCatalogFile([dir]) : undefined
382
+ if (file) loaded = await loadPiCatalog({ file })
383
+ }
384
+ if (disposed) return
385
+ if (!loaded) {
386
+ timer = setTimeout(() => attempt().catch(() => {}), CATALOG_RETRY_MS)
387
+ timer.unref?.()
388
+ return
389
+ }
347
390
  pi = loaded
348
391
  debug('pi catalog', loaded.file)
349
392
  refresh()
350
- }).catch(() => {})
351
- return () => { disposed = true }
393
+ }
394
+ attempt().catch(() => {})
395
+ return () => {
396
+ disposed = true
397
+ clearTimeout(timer)
398
+ }
352
399
  }, 'notify-tray: price catalog')
353
400
 
354
401
  // ---- plan quota polling ---------------------------------------------------
@@ -404,8 +451,8 @@ export function apply(ctx, config) {
404
451
  // ---- DeepSeek account balance (optional service) ------------------------
405
452
  ctx.inject(['deepseekAccount'], (ctx) => {
406
453
  const client = {
407
- // Mirrors DSH's own settings page: the harness version and the UI locale.
408
- version: DSH_VERSION,
454
+ // Mirrors DSH's own settings page: the installed harness version and the UI locale.
455
+ version: findDshVersion() ?? DSH_VERSION_FALLBACK,
409
456
  locale: 'zh-CN',
410
457
  timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60,
411
458
  }
@@ -470,8 +517,14 @@ export function apply(ctx, config) {
470
517
  // a browser tab without permission must not silence the system channel.
471
518
  if (url.searchParams.get('notify') === '1') lastClientPoll = Date.now()
472
519
  const after = Number(url.searchParams.get('after') ?? '-1')
520
+ // A window that just came forward after a toast takes that toast's session, once.
521
+ if (url.searchParams.get('claim') === '1' && toastPending) {
522
+ if (Date.now() - toastPending.at < TOAST_CLAIM_MS) focusQueue.push(toastPending.sessionId)
523
+ toastPending = undefined
524
+ }
473
525
  const channel = cfg.channel
474
526
  const clientSide = channel === 'auto' || channel === 'client' || channel === 'both'
527
+ const currentUsage = usage()
475
528
  const enabled = Object.fromEntries(Object.entries(EVENT_SWITCH).map(([type, key]) => [type, Boolean(cfg[key])]))
476
529
  const body = {
477
530
  boot,
@@ -487,7 +540,9 @@ export function apply(ctx, config) {
487
540
  suppressWhenFocused: cfg.suppressWhenFocused,
488
541
  focus: focusQueue,
489
542
  summary: tracker.summary(),
490
- usage: usage(),
543
+ usage: currentUsage,
544
+ // Today's figure exactly as the tray shows it, for the settings page's spend card.
545
+ spend: spendOf(currentUsage, cfg.spendSource) ?? null,
491
546
  pricing: pricing(),
492
547
  plan: plan(),
493
548
  catalogLoaded: Boolean(pi),
@@ -515,6 +570,19 @@ export function apply(ctx, config) {
515
570
  .catch(error => json(res, { quota: { ok: false, at: Date.now(), error: String(error?.message ?? error) }, plan: plan() }))
516
571
  },
517
572
  }), `notify-tray: POST ${REFRESH_PATH}`)
573
+ // A click on an in-window notification: the renderer cannot change the OS
574
+ // foreground, so in the Windows desktop app the host relaunches it, and the
575
+ // single-instance handler restores a minimized window (a visible window
576
+ // behind another one stays put: Windows' foreground lock, see issue #4).
577
+ ctx.effect(() => ctx.webServer.register({
578
+ kind: 'exact',
579
+ path: RAISE_PATH,
580
+ handler: (req, res) => {
581
+ if (!guard(req, res, 'POST')) return
582
+ const raise = process.platform === 'win32' && desktopHosted() ? open() : Promise.resolve(false)
583
+ raise.then(raised => json(res, { raised: Boolean(raised) }))
584
+ },
585
+ }), `notify-tray: POST ${RAISE_PATH}`)
518
586
  // The settings page's "show the whale again": undoes the tray menu's hide.
519
587
  ctx.effect(() => ctx.webServer.register({
520
588
  kind: 'exact',
package/lib/ledger.js CHANGED
@@ -6,13 +6,15 @@
6
6
  * samples with token-meter's dedupe rule (each (turn, step) slot keeps its
7
7
  * last sample; `llm/retry-started` opens a new slot), filed under the
8
8
  * `provider/model` route the session's latest `request/header` announced
9
- * and priced by a resolver (see pricing.js) per million tokens;
9
+ * and priced by a resolver (see pricing.js) per million tokens; DeepSeek
10
+ * tokens used off-peak are also counted apart (`offPeak`), so the
11
+ * resolver's `offPeakFactor` can discount them;
10
12
  * - balance: polled DeepSeek account balance; the day's spend is the sum of
11
13
  * balance drops, so a top-up never reads as negative spend.
12
14
  */
13
15
  import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
14
16
  import { dirname } from 'node:path'
15
- import { providerForRoute } from './catalog.js'
17
+ import { isDeepseekOffPeak, providerForRoute } from './catalog.js'
16
18
  import { localDate } from './tracker.js'
17
19
 
18
20
  /** Days of history kept on disk. */
@@ -114,7 +116,7 @@ export class Ledger {
114
116
  const date = localDate(this.now())
115
117
  let day = this.days[date]
116
118
  if (day === undefined) {
117
- day = { date, tokens: zero(), byModel: {}, balanceSpend: {}, balanceLast: {} }
119
+ day = { date, tokens: zero(), byModel: {}, offPeak: {}, balanceSpend: {}, balanceLast: {} }
118
120
  // Carry the last known balance across midnight so the first poll of the day diffs against it.
119
121
  const previous = Object.keys(this.days).sort().pop()
120
122
  if (previous !== undefined) day.balanceLast = { ...this.days[previous].balanceLast }
@@ -172,10 +174,13 @@ export class Ledger {
172
174
  const previous = slot && slot.turn === turn && slot.step === step ? slot : undefined
173
175
  const day = this.today()
174
176
  const byModel = (day.byModel[key] ??= zero())
177
+ // Days recorded before off-peak tracking have no `offPeak` map.
178
+ const offPeak = billedToDeepseek(key) && isDeepseekOffPeak(this.now()) ? ((day.offPeak ??= {})[key] ??= zero()) : undefined
175
179
  for (const bucket of Object.keys(next)) {
176
180
  const delta = next[bucket] - (previous?.buckets[bucket] ?? 0)
177
181
  day.tokens[bucket] += delta
178
182
  byModel[bucket] += delta
183
+ if (offPeak) offPeak[bucket] += delta
179
184
  }
180
185
  this.slots.set(id, { turn, step, buckets: next })
181
186
  this.changed()
@@ -208,7 +213,9 @@ export class Ledger {
208
213
  * Today's totals. `pricing` is either a user price table (per million tokens,
209
214
  * keyed by route / model id / prefix) or a resolver
210
215
  * `(routeKey) => { price, source } | undefined` whose price is already in the
211
- * display currency. The estimate is undefined until at least one route priced.
216
+ * display currency. A hit with `offPeakFactor` bills the route's off-peak
217
+ * tokens at that fraction of its price. The estimate is undefined until at
218
+ * least one route priced.
212
219
  */
213
220
  summary(pricing, currency) {
214
221
  const day = this.today()
@@ -223,7 +230,10 @@ export class Ledger {
223
230
  const byModel = []
224
231
  for (const [key, buckets] of Object.entries(day.byModel)) {
225
232
  const hit = resolve(key)
226
- const cost = hit ? round(costOf(buckets, hit.price)) : undefined
233
+ const offPeak = hit?.offPeakFactor !== undefined ? day.offPeak?.[key] : undefined
234
+ const cost = hit
235
+ ? round(costOf(buckets, hit.price) - (offPeak ? costOf(offPeak, hit.price) * (1 - hit.offPeakFactor) : 0))
236
+ : undefined
227
237
  if (hit) {
228
238
  priced = true
229
239
  sources.add(hit.source)
package/lib/pricing.js CHANGED
@@ -7,12 +7,13 @@
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, realpathSync } from 'node:fs'
10
+ import { execFile } from 'node:child_process'
11
+ import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs'
11
12
  import { homedir } from 'node:os'
12
13
  import { dirname, join } from 'node:path'
13
14
  import { pathToFileURL } from 'node:url'
14
- import { priceFor, splitRoute } from './ledger.js'
15
- import { staticPriceFor } from './catalog.js'
15
+ import { billedToDeepseek, priceFor, splitRoute } from './ledger.js'
16
+ import { DEEPSEEK_OFF_PEAK, isDeepseekOffPeak, staticPriceFor } from './catalog.js'
16
17
 
17
18
  const PI_AI_REL = join('@earendil-works', 'pi-ai', 'dist', 'models.generated.js')
18
19
  /** Fallback CNY-per-USD rate when the user leaves the setting blank. */
@@ -25,26 +26,64 @@ const DSH_PACKAGE = join('@deepseek-ai', 'dsh')
25
26
  /**
26
27
  * Where a globally installed `@deepseek-ai/dsh` (the web / CLI profile) may
27
28
  * 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
+ * prefix of the node running us, npm's Windows prefix (`%APPDATA%\npm`),
30
+ * pnpm's global store, and every node a version manager (nvm, nvm-windows,
31
+ * fnm, volta) installed.
29
32
  */
30
33
  export function globalDshDirs(env = process.env, home = safeHome(), execPath = process.execPath) {
31
34
  const prefixes = [env.npm_config_prefix, env.NPM_CONFIG_PREFIX, env.PREFIX]
32
35
  if (home) prefixes.push(join(home, '.npm-global'), join(home, '.npm-packages'), join(home, '.local'))
33
- if (execPath) prefixes.push(dirname(dirname(execPath)))
36
+ if (execPath) prefixes.push(dirname(dirname(execPath)), dirname(execPath))
37
+ if (env.APPDATA) prefixes.push(join(env.APPDATA, 'npm'))
34
38
  prefixes.push('/usr/local', '/usr', '/opt/homebrew')
39
+ // Version managers keep one prefix per installed node; DSH may sit under any of them.
40
+ const nvmDir = env.NVM_DIR || (home ? join(home, '.nvm') : undefined)
41
+ if (nvmDir) for (const v of safeReaddir(join(nvmDir, 'versions', 'node'))) prefixes.push(join(nvmDir, 'versions', 'node', v))
42
+ if (env.NVM_HOME) for (const v of safeReaddir(env.NVM_HOME)) prefixes.push(join(env.NVM_HOME, v))
43
+ 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')]
44
+ for (const fnm of fnmDirs) {
45
+ if (!fnm) continue
46
+ for (const v of safeReaddir(join(fnm, 'node-versions'))) prefixes.push(join(fnm, 'node-versions', v, 'installation'))
47
+ }
35
48
  const dirs = []
36
49
  for (const prefix of prefixes) {
37
50
  if (!prefix) continue
38
51
  // POSIX prefixes keep packages under lib/; Windows prefixes keep them at the top.
39
52
  dirs.push(join(prefix, 'lib', 'node_modules', DSH_PACKAGE), join(prefix, 'node_modules', DSH_PACKAGE))
40
53
  }
41
- const pnpmHome = env.PNPM_HOME || (home ? join(home, '.local', 'share', 'pnpm') : undefined)
42
- if (pnpmHome) {
54
+ // Volta installs each global package into its own image.
55
+ const volta = env.VOLTA_HOME || (home ? join(home, '.volta') : undefined)
56
+ if (volta) {
57
+ const image = join(volta, 'tools', 'image', 'packages', DSH_PACKAGE)
58
+ dirs.push(join(image, 'lib', 'node_modules', DSH_PACKAGE), join(image, 'node_modules', DSH_PACKAGE))
59
+ }
60
+ const pnpmHomes = [env.PNPM_HOME, home && join(home, '.local', 'share', 'pnpm'), home && join(home, 'Library', 'pnpm'), env.LOCALAPPDATA && join(env.LOCALAPPDATA, 'pnpm')]
61
+ for (const pnpmHome of pnpmHomes) {
62
+ if (!pnpmHome) continue
43
63
  for (const store of safeReaddir(join(pnpmHome, 'global'))) dirs.push(join(pnpmHome, 'global', store, 'node_modules', DSH_PACKAGE))
44
64
  }
45
65
  return dirs
46
66
  }
47
67
 
68
+ /**
69
+ * Last resort for an install no guess above covers: ask npm where its global
70
+ * packages live (`npm root -g`). Resolves to the dsh package dir or undefined.
71
+ */
72
+ export function npmGlobalDshDir({ run = execFile, timeoutMs = 8000 } = {}) {
73
+ return new Promise(resolve => {
74
+ try {
75
+ const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm'
76
+ // npm.cmd is a batch file: Node only runs it through a shell.
77
+ run(npm, ['root', '-g'], { timeout: timeoutMs, windowsHide: true, shell: process.platform === 'win32' }, (error, stdout) => {
78
+ const root = String(stdout ?? '').trim()
79
+ resolve(error || !root ? undefined : join(root, DSH_PACKAGE))
80
+ })
81
+ } catch {
82
+ resolve(undefined)
83
+ }
84
+ })
85
+ }
86
+
48
87
  function safeHome() {
49
88
  try { return homedir() } catch { return undefined }
50
89
  }
@@ -100,6 +139,36 @@ export function findPiCatalogFile(bases = defaultBases()) {
100
139
  return undefined
101
140
  }
102
141
 
142
+ /**
143
+ * The version of the `@deepseek-ai/dsh` package this host runs from, read
144
+ * from its package.json (the package itself, or one found in a
145
+ * node_modules on the way up), or undefined when none is found.
146
+ */
147
+ export function findDshVersion(bases = defaultBases()) {
148
+ const seen = new Set()
149
+ const read = file => {
150
+ try {
151
+ const pkg = JSON.parse(readFileSync(file, 'utf8'))
152
+ return pkg?.name === '@deepseek-ai/dsh' && typeof pkg.version === 'string' ? pkg.version : undefined
153
+ } catch {
154
+ return undefined
155
+ }
156
+ }
157
+ for (const base of bases) {
158
+ let dir = base
159
+ for (let depth = 0; depth < 8 && dir; depth += 1) {
160
+ if (seen.has(dir)) break
161
+ seen.add(dir)
162
+ const version = read(join(dir, 'package.json')) ?? read(join(dir, 'node_modules', DSH_PACKAGE, 'package.json'))
163
+ if (version) return version
164
+ const parent = dirname(dir)
165
+ if (parent === dir) break
166
+ dir = parent
167
+ }
168
+ }
169
+ return undefined
170
+ }
171
+
103
172
  function safeExists(path) {
104
173
  try { return existsSync(path) } catch { return false }
105
174
  }
@@ -155,6 +224,8 @@ export function customPrice(cfg) {
155
224
  /**
156
225
  * Build the resolver the ledger prices each `provider/model` route with.
157
226
  * Returns rows already converted to `currency`, tagged with their source.
227
+ * Listed prices of DeepSeek routes are peak prices, so those hits carry the
228
+ * off-peak discount; prices the user typed are taken as they are.
158
229
  */
159
230
  export function makeResolver({ cfg, models, currency = cfg.currency ?? 'CNY' }) {
160
231
  const rate = typeof cfg.exchangeRate === 'number' && cfg.exchangeRate > 0 ? cfg.exchangeRate : DEFAULT_RATE
@@ -171,16 +242,17 @@ export function makeResolver({ cfg, models, currency = cfg.currency ?? 'CNY' })
171
242
  if (table && mode === 'auto') return { price: table, source: 'table' }
172
243
  if (custom && (mode === 'auto' || mode === 'custom')) return { price: toDisplay(custom, custom.currency), source: 'custom' }
173
244
  if (mode === 'custom') return undefined
245
+ const offPeak = billedToDeepseek(key) ? { offPeakFactor: DEEPSEEK_OFF_PEAK.factor } : {}
174
246
  const fromCatalog = catalogCost(models, provider, model)
175
- if (fromCatalog) return { price: toDisplay(fromCatalog, 'USD'), source: 'catalog' }
247
+ if (fromCatalog) return { price: toDisplay(fromCatalog, 'USD'), source: 'catalog', ...offPeak }
176
248
  const fallback = staticPriceFor(provider, model)
177
- if (fallback) return { price: toDisplay(fallback, fallback.currency), source: 'static' }
249
+ if (fallback) return { price: toDisplay(fallback, fallback.currency), source: 'static', ...offPeak }
178
250
  return undefined
179
251
  }
180
252
  }
181
253
 
182
254
  /** 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 }) {
255
+ export function describeRoute({ cfg, models, route, now = Date.now() }) {
184
256
  if (!route?.model) return undefined
185
257
  const resolve = makeResolver({ cfg, models })
186
258
  const hit = resolve(`${route.provider ?? ''}/${route.model}`.replace(/^\//u, ''))
@@ -190,6 +262,13 @@ export function describeRoute({ cfg, models, route }) {
190
262
  model: route.model,
191
263
  name: listed?.name,
192
264
  listed: listed ? { input: listed.input, cacheRead: listed.cacheRead, cacheWrite: listed.cacheWrite, output: listed.output, currency: listed.currency } : undefined,
193
- effective: hit ? { ...hit.price, currency: cfg.currency ?? 'CNY', source: hit.source } : undefined,
265
+ effective: hit
266
+ ? {
267
+ ...hit.price,
268
+ currency: cfg.currency ?? 'CNY',
269
+ source: hit.source,
270
+ ...(hit.offPeakFactor !== undefined ? { offPeakFactor: hit.offPeakFactor, offPeakNow: isDeepseekOffPeak(now) } : {}),
271
+ }
272
+ : undefined,
194
273
  }
195
274
  }