dsh-notify-tray 0.1.7 → 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.
@@ -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
@@ -9,6 +9,7 @@
9
9
  * snapshot again.
10
10
  */
11
11
  import { createHash } from 'node:crypto'
12
+ import { readFileSync } from 'node:fs'
12
13
  import { publicCatalog } from '../catalog.js'
13
14
  import { spendOf, TITLES } from '../format.js'
14
15
  import { desktopHosted } from '../system.js'
@@ -19,6 +20,7 @@ const CATALOG_PATH = '/notify-tray/catalog'
19
20
  const REFRESH_PATH = '/notify-tray/refresh'
20
21
  const TRAY_PATH = '/notify-tray/tray'
21
22
  const RAISE_PATH = '/notify-tray/raise'
23
+ const MASCOT_PATH = '/notify-tray/mascot'
22
24
  /**
23
25
  * A clicked Windows toast can only launch `dsh://open` (or the web GUI), so no
24
26
  * session travels with it: a window that comes forward within this long after
@@ -56,6 +58,19 @@ export function setupRoutes(ctx, host) {
56
58
  res.setHeader('cache-control', 'no-store')
57
59
  res.end(JSON.stringify(body))
58
60
  }
61
+ // The peeking sprite includes the neck, shoulders and hands.
62
+ const mascot = readFileSync(new URL('../../assets/mascot-peeking.png', import.meta.url))
63
+ ctx.effect(() => ctx.webServer.register({
64
+ kind: 'exact',
65
+ path: MASCOT_PATH,
66
+ handler: (req, res) => {
67
+ if (!guard(req, res, 'GET')) return
68
+ res.statusCode = 200
69
+ res.setHeader('content-type', 'image/png')
70
+ res.setHeader('cache-control', 'private, max-age=3600')
71
+ res.end(mascot)
72
+ },
73
+ }), `notify-tray: GET ${MASCOT_PATH}`)
59
74
  /** Everything the settings page shows; only computed when a page asks. */
60
75
  const snapshot = () => {
61
76
  const currentUsage = host.usage()
@@ -82,8 +97,10 @@ export function setupRoutes(ctx, host) {
82
97
  // a browser tab without permission must not silence the system channel.
83
98
  if (url.searchParams.get('notify') === '1') host.lastClientPoll = Date.now()
84
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'
85
102
  // A window that just came forward after a toast takes that toast's session, once.
86
- if (url.searchParams.get('claim') === '1' && host.toastPending) {
103
+ if (claim && host.toastPending) {
87
104
  if (Date.now() - host.toastPending.at < TOAST_CLAIM_MS) host.focusQueue.push(host.toastPending.sessionId)
88
105
  host.toastPending = undefined
89
106
  }
@@ -99,10 +116,9 @@ export function setupRoutes(ctx, host) {
99
116
  : [],
100
117
  titles: TITLES,
101
118
  suppressWhenFocused: cfg.suppressWhenFocused,
102
- focus: host.focusQueue,
119
+ focus: lite || claim ? host.focusQueue.splice(0) : [],
103
120
  }
104
- host.focusQueue = []
105
- if (url.searchParams.get('lite') === '1') return void json(res, body)
121
+ if (lite) return void json(res, body)
106
122
  const snap = snapshot()
107
123
  const rev = revOf(snap)
108
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/locale/en.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "Whale Notify Station",
4
- "description": "(Click to open the detailed settings) A plump blue whale girl: when a task finishes, needs a choice, or waits for your words, she blows bubbles and pops a notification — and keeps today's spend in mind for you. On macOS / Linux she also lives in your status bar; Windows has no status bar, so there she only notifies."
4
+ "description": "Notifications when tasks finish, fail, or need your attention, with daily spend and plan quota. Open Whale Notify Station in the left sidebar to configure it; this page contains the user guide. The status-bar whale is available on macOS / Linux; Windows supports notifications only.",
5
+ "detail": "README.md"
5
6
  }
6
7
  }
package/locale/zh.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "小鲸鱼通知站",
4
- "description": "(点击可进行详细设置)一只蓝色的大肥鲸鱼娘:任务做完、要你选一个、等你写几个字的时候,她会冒着泡泡弹通知来找你~ 顺便帮你记着今天花了多少钱。macOS / Linux 上她还会常驻状态栏;Windows 没有状态栏,只弹通知。"
4
+ "description": "任务完成、失败或需要你处理时弹通知,查看今日花费与套餐额度。点击左侧栏「小鲸鱼通知站」进行设置;此页为使用说明。macOS / Linux 支持状态栏小鲸鱼,Windows 仅提供通知。",
5
+ "detail": "README.md"
5
6
  }
6
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-notify-tray",
3
- "version": "0.1.7",
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,12 +24,16 @@
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",
31
34
  "README.md",
32
- "README.zh-CN.md"
35
+ "README.zh-CN.md",
36
+ "README.en.md"
33
37
  ],
34
38
  "license": "MIT",
35
39
  "author": "ROYLeXJ",
@@ -50,7 +54,7 @@
50
54
  },
51
55
  "scripts": {
52
56
  "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",
57
+ "version": "node scripts/sync-readme-version.mjs && git add README.md README.zh-CN.md README.en.md",
54
58
  "update-prices": "node scripts/update-models-dev.mjs"
55
59
  },
56
60
  "dsh": {
@@ -65,7 +69,9 @@
65
69
  "@deepseek-ai/dsh-client-ui-workspace",
66
70
  "@deepseek-ai/dsh-client-locale",
67
71
  "@deepseek-ai/dsh-client-ui-settings",
68
- "@deepseek-ai/dsh-client-ui-plugin-manager"
72
+ "@deepseek-ai/dsh-client-ui-layout",
73
+ "@deepseek-ai/dsh-client-ui-sidebar",
74
+ "@deepseek-ai/dsh-api-remotes"
69
75
  ]
70
76
  }
71
77
  },
@@ -73,8 +79,8 @@
73
79
  "dbus-next": "^0.10.2"
74
80
  },
75
81
  "peerDependencies": {
76
- "@deepseek-ai/cordis": "~4.0.5",
77
- "@deepseek-ai/schemastery": "~3.18.5"
82
+ "@deepseek-ai/cordis": "~4.0.5 || ~4.1.0",
83
+ "@deepseek-ai/schemastery": "~3.18.5 || ~3.19.0"
78
84
  },
79
85
  "devDependencies": {
80
86
  "@deepseek-ai/schemastery": "~3.18.5"