dsh-notify-tray 0.1.11 → 0.1.13

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
@@ -1,284 +1,284 @@
1
- /**
2
- * Turn tracker + ledger summaries into the tray view model every platform
3
- * helper consumes: the menu-bar text, a tooltip, the icon state, and menu
4
- * rows (with optional SF Symbol names and nested children).
5
- *
6
- * The whale itself carries the state (idle / spouting / "!" / "×"); the
7
- * menu-bar text only ever says what needs you, never money.
8
- */
9
-
10
- /** Notification titles per event type (shared by the host, the window and the demo). */
11
- export const TITLES = {
12
- completed: '✅ 任务完成',
13
- failed: '❌ 任务失败',
14
- approval: '🔐 需要你批准',
15
- choice: '🔘 需要你选择',
16
- input: '✏️ 需要你输入',
17
- }
18
-
19
- const SYMBOL = { CNY: '¥', USD: '$' }
20
- /** Where an estimate's price came from (mirrors pricing.js, kept here so this file stays DSH-free). */
21
- const SOURCE_LABEL = { table: '价格表', custom: '自定义价', catalog: '目录价', static: '内置价', modelsDev: 'models.dev 价' }
22
- const KIND_LABEL = {
23
- approval: '待批准',
24
- choice: '待选择',
25
- input: '待输入',
26
- completed: '完成',
27
- failed: '失败',
28
- aborted: '已停止',
29
- }
30
- const KIND_ICON = {
31
- approval: 'lock.shield',
32
- choice: 'questionmark.circle',
33
- input: 'pencil.line',
34
- completed: 'checkmark.circle',
35
- failed: 'xmark.circle',
36
- aborted: 'stop.circle',
37
- }
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
- }
66
-
67
- export function money(value, currency) {
68
- if (value === undefined || value === null) return undefined
69
- const symbol = SYMBOL[currency] ?? `${currency} `
70
- return `${symbol}${value < 10 ? value.toFixed(2) : value.toFixed(1)}`
71
- }
72
-
73
- export function compactTokens(n) {
74
- if (n >= 1e8) return `${(n / 1e8).toFixed(1)}亿`
75
- if (n >= 1e4) return `${(n / 1e4).toFixed(1)}万`
76
- return String(n)
77
- }
78
-
79
- /** "刚开始" / "3 分钟" / "1 小时 20 分". */
80
- export function elapsed(since, now) {
81
- if (since === undefined) return ''
82
- const minutes = Math.floor((now - since) / 60_000)
83
- if (minutes < 1) return '刚开始'
84
- if (minutes < 60) return `${minutes} 分钟`
85
- return `${Math.floor(minutes / 60)} 小时 ${minutes % 60} 分`
86
- }
87
-
88
- function clock(time) {
89
- const d = new Date(time)
90
- return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
91
- }
92
-
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('估算') ? '估算' : '余额扣费')
98
-
99
- /** A reset time: ISO strings become a clock, anything the user typed stays as typed. */
100
- function resetText(value) {
101
- const ms = Date.parse(value)
102
- if (!Number.isFinite(ms) || !/\d{4}-\d{2}-\d{2}T/u.test(value)) return value
103
- const d = new Date(ms)
104
- const sameDay = d.toDateString() === new Date().toDateString()
105
- return `${sameDay ? '' : `${d.getMonth() + 1}/${d.getDate()} `}${clock(ms)}`
106
- }
107
-
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
- */
118
- export function spendOf(usage, source) {
119
- const hasBalance = usage.balanceSpend !== undefined || usage.balance !== undefined
120
- const fromBalance = hasBalance ? { value: usage.balanceSpend ?? 0, label: '余额扣费' } : undefined
121
- const sources = (usage.estimateSources ?? []).map(key => SOURCE_LABEL[key] ?? key)
122
- const estimateLabel = sources.length ? `估算 · ${sources.join('+')}` : '估算'
123
- const fromEstimate = usage.estimate !== undefined ? { value: usage.estimate, label: estimateLabel } : undefined
124
- if (source === 'balance') return fromBalance
125
- if (source === 'estimate') return 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 }
135
- }
136
-
137
- const round4 = value => Math.round(value * 10000) / 10000
138
-
139
- /** How long the whale celebrates after a finish before going back to idle. */
140
- export const DONE_HOLD_MS = 6000
141
-
142
- /** 'attention' | 'error' | 'running' | 'done' | 'idle' — picks the whale's animation. */
143
- export function stateOf(tasks, now, errorWindowMs, doneWindowMs = DONE_HOLD_MS) {
144
- if (tasks.waiting.length > 0) return 'attention'
145
- const lastFailed = tasks.recent.find(item => item.kind === 'failed')
146
- if (lastFailed && now - lastFailed.at < errorWindowMs && tasks.recent[0] === lastFailed) return 'error'
147
- if (tasks.running > 0) return 'running'
148
- const latest = tasks.recent[0]
149
- if (latest && latest.kind === 'completed' && now - latest.at < doneWindowMs) return 'done'
150
- return 'idle'
151
- }
152
-
153
- /** Menu-bar text next to the whale. */
154
- export function titleOf(tasks, config, spendText) {
155
- const style = config.titleStyle ?? 'text'
156
- const parts = []
157
- if (style !== 'icon') {
158
- if (tasks.waiting.length > 0) parts.push(style === 'count' ? String(tasks.waiting.length) : `待处理 ${tasks.waiting.length}`)
159
- else if (tasks.running > 0) parts.push(style === 'count' ? String(tasks.running) : `运行中 ${tasks.running}`)
160
- }
161
- if (config.showSpendInTitle === true && spendText) parts.push(spendText)
162
- return parts.join(' · ')
163
- }
164
-
165
- export function buildView(tasks, usage, config, now = Date.now(), plan = undefined) {
166
- const state = stateOf(tasks, now, (config.errorHoldMinutes ?? 10) * 60_000)
167
- const spend = spendOf(usage, config.spendSource)
168
- const spendText = spend ? money(spend.value, usage.currency) : undefined
169
- const title = titleOf(tasks, config, spendText)
170
- const today = tasks.today
171
-
172
- // ---- headline: what the whale is up to -----------------------------------
173
- let headline
174
- let headIcon
175
- if (tasks.waiting.length > 0) {
176
- const others = tasks.runningList.filter(item => !tasks.waiting.some(wait => wait.sessionId === item.sessionId)).length
177
- headline = `${tasks.waiting.length} 件事等你${others > 0 ? ` · ${others} 个在跑` : ''}`
178
- headIcon = 'bell.badge'
179
- } else if (tasks.running > 0) {
180
- headline = `正在运行 ${tasks.running} 个任务`
181
- headIcon = 'bolt.horizontal.circle'
182
- } else if (state === 'error') {
183
- headline = '刚才有任务失败了'
184
- headIcon = 'exclamationmark.triangle'
185
- } else if (state === 'done') {
186
- headline = '搞定啦~ 刚完成一个任务'
187
- headIcon = 'sparkles'
188
- } else {
189
- headline = today.completed + today.failed > 0 ? `空闲 · 今天完成 ${today.completed} 个` : '空闲,等你派活'
190
- headIcon = 'moon.zzz'
191
- }
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.
196
- const menu = []
197
- menu.push({ id: 'headline', label: headline, icon: headIcon, enabled: false })
198
-
199
- // ---- the tasks themselves --------------------------------------------------
200
- const taskRows = []
201
- for (const wait of tasks.waiting) {
202
- const detail = wait.text ? `:${wait.text}` : ''
203
- taskRows.push({ id: `open:${wait.sessionId}`, icon: KIND_ICON[wait.kind], label: trim(`${KIND_LABEL[wait.kind]} · ${wait.title}${detail}`) })
204
- }
205
- for (const item of tasks.runningList) {
206
- if (tasks.waiting.some(wait => wait.sessionId === item.sessionId)) continue
207
- const age = elapsed(item.since, now)
208
- taskRows.push({ id: `open:${item.sessionId}`, icon: 'play.circle', label: trim([item.title, age].filter(Boolean).join(' · ')) })
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} 个…` })
212
- menu.push({ separator: true })
213
-
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) })
227
- }
228
- const todayBits = ['今日']
229
- if (spendText) todayBits.push(spendText)
230
- menu.push({ id: 'today', icon: 'chart.bar', label: `${todayBits.join(' ')} · 完成 ${today.completed}`, children: todayRows })
231
-
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)}` })
235
- if (plan) {
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 })
254
- }
255
-
256
- if (tasks.recent.length > 0) {
257
- const rows = tasks.recent.slice(0, SUB_ROWS).map(item => ({
258
- id: `open:${item.sessionId}`,
259
- icon: KIND_ICON[item.kind],
260
- label: trim(`${clock(item.at)} ${KIND_LABEL[item.kind]} · ${item.title}`, SUB_MAX),
261
- }))
262
- menu.push({ id: 'recent', icon: 'clock.arrow.circlepath', label: '最近结束', children: rows })
263
- }
264
- menu.push({ separator: true })
265
- menu.push({ id: 'show-app', icon: 'macwindow', label: '打开 DeepSeek Harness' })
266
- menu.push({ id: 'hide-tray', icon: 'eye.slash', label: '隐藏状态栏图标' })
267
-
268
- // ---- tooltip (Windows / Linux hover) ------------------------------------------
269
- const lines = [headline]
270
- lines.push(`今日 完成 ${today.completed} · 失败 ${today.failed}`)
271
- if (spend) lines.push(`今日花费 ${spendText}(${spend.label})`)
272
- if (usage.balance !== undefined) lines.push(`账户余额 ${money(usage.balance, usage.currency)}`)
273
- if (plan) {
274
- const bits = [plan.name, plan.priceText, plan.remaining !== undefined ? `剩余 ${plan.remaining}` : undefined, plan.balance !== undefined ? `余额 ${money(plan.balance, plan.balanceCurrency)}` : undefined].filter(Boolean)
275
- lines.push(`套餐 ${bits.join(' · ')}`)
276
- }
277
- const tooltip = ['DeepSeek Harness', ...lines].join('\n')
278
-
279
- // Single glyph drawn into the Windows/Linux icon badge.
280
- const badge = tasks.waiting.length > 0 ? String(Math.min(tasks.waiting.length, 9))
281
- : tasks.running > 0 ? String(Math.min(tasks.running, 9)) : ''
282
-
283
- return { state, title, tooltip, menu, badge, headline }
284
- }
1
+ /**
2
+ * Turn tracker + ledger summaries into the tray view model every platform
3
+ * helper consumes: the menu-bar text, a tooltip, the icon state, and menu
4
+ * rows (with optional SF Symbol names and nested children).
5
+ *
6
+ * The whale itself carries the state (idle / spouting / "!" / "×"); the
7
+ * menu-bar text only ever says what needs you, never money.
8
+ */
9
+
10
+ /** Notification titles per event type (shared by the host, the window and the demo). */
11
+ export const TITLES = {
12
+ completed: '✅ 任务完成',
13
+ failed: '❌ 任务失败',
14
+ approval: '🔐 需要你批准',
15
+ choice: '🔘 需要你选择',
16
+ input: '✏️ 需要你输入',
17
+ }
18
+
19
+ const SYMBOL = { CNY: '¥', USD: '$' }
20
+ /** Where an estimate's price came from (mirrors pricing.js, kept here so this file stays DSH-free). */
21
+ const SOURCE_LABEL = { table: '价格表', custom: '自定义价', catalog: '目录价', static: '内置价', modelsDev: 'models.dev 价' }
22
+ const KIND_LABEL = {
23
+ approval: '待批准',
24
+ choice: '待选择',
25
+ input: '待输入',
26
+ completed: '完成',
27
+ failed: '失败',
28
+ aborted: '已停止',
29
+ }
30
+ const KIND_ICON = {
31
+ approval: 'lock.shield',
32
+ choice: 'questionmark.circle',
33
+ input: 'pencil.line',
34
+ completed: 'checkmark.circle',
35
+ failed: 'xmark.circle',
36
+ aborted: 'stop.circle',
37
+ }
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
+ }
66
+
67
+ export function money(value, currency) {
68
+ if (value === undefined || value === null) return undefined
69
+ const symbol = SYMBOL[currency] ?? `${currency} `
70
+ return `${symbol}${value < 10 ? value.toFixed(2) : value.toFixed(1)}`
71
+ }
72
+
73
+ export function compactTokens(n) {
74
+ if (n >= 1e8) return `${(n / 1e8).toFixed(1)}亿`
75
+ if (n >= 1e4) return `${(n / 1e4).toFixed(1)}万`
76
+ return String(n)
77
+ }
78
+
79
+ /** "刚开始" / "3 分钟" / "1 小时 20 分". */
80
+ export function elapsed(since, now) {
81
+ if (since === undefined) return ''
82
+ const minutes = Math.floor((now - since) / 60_000)
83
+ if (minutes < 1) return '刚开始'
84
+ if (minutes < 60) return `${minutes} 分钟`
85
+ return `${Math.floor(minutes / 60)} 小时 ${minutes % 60} 分`
86
+ }
87
+
88
+ function clock(time) {
89
+ const d = new Date(time)
90
+ return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
91
+ }
92
+
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('估算') ? '估算' : '余额扣费')
98
+
99
+ /** A reset time: ISO strings become a clock, anything the user typed stays as typed. */
100
+ function resetText(value) {
101
+ const ms = Date.parse(value)
102
+ if (!Number.isFinite(ms) || !/\d{4}-\d{2}-\d{2}T/u.test(value)) return value
103
+ const d = new Date(ms)
104
+ const sameDay = d.toDateString() === new Date().toDateString()
105
+ return `${sameDay ? '' : `${d.getMonth() + 1}/${d.getDate()} `}${clock(ms)}`
106
+ }
107
+
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
+ */
118
+ export function spendOf(usage, source) {
119
+ const hasBalance = usage.balanceSpend !== undefined || usage.balance !== undefined
120
+ const fromBalance = hasBalance ? { value: usage.balanceSpend ?? 0, label: '余额扣费' } : undefined
121
+ const sources = (usage.estimateSources ?? []).map(key => SOURCE_LABEL[key] ?? key)
122
+ const estimateLabel = sources.length ? `估算 · ${sources.join('+')}` : '估算'
123
+ const fromEstimate = usage.estimate !== undefined ? { value: usage.estimate, label: estimateLabel } : undefined
124
+ if (source === 'balance') return fromBalance
125
+ if (source === 'estimate') return 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 }
135
+ }
136
+
137
+ const round4 = value => Math.round(value * 10000) / 10000
138
+
139
+ /** How long the whale celebrates after a finish before going back to idle. */
140
+ export const DONE_HOLD_MS = 6000
141
+
142
+ /** 'attention' | 'error' | 'running' | 'done' | 'idle' — picks the whale's animation. */
143
+ export function stateOf(tasks, now, errorWindowMs, doneWindowMs = DONE_HOLD_MS) {
144
+ if (tasks.waiting.length > 0) return 'attention'
145
+ const lastFailed = tasks.recent.find(item => item.kind === 'failed')
146
+ if (lastFailed && now - lastFailed.at < errorWindowMs && tasks.recent[0] === lastFailed) return 'error'
147
+ if (tasks.running > 0) return 'running'
148
+ const latest = tasks.recent[0]
149
+ if (latest && latest.kind === 'completed' && now - latest.at < doneWindowMs) return 'done'
150
+ return 'idle'
151
+ }
152
+
153
+ /** Menu-bar text next to the whale. */
154
+ export function titleOf(tasks, config, spendText) {
155
+ const style = config.titleStyle ?? 'text'
156
+ const parts = []
157
+ if (style !== 'icon') {
158
+ if (tasks.waiting.length > 0) parts.push(style === 'count' ? String(tasks.waiting.length) : `待处理 ${tasks.waiting.length}`)
159
+ else if (tasks.running > 0) parts.push(style === 'count' ? String(tasks.running) : `运行中 ${tasks.running}`)
160
+ }
161
+ if (config.showSpendInTitle === true && spendText) parts.push(spendText)
162
+ return parts.join(' · ')
163
+ }
164
+
165
+ export function buildView(tasks, usage, config, now = Date.now(), plan = undefined) {
166
+ const state = stateOf(tasks, now, (config.errorHoldMinutes ?? 10) * 60_000)
167
+ const spend = spendOf(usage, config.spendSource)
168
+ const spendText = spend ? money(spend.value, usage.currency) : undefined
169
+ const title = titleOf(tasks, config, spendText)
170
+ const today = tasks.today
171
+
172
+ // ---- headline: what the whale is up to -----------------------------------
173
+ let headline
174
+ let headIcon
175
+ if (tasks.waiting.length > 0) {
176
+ const others = tasks.runningList.filter(item => !tasks.waiting.some(wait => wait.sessionId === item.sessionId)).length
177
+ headline = `${tasks.waiting.length} 件事等你${others > 0 ? ` · ${others} 个在跑` : ''}`
178
+ headIcon = 'bell.badge'
179
+ } else if (tasks.running > 0) {
180
+ headline = `正在运行 ${tasks.running} 个任务`
181
+ headIcon = 'bolt.horizontal.circle'
182
+ } else if (state === 'error') {
183
+ headline = '刚才有任务失败了'
184
+ headIcon = 'exclamationmark.triangle'
185
+ } else if (state === 'done') {
186
+ headline = '搞定啦~ 刚完成一个任务'
187
+ headIcon = 'sparkles'
188
+ } else {
189
+ headline = today.completed + today.failed > 0 ? `空闲 · 今天完成 ${today.completed} 个` : '空闲,等你派活'
190
+ headIcon = 'moon.zzz'
191
+ }
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.
196
+ const menu = []
197
+ menu.push({ id: 'headline', label: headline, icon: headIcon, enabled: false })
198
+
199
+ // ---- the tasks themselves --------------------------------------------------
200
+ const taskRows = []
201
+ for (const wait of tasks.waiting) {
202
+ const detail = wait.text ? `:${wait.text}` : ''
203
+ taskRows.push({ id: `open:${wait.sessionId}`, icon: KIND_ICON[wait.kind], label: trim(`${KIND_LABEL[wait.kind]} · ${wait.title}${detail}`) })
204
+ }
205
+ for (const item of tasks.runningList) {
206
+ if (tasks.waiting.some(wait => wait.sessionId === item.sessionId)) continue
207
+ const age = elapsed(item.since, now)
208
+ taskRows.push({ id: `open:${item.sessionId}`, icon: 'play.circle', label: trim([item.title, age].filter(Boolean).join(' · ')) })
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} 个…` })
212
+ menu.push({ separator: true })
213
+
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) })
227
+ }
228
+ const todayBits = ['今日']
229
+ if (spendText) todayBits.push(spendText)
230
+ menu.push({ id: 'today', icon: 'chart.bar', label: `${todayBits.join(' ')} · 完成 ${today.completed}`, children: todayRows })
231
+
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)}` })
235
+ if (plan) {
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 })
254
+ }
255
+
256
+ if (tasks.recent.length > 0) {
257
+ const rows = tasks.recent.slice(0, SUB_ROWS).map(item => ({
258
+ id: `open:${item.sessionId}`,
259
+ icon: KIND_ICON[item.kind],
260
+ label: trim(`${clock(item.at)} ${KIND_LABEL[item.kind]} · ${item.title}`, SUB_MAX),
261
+ }))
262
+ menu.push({ id: 'recent', icon: 'clock.arrow.circlepath', label: '最近结束', children: rows })
263
+ }
264
+ menu.push({ separator: true })
265
+ menu.push({ id: 'show-app', icon: 'macwindow', label: '打开 DeepSeek Harness' })
266
+ menu.push({ id: 'hide-tray', icon: 'eye.slash', label: '隐藏状态栏图标' })
267
+
268
+ // ---- tooltip (Windows / Linux hover) ------------------------------------------
269
+ const lines = [headline]
270
+ lines.push(`今日 完成 ${today.completed} · 失败 ${today.failed}`)
271
+ if (spend) lines.push(`今日花费 ${spendText}(${spend.label})`)
272
+ if (usage.balance !== undefined) lines.push(`账户余额 ${money(usage.balance, usage.currency)}`)
273
+ if (plan) {
274
+ const bits = [plan.name, plan.priceText, plan.remaining !== undefined ? `剩余 ${plan.remaining}` : undefined, plan.balance !== undefined ? `余额 ${money(plan.balance, plan.balanceCurrency)}` : undefined].filter(Boolean)
275
+ lines.push(`套餐 ${bits.join(' · ')}`)
276
+ }
277
+ const tooltip = ['DeepSeek Harness', ...lines].join('\n')
278
+
279
+ // Single glyph drawn into the Windows/Linux icon badge.
280
+ const badge = tasks.waiting.length > 0 ? String(Math.min(tasks.waiting.length, 9))
281
+ : tasks.running > 0 ? String(Math.min(tasks.running, 9)) : ''
282
+
283
+ return { state, title, tooltip, menu, badge, headline }
284
+ }
@@ -48,13 +48,21 @@ export function createHost(ctx, config) {
48
48
  webOrigin: () => undefined,
49
49
  /** Identifies this host run, so clients reset their cursor after a restart. */
50
50
  boot: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
51
- lastClientPoll: 0,
51
+
52
52
  /** Session ids a tray click asked the window to open, consumed by the next poll. */
53
53
  focusQueue: [],
54
- /** The session the latest Windows toast announced: { sessionId, at }. */
55
- toastPending: undefined,
56
54
  }
57
55
 
56
+ // Short-lived presence only suppresses alerts. It never selects a session.
57
+ const windows = new Map()
58
+ host.reportView = (windowId, sessionId) => {
59
+ const now = Date.now()
60
+ for (const [id, view] of windows) if (now - view.at >= 6000) windows.delete(id)
61
+ if (sessionId) windows.set(windowId, { sessionId, at: now })
62
+ else windows.delete(windowId)
63
+ }
64
+ host.isViewing = id => [...windows.values()].some(view => view.sessionId === id && Date.now() - view.at < 6000)
65
+
58
66
  /** Set DSH_NOTIFY_TRAY_DEBUG=1 to trace tracked events into storages/dsh-notify-tray/debug.log. */
59
67
  host.debug = process.env.DSH_NOTIFY_TRAY_DEBUG
60
68
  ? (...parts) => {