dsh-notify-tray 0.1.8 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md CHANGED
@@ -56,7 +56,7 @@ The spend and plan section shows daily spend, the current model, and its API pri
56
56
  - **Spend:** Auto prefers DeepSeek account balance changes, using estimates while billing catches up. Other providers use token usage and unit prices. These figures are estimates; the provider's bill is authoritative.
57
57
  - **Prices:** Your prices take priority, followed by DSH's model catalog, built-in prices, or the bundled models.dev snapshot. Custom prices and the exchange rate are under **Advanced**.
58
58
  - **Plans:** Choosing a provider and plan fills preset values. Expand the plan details to edit the name, price, period, balance, and quota.
59
- - **Automatic quota:** Enter the credential reference name saved in DSH's Models page, or an environment-variable name, under **API key reference**. Clicking **Refresh** saves pending settings before querying quota. Enter the reference name, not the secret itself. Providers without a quota endpoint allow manual values or blank fields.
59
+ - **Automatic quota:** Enter the credential reference name saved in DSH's Models page, or an environment-variable name, under **API key reference**. Clicking **Refresh** saves pending settings before querying quota. Enter the reference name, not the secret itself. Providers without a quota endpoint allow manual values or blank fields. Switching providers selects the new provider’s quota endpoint and key reference. If you use a custom key name, enter it again for the new provider.
60
60
  - **Query failures:** The page shows the reason and credential sources tried. Check the reference name, permissions, and selected provider before refreshing.
61
61
 
62
62
  Plan presets and price snapshots may lag behind provider changes and can be overridden. A subscription's price and API token spend are shown separately.
package/README.md CHANGED
@@ -56,7 +56,7 @@
56
56
  - **花费**:默认优先使用 DeepSeek 账户余额变化;余额更新有延迟时先显示估算,其他平台按 Token 用量与单价估算。此数字用于参考,实际账单以服务商为准。
57
57
  - **价格**:优先使用你填写的价格,其次使用 DSH 模型目录、插件内置价格或随插件发布的 models.dev 快照。自定义单价与汇率在「高级设置」里调整。
58
58
  - **套餐**:选择平台和套餐后,会填入预设信息;可以展开「手动改套餐信息」修改名称、价格、周期、余额和额度。
59
- - **自动查额度**:在「API Key 引用」填写 DSH「模型」页保存密钥时使用的名字,或环境变量名,点击「刷新」时会先保存当前设置,再查询额度。这里填的是引用名,不是密钥本身。没有额度接口的平台可手填,也可以留空。
59
+ - **自动查额度**:在「API Key 引用」填写 DSH「模型」页保存密钥时使用的名字,或环境变量名,点击「刷新」时会先保存当前设置,再查询额度。这里填的是引用名,不是密钥本身。没有额度接口的平台可手填,也可以留空。切换平台时,查询地址和密钥引用会随平台更新。使用自定义密钥名时,需要为新平台重新填写。
60
60
  - **查询失败**:页面会显示失败原因及尝试过的密钥来源。检查引用名、密钥权限和所选平台后再刷新。
61
61
 
62
62
  套餐预设和价格快照可能落后于服务商调整,都可以手动覆盖。套餐订阅价格不等于 API Token 花费,两者分别显示。
package/README.zh-CN.md CHANGED
@@ -56,7 +56,7 @@
56
56
  - **花费**:默认优先使用 DeepSeek 账户余额变化;余额更新有延迟时先显示估算,其他平台按 Token 用量与单价估算。此数字用于参考,实际账单以服务商为准。
57
57
  - **价格**:优先使用你填写的价格,其次使用 DSH 模型目录、插件内置价格或随插件发布的 models.dev 快照。自定义单价与汇率在「高级设置」里调整。
58
58
  - **套餐**:选择平台和套餐后,会填入预设信息;可以展开「手动改套餐信息」修改名称、价格、周期、余额和额度。
59
- - **自动查额度**:在「API Key 引用」填写 DSH「模型」页保存密钥时使用的名字,或环境变量名,点击「刷新」时会先保存当前设置,再查询额度。这里填的是引用名,不是密钥本身。没有额度接口的平台可手填,也可以留空。
59
+ - **自动查额度**:在「API Key 引用」填写 DSH「模型」页保存密钥时使用的名字,或环境变量名,点击「刷新」时会先保存当前设置,再查询额度。这里填的是引用名,不是密钥本身。没有额度接口的平台可手填,也可以留空。切换平台时,查询地址和密钥引用会随平台更新。使用自定义密钥名时,需要为新平台重新填写。
60
60
  - **查询失败**:页面会显示失败原因及尝试过的密钥来源。检查引用名、密钥权限和所选平台后再刷新。
61
61
 
62
62
  套餐预设和价格快照可能落后于服务商调整,都可以手动覆盖。套餐订阅价格不等于 API Token 花费,两者分别显示。
package/lib/client.js CHANGED
@@ -485,15 +485,16 @@ window.__ModuleLoader__.load({
485
485
  const BOOLS = ['notifyCompleted', 'notifyChoice', 'notifyInput', 'notifyApproval', 'notifyFailed', 'suppressWhenFocused', 'sound', 'tray', 'showSpendInTitle', 'planAutoQuota']
486
486
  const CHOICES = ['channel', 'titleStyle', 'spendSource', 'currency', 'priceSource', 'customPriceCurrency', 'planPeriod', 'planCurrency']
487
487
  const NUMBERS = ['errorHoldMinutes', 'balancePollMinutes', 'customInput', 'customCacheRead', 'customOutput', 'exchangeRate', 'planPrice', 'planBalance', 'quotaPollMinutes']
488
- const TEXTS = ['planProvider', 'planId', 'planName', 'planQuota', 'planRemaining', 'planResetAt', 'planApiKeyEnv', 'planQuotaUrl']
489
- const FIELDS = [...BOOLS, ...CHOICES, ...NUMBERS, ...TEXTS]
488
+ const TEXTS = ['planProvider', 'planId', 'planName', 'planQuota', 'planRemaining', 'planResetAt']
489
+ const QUOTA_FIELDS = ['planApiKeyEnv', 'planQuotaUrl']
490
+ const FIELDS = [...BOOLS, ...CHOICES, ...NUMBERS, ...TEXTS, ...QUOTA_FIELDS]
490
491
  /** The five "notify me when" switches, shown as one row of checkboxes. */
491
492
  const NOTIFY_FIELDS = ['notifyCompleted', 'notifyChoice', 'notifyInput', 'notifyApproval', 'notifyFailed']
492
493
  /** Fields behind the "Advanced" fold (counted for its "n changed" tag). */
493
494
  const ADVANCED_FIELDS = ['channel', 'suppressWhenFocused', 'showSpendInTitle', 'errorHoldMinutes', 'spendSource', 'currency', 'balancePollMinutes', 'priceSource', 'customInput', 'customCacheRead', 'customOutput', 'customPriceCurrency', 'exchangeRate', 'planAutoQuota', 'quotaPollMinutes', 'planQuotaUrl']
494
495
  const TRAY_FIELDS = ['showSpendInTitle', 'errorHoldMinutes']
495
496
  /** Plan fields a preset fills in; switching provider clears them. */
496
- const PRESET_FIELDS = ['planId', 'planName', 'planPrice', 'planCurrency', 'planPeriod', 'planQuota', 'planQuotaUrl']
497
+ const PRESET_FIELDS = ['planId', 'planName', 'planPrice', 'planCurrency', 'planPeriod', 'planQuota']
497
498
 
498
499
  // The form model clears staged edits when a save resolves. Keep edits made
499
500
  // during that request and replay them before submitting the next batch.
@@ -504,6 +505,8 @@ window.__ModuleLoader__.load({
504
505
  ...CHOICES.map(choiceField),
505
506
  ...NUMBERS.map(f => ui.settingsNumberField(f)),
506
507
  ...TEXTS.map(textField),
508
+ // An explicit blank masks a credential or endpoint inherited from the deployment.
509
+ ...QUOTA_FIELDS.map(field => ({ ...textField(field), parse: text => ({ kind: 'set', value: text.trim() }) })),
507
510
  ])
508
511
  this.actions = this.form.actions()
509
512
  this.listeners = new Set()
@@ -964,19 +967,14 @@ window.__ModuleLoader__.load({
964
967
  edit('planCurrency', next.currency)
965
968
  edit('planPeriod', next.period)
966
969
  edit('planQuota', next.quotaText ?? '')
967
- resetField('planQuotaUrl')
970
+ edit('planQuotaUrl', '')
968
971
  }
969
972
  const chooseProvider = id => {
970
973
  edit('planProvider', id)
971
974
  for (const name of PRESET_FIELDS) resetField(name)
972
- // Suggest the provider's usual key reference, unless the user typed their own name.
973
- const current = f.planApiKeyEnv.text
974
- const suggested = !current || providers.some(p => p.keyEnv === current)
975
975
  const nextProvider = providers.find(p => p.id === id)
976
- if (suggested) {
977
- if (nextProvider?.keyEnv) edit('planApiKeyEnv', nextProvider.keyEnv)
978
- else resetField('planApiKeyEnv')
979
- }
976
+ edit('planApiKeyEnv', nextProvider?.keyEnv ?? '')
977
+ edit('planQuotaUrl', '')
980
978
  }
981
979
  const providerOptions = [['none', t('providerNone')], ...providers.map(p => [p.id, p.name]), ['custom', t('providerCustom')]]
982
980
  const planOptions = [...plans.map(p => [p.id, `${p.name}${p.price ? ` · ${SYM[p.currency] ?? ''}${p.price}` : ''}`]), ['', t('planCustom')]]
@@ -29,6 +29,8 @@ export function createHost(ctx, config) {
29
29
  },
30
30
  })
31
31
  const dir = storageDir()
32
+ const ledger = new Ledger({ file: join(dir, 'ledger.json') })
33
+ ledger.load()
32
34
 
33
35
  const host = {
34
36
  ctx,
@@ -36,7 +38,7 @@ export function createHost(ctx, config) {
36
38
  dir,
37
39
  logger: ctx.logger?.('notify-tray') ?? console,
38
40
  tracker: new Tracker(),
39
- ledger: new Ledger({ file: join(dir, 'ledger.json') }),
41
+ ledger,
40
42
  account: { usageUrl: undefined },
41
43
  /** pi-ai's model catalog (prices), once loaded. */
42
44
  pi: undefined,
@@ -65,7 +67,7 @@ export function createHost(ctx, config) {
65
67
 
66
68
  /** Which endpoint the plan's quota comes from, and what identifies one reading as current. */
67
69
  host.quotaSpec = () => quotaSpecFor(cfg.planProvider, cfg.planId, cfg.planQuotaUrl)
68
- host.quotaSignature = () => `${cfg.planProvider}|${cfg.planId}|${cfg.planApiKeyEnv ?? ''}|${cfg.planQuotaUrl ?? ''}`
70
+ host.quotaSignature = () => JSON.stringify([cfg.planProvider, cfg.planId, cfg.planApiKeyEnv, cfg.planQuotaUrl])
69
71
  /** The route in use: the latest request header anywhere, else DSH's default model selection. */
70
72
  host.currentRoute = () => {
71
73
  if (host.ledger.lastRoute) return host.ledger.lastRoute
@@ -97,8 +97,10 @@ export function setupRoutes(ctx, host) {
97
97
  // a browser tab without permission must not silence the system channel.
98
98
  if (url.searchParams.get('notify') === '1') host.lastClientPoll = Date.now()
99
99
  const after = Number(url.searchParams.get('after') ?? '-1')
100
+ const lite = url.searchParams.get('lite') === '1'
101
+ const claim = url.searchParams.get('claim') === '1'
100
102
  // A window that just came forward after a toast takes that toast's session, once.
101
- if (url.searchParams.get('claim') === '1' && host.toastPending) {
103
+ if (claim && host.toastPending) {
102
104
  if (Date.now() - host.toastPending.at < TOAST_CLAIM_MS) host.focusQueue.push(host.toastPending.sessionId)
103
105
  host.toastPending = undefined
104
106
  }
@@ -114,10 +116,9 @@ export function setupRoutes(ctx, host) {
114
116
  : [],
115
117
  titles: TITLES,
116
118
  suppressWhenFocused: cfg.suppressWhenFocused,
117
- focus: host.focusQueue,
119
+ focus: lite || claim ? host.focusQueue.splice(0) : [],
118
120
  }
119
- host.focusQueue = []
120
- if (url.searchParams.get('lite') === '1') return void json(res, body)
121
+ if (lite) return void json(res, body)
121
122
  const snap = snapshot()
122
123
  const rev = revOf(snap)
123
124
  if (url.searchParams.get('rev') === rev) return void json(res, { ...body, rev, unchanged: true })
package/lib/host/spend.js CHANGED
@@ -15,11 +15,11 @@ export function setupSpend(ctx, host) {
15
15
 
16
16
  // ---- ledger persistence -------------------------------------------------
17
17
  ctx.effect(() => {
18
- ledger.load().then(host.refresh)
19
- const timer = setInterval(() => ledger.save().catch(() => {}), 30_000)
18
+ const save = () => ledger.save().catch(error => logger.warn('保存花费账本失败', error))
19
+ const timer = setInterval(save, 30_000)
20
20
  return () => {
21
21
  clearInterval(timer)
22
- ledger.save().catch(() => {})
22
+ return save()
23
23
  }
24
24
  }, 'notify-tray: ledger')
25
25
 
@@ -62,11 +62,14 @@ export function setupSpend(ctx, host) {
62
62
  const ref = (cfg.planApiKeyEnv ?? '').trim()
63
63
  const signature = host.quotaSignature()
64
64
  if (!spec || !ref || (!force && !cfg.planAutoQuota)) {
65
+ if (polling?.signature !== signature) polling = undefined
65
66
  if (host.quota !== undefined) { host.quota = undefined; host.refresh() }
66
67
  return undefined
67
68
  }
68
- if (polling) return polling
69
- polling = (async () => {
69
+ if (polling?.signature === signature) return polling.result
70
+ const request = { signature }
71
+ polling = request
72
+ request.result = (async () => {
70
73
  // The key DSH's Models page saved first, then the environment variable of the same name.
71
74
  let saved
72
75
  const reading = await runQuotaPlan([
@@ -97,12 +100,15 @@ export function setupSpend(ctx, host) {
97
100
  fetch: () => fetchQuota(spec, process.env[ref]),
98
101
  },
99
102
  ], { noneError: `没找到 API Key:${ref} 没有保存,也没有设置为环境变量` })
103
+ if (polling !== request || host.quotaSignature() !== signature) return undefined
100
104
  host.quota = { ...reading, signature, spec: { kind: spec.kind, url: spec.url } }
101
105
  debug('quota', host.quota)
102
106
  host.refresh()
103
107
  return host.quota
104
- })().finally(() => { polling = undefined })
105
- return polling
108
+ })().finally(() => {
109
+ if (polling === request) polling = undefined
110
+ })
111
+ return request.result
106
112
  }
107
113
  ctx.effect(() => {
108
114
  let timer
@@ -130,16 +136,33 @@ export function setupSpend(ctx, host) {
130
136
  locale: 'zh-CN',
131
137
  timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60,
132
138
  }
139
+ let disposed = false
140
+ let pollingBalance = false
141
+ let pollAgain = false
142
+ let idleTimer
133
143
  const poll = async () => {
144
+ if (disposed) return
145
+ if (pollingBalance) {
146
+ pollAgain = true
147
+ return
148
+ }
149
+ pollingBalance = true
134
150
  try {
135
151
  const balance = await ctx.deepseekAccount.getBalance(client)
152
+ if (disposed) return
136
153
  if (balance?.status === 'ready') ledger.balance(balance.value)
137
154
  if (host.account.usageUrl === undefined) {
138
155
  const state = await ctx.deepseekAccount.getState?.()
139
- host.account.usageUrl = state?.links?.usageUrl
156
+ if (!disposed) host.account.usageUrl = state?.links?.usageUrl
140
157
  }
141
158
  } catch (error) {
142
159
  logger.debug?.('读取账户余额失败', error)
160
+ } finally {
161
+ pollingBalance = false
162
+ if (pollAgain && !disposed) {
163
+ pollAgain = false
164
+ poll()
165
+ }
143
166
  }
144
167
  }
145
168
  ctx.effect(() => {
@@ -149,11 +172,19 @@ export function setupSpend(ctx, host) {
149
172
  timer = setTimeout(loop, Math.max(1, cfg.balancePollMinutes) * 60_000)
150
173
  }
151
174
  loop()
152
- return () => clearTimeout(timer)
175
+ return () => {
176
+ disposed = true
177
+ clearTimeout(timer)
178
+ clearTimeout(idleTimer)
179
+ }
153
180
  }, 'notify-tray: balance poll')
154
181
  // A finished turn is when spend lands; refresh shortly after.
155
182
  ctx.on('agent/status', ({ status }) => {
156
- if (status === 'idle') setTimeout(poll, 5000)
183
+ if (status !== 'idle' || idleTimer || disposed) return
184
+ idleTimer = setTimeout(() => {
185
+ idleTimer = undefined
186
+ poll()
187
+ }, 5000)
157
188
  })
158
189
  })
159
190
  }
package/lib/ledger.js CHANGED
@@ -12,7 +12,8 @@
12
12
  * - balance: polled DeepSeek account balance; the day's spend is the sum of
13
13
  * balance drops, so a top-up never reads as negative spend.
14
14
  */
15
- import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
15
+ import { readFileSync } from 'node:fs'
16
+ import { mkdir, rename, writeFile } from 'node:fs/promises'
16
17
  import { dirname } from 'node:path'
17
18
  import { isDeepseekOffPeak, providerForRoute } from './catalog.js'
18
19
  import { localDate } from './tracker.js'
@@ -98,7 +99,9 @@ export class Ledger {
98
99
  this.routes = new Map()
99
100
  /** The route the most recent request header anywhere announced: "the current model". */
100
101
  this.lastRoute = undefined
101
- this.dirty = false
102
+ this.revision = 0
103
+ this.savedRevision = 0
104
+ this.writing = Promise.resolve()
102
105
  this.listeners = new Set()
103
106
  }
104
107
 
@@ -108,7 +111,7 @@ export class Ledger {
108
111
  }
109
112
 
110
113
  changed() {
111
- this.dirty = true
114
+ this.revision += 1
112
115
  for (const listener of this.listeners) listener()
113
116
  }
114
117
 
@@ -125,26 +128,34 @@ export class Ledger {
125
128
  return day
126
129
  }
127
130
 
128
- async load() {
131
+ // Read once at startup, before any session or balance callbacks can run.
132
+ load() {
129
133
  if (!this.file) return
130
134
  try {
131
- const parsed = JSON.parse(await readFile(this.file, 'utf8'))
132
- if (parsed && typeof parsed.days === 'object') this.days = parsed.days
135
+ const parsed = JSON.parse(readFileSync(this.file, 'utf8'))
136
+ if (parsed?.days && typeof parsed.days === 'object' && !Array.isArray(parsed.days)) this.days = parsed.days
133
137
  if (typeof parsed?.lastRoute === 'object' && parsed.lastRoute?.model) this.lastRoute = parsed.lastRoute
134
138
  } catch {
135
139
  // first run or unreadable file: start fresh
136
140
  }
137
141
  }
138
142
 
139
- async save() {
140
- if (!this.file || !this.dirty) return
141
- this.dirty = false
142
- const dates = Object.keys(this.days).sort()
143
- for (const date of dates.slice(0, Math.max(0, dates.length - KEEP_DAYS))) delete this.days[date]
144
- await mkdir(dirname(this.file), { recursive: true })
145
- const tmp = `${this.file}.tmp`
146
- await writeFile(tmp, JSON.stringify({ version: 1, days: this.days, lastRoute: this.lastRoute }))
147
- await rename(tmp, this.file)
143
+ save() {
144
+ const write = async () => {
145
+ const revision = this.revision
146
+ if (!this.file || this.savedRevision === revision) return
147
+ const dates = Object.keys(this.days).sort()
148
+ for (const date of dates.slice(0, Math.max(0, dates.length - KEEP_DAYS))) delete this.days[date]
149
+ const snapshot = JSON.stringify({ version: 1, days: this.days, lastRoute: this.lastRoute })
150
+ await mkdir(dirname(this.file), { recursive: true })
151
+ const tmp = `${this.file}.tmp`
152
+ await writeFile(tmp, snapshot)
153
+ await rename(tmp, this.file)
154
+ this.savedRevision = revision
155
+ }
156
+ // The periodic flush and the last flush at unload share one writer, including after a failure.
157
+ this.writing = this.writing.then(write, write)
158
+ return this.writing
148
159
  }
149
160
 
150
161
  sessionEvent(session, event) {
package/lib/notices.js CHANGED
@@ -61,7 +61,11 @@ export class Notices {
61
61
 
62
62
  /** Feed one tracker event (already filtered by the user's per-type switches). */
63
63
  push(event) {
64
- if (event.type !== 'completed' || this.windowMs <= 0) return void this.show(event)
64
+ if (event.type !== 'completed') {
65
+ if (this.burst) this.burst.extra = this.burst.extra.filter(older => older.sessionId !== event.sessionId)
66
+ return void this.show(event)
67
+ }
68
+ if (this.windowMs <= 0) return void this.show(event)
65
69
  if (this.burst) {
66
70
  this.burst.extra.push(event)
67
71
  return
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-notify-tray",
3
- "version": "0.1.8",
3
+ "version": "0.1.9",
4
4
  "description": "DeepSeek Harness 通知 + 状态栏插件:任务完成、需要输入、需要选择时弹系统通知(macOS / Windows / Linux);macOS 与 Linux(含 UOS、Deepin、麒麟)状态栏常驻小图标,显示任务进度与花费。Windows 没有状态栏,只弹通知。",
5
5
  "keywords": [
6
6
  "deepseek",
@@ -24,7 +24,10 @@
24
24
  },
25
25
  "files": [
26
26
  "lib",
27
- "assets",
27
+ "assets/mascot-peeking.png",
28
+ "assets/mascot-peeking.prompt.txt",
29
+ "assets/preview.svg",
30
+ "assets/tray-darwin.js",
28
31
  "locale",
29
32
  "icon.webp",
30
33
  "cordis.patch.yml",