dsh-notify-tray 0.1.12 → 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/tray/linux.js CHANGED
@@ -1,393 +1,393 @@
1
- /**
2
- * Linux tray + notifications over the D-Bus session bus, in-process via the
3
- * pure-JS `dbus-next` client: no compiled helper, so it runs on every CPU the
4
- * distro runs on (x86_64, ARM64 Kunpeng/Phytium, LoongArch, MIPS).
5
- *
6
- * Tray: StatusNotifierItem (org.kde.StatusNotifierItem) + com.canonical.dbusmenu,
7
- * the protocol shared by KDE, DDE (UOS / Deepin), UKUI (Kylin), GNOME with the
8
- * AppIndicator extension, XFCE and LXQt.
9
- * Notifications: org.freedesktop.Notifications, with click-to-open actions.
10
- */
11
- import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
12
- import { createRequire } from 'node:module'
13
- import { join } from 'node:path'
14
- import { pngIcon, renderIcon, rgbaIcon } from '../icon.js'
15
- import { iconSpec } from '../whale.js'
16
-
17
- const require = createRequire(import.meta.url)
18
-
19
- const ITEM_PATH = '/StatusNotifierItem'
20
- const MENU_PATH = '/MenuBar'
21
- const ICON_SIZES = [22, 32, 48]
22
- /** Give up on a session bus that does not answer Hello within this long. */
23
- const CONNECT_TIMEOUT_MS = 10_000
24
- /** Per-state frame count and timing (fps / loop) from lib/whale.js. */
25
- const ANIM = iconSpec().anim
26
- const FRAME_COUNT = Object.fromEntries(Object.entries(iconSpec().frames).map(([state, frames]) => [state, frames.length]))
27
-
28
- /**
29
- * Where the session bus lives. `DBUS_SESSION_BUS_ADDRESS` is what every
30
- * desktop session exports; without it, systemd's per-user bus at
31
- * `$XDG_RUNTIME_DIR/bus` is the next best guess (dbus-next would instead go
32
- * looking for dbus-launch's `~/.dbus/session-bus/` files and throw).
33
- *
34
- * `unix:abstract=` addresses (dbus-launch sessions, still common on older
35
- * X11 desktops) need the optional native `usocket` module in dbus-next, which
36
- * is not installed; Node's own `net` dials abstract sockets when the path
37
- * starts with a NUL byte, so rewrite them to `unix:path=\0…`.
38
- */
39
- export function sessionBusAddress(env = process.env) {
40
- const address = env.DBUS_SESSION_BUS_ADDRESS?.trim()
41
- if (address) {
42
- return address.split(';').map(entry => entry.replace(/^unix:abstract=([^,]+)/u, (_, name) => `unix:path=\0${name}`)).join(';')
43
- }
44
- const runtime = env.XDG_RUNTIME_DIR?.trim()
45
- if (runtime && existsSync(join(runtime, 'bus'))) return `unix:path=${join(runtime, 'bus')}`
46
- throw new Error('没有 D-Bus 会话总线(不在图形桌面会话里?)')
47
- }
48
-
49
- let shared
50
- /**
51
- * Lazily open one session-bus connection for tray and notifications. Resolves
52
- * once the bus has answered Hello; dbus-next never settles pending calls on a
53
- * dead socket, so a refused or hung connection is turned into a rejection here.
54
- */
55
- async function connect() {
56
- if (shared) {
57
- await shared.ready
58
- return shared
59
- }
60
- const dbus = require('dbus-next')
61
- const bus = dbus.sessionBus({ busAddress: sessionBusAddress() })
62
- const ready = new Promise((resolve, reject) => {
63
- const timer = setTimeout(() => reject(new Error(`连接 D-Bus 会话总线超时(${CONNECT_TIMEOUT_MS / 1000} 秒)`)), CONNECT_TIMEOUT_MS)
64
- timer.unref?.()
65
- bus.once('connect', () => { clearTimeout(timer); resolve() })
66
- bus.once('error', error => { clearTimeout(timer); reject(error) })
67
- })
68
- shared = { dbus, bus, ready }
69
- // A dropped connection (bus restart) is forgotten, so the next notification reconnects.
70
- bus.on('error', () => { if (shared?.bus === bus) shared = undefined })
71
- try {
72
- await ready
73
- } catch (error) {
74
- if (shared?.bus === bus) shared = undefined
75
- try { bus.disconnect() } catch {}
76
- throw error
77
- }
78
- return shared
79
- }
80
-
81
- const pixmapCache = new Map()
82
- /** Pixmaps for one state + frame, rendered once and reused. */
83
- function pixmaps(state, frame = 0) {
84
- const key = `${state}:${frame}`
85
- let cached = pixmapCache.get(key)
86
- if (cached === undefined) {
87
- cached = ICON_SIZES.map(size => [size, size, renderIcon(size, state, frame)])
88
- pixmapCache.set(key, cached)
89
- }
90
- return cached
91
- }
92
-
93
- /**
94
- * dbusmenu wants integer ids; rows (and their `children`) get them in a
95
- * depth-first walk so submenus work on every panel that implements the protocol.
96
- */
97
- function flattenMenu(rows) {
98
- const byId = new Map()
99
- const walk = (list, parentId) => {
100
- const ids = []
101
- for (const row of list) {
102
- const id = byId.size + 1
103
- byId.set(id, { row, parentId, childIds: [] })
104
- ids.push(id)
105
- if (row.children?.length) byId.get(id).childIds = walk(row.children, id)
106
- }
107
- return ids
108
- }
109
- const rootIds = walk(rows, 0)
110
- return { byId, rootIds }
111
- }
112
-
113
- export async function startLinuxTray({ onAction, logger }) {
114
- const { dbus, bus } = await connect()
115
- const { Interface, ACCESS_READ } = dbus.interface
116
- const Variant = dbus.Variant
117
- let view = { state: 'idle', title: 'DSH', tooltip: 'DeepSeek Harness', menu: [], badge: '' }
118
- let layout = flattenMenu([])
119
- let frame = 0
120
- let frameTimer
121
- let revision = 1
122
-
123
- class Item extends Interface {
124
- get Category() { return 'ApplicationStatus' }
125
- get Id() { return 'dsh-notify-tray' }
126
- get Title() { return 'DeepSeek Harness' }
127
- get Status() { return view.state === 'attention' ? 'NeedsAttention' : 'Active' }
128
- get WindowId() { return 0 }
129
- get IconName() { return '' }
130
- get IconPixmap() { return pixmaps(view.state, frame) }
131
- get AttentionIconName() { return '' }
132
- get AttentionIconPixmap() { return pixmaps(view.state, frame) }
133
- get OverlayIconName() { return '' }
134
- get OverlayIconPixmap() { return [] }
135
- get ToolTip() {
136
- const [head, ...rest] = view.tooltip.split('\n')
137
- return ['', pixmaps(view.state, 0), head, rest.join('\n')]
138
- }
139
- get ItemIsMenu() { return false }
140
- get Menu() { return MENU_PATH }
141
- Activate() { onAction('show-app') }
142
- SecondaryActivate() { onAction('show-app') }
143
- ContextMenu() {}
144
- Scroll() {}
145
- NewIcon() {}
146
- NewAttentionIcon() {}
147
- NewToolTip() {}
148
- NewTitle() {}
149
- NewStatus(status) { return status }
150
- }
151
- const ro = signature => ({ signature, access: ACCESS_READ })
152
- Item.configureMembers({
153
- properties: {
154
- Category: ro('s'), Id: ro('s'), Title: ro('s'), Status: ro('s'), WindowId: ro('i'),
155
- IconName: ro('s'), IconPixmap: ro('a(iiay)'), AttentionIconName: ro('s'),
156
- AttentionIconPixmap: ro('a(iiay)'), OverlayIconName: ro('s'), OverlayIconPixmap: ro('a(iiay)'),
157
- ToolTip: ro('(sa(iiay)ss)'), ItemIsMenu: ro('b'), Menu: ro('o'),
158
- },
159
- methods: {
160
- Activate: { inSignature: 'ii' },
161
- SecondaryActivate: { inSignature: 'ii' },
162
- ContextMenu: { inSignature: 'ii' },
163
- Scroll: { inSignature: 'is' },
164
- },
165
- signals: {
166
- NewIcon: { signature: '' },
167
- NewAttentionIcon: { signature: '' },
168
- NewToolTip: { signature: '' },
169
- NewTitle: { signature: '' },
170
- NewStatus: { signature: 's' },
171
- },
172
- })
173
-
174
- // dbusmenu: item 0 is the root; every row (nested ones too) has an id from flattenMenu.
175
- const props = (entry) => {
176
- if (entry === undefined) return { 'children-display': new Variant('s', 'submenu') }
177
- const { row, childIds } = entry
178
- if (row.separator) return { type: new Variant('s', 'separator') }
179
- const out = {
180
- label: new Variant('s', row.label.replace(/_/gu, '__')),
181
- enabled: new Variant('b', row.enabled !== false || childIds.length > 0),
182
- visible: new Variant('b', true),
183
- }
184
- if (childIds.length > 0) out['children-display'] = new Variant('s', 'submenu')
185
- return out
186
- }
187
- const node = (id, depth) => {
188
- const entry = layout.byId.get(id)
189
- const children = depth === 0 ? [] : entry.childIds.map(child => new Variant('(ia{sv}av)', node(child, depth - 1)))
190
- return [id, props(entry), children]
191
- }
192
-
193
- class Menu extends Interface {
194
- get Version() { return 3 }
195
- get TextDirection() { return 'ltr' }
196
- get Status() { return 'normal' }
197
- get IconThemePath() { return [] }
198
- GetLayout(parentId, recursionDepth) {
199
- const depth = recursionDepth < 0 ? 99 : recursionDepth
200
- if (parentId !== 0) {
201
- return [revision, layout.byId.has(parentId) ? node(parentId, depth) : [parentId, {}, []]]
202
- }
203
- const children = depth === 0 ? [] : layout.rootIds.map(id => new Variant('(ia{sv}av)', node(id, depth - 1)))
204
- return [revision, [0, props(undefined), children]]
205
- }
206
- GetGroupProperties(ids) {
207
- return ids.map(id => [id, id === 0 ? props(undefined) : props(layout.byId.get(id) ?? { row: {}, childIds: [] })])
208
- }
209
- GetProperty(id, name) {
210
- const all = id === 0 ? props(undefined) : props(layout.byId.get(id) ?? { row: {}, childIds: [] })
211
- return all[name] ?? new Variant('s', '')
212
- }
213
- Event(id, eventId) {
214
- if (eventId !== 'clicked') return
215
- const row = layout.byId.get(id)?.row
216
- if (row && !row.separator && row.enabled !== false && !row.children?.length) onAction(row.id)
217
- }
218
- EventGroup(events) {
219
- for (const [id, eventId] of events) this.Event(id, eventId)
220
- return []
221
- }
222
- AboutToShow() { return false }
223
- AboutToShowGroup() { return [[], []] }
224
- LayoutUpdated(rev, parent) { return [rev, parent] }
225
- ItemsPropertiesUpdated() { return [[], []] }
226
- }
227
- Menu.configureMembers({
228
- properties: { Version: ro('u'), TextDirection: ro('s'), Status: ro('s'), IconThemePath: ro('as') },
229
- methods: {
230
- GetLayout: { inSignature: 'iias', outSignature: 'u(ia{sv}av)' },
231
- GetGroupProperties: { inSignature: 'aias', outSignature: 'a(ia{sv})' },
232
- GetProperty: { inSignature: 'is', outSignature: 'v' },
233
- Event: { inSignature: 'isvu' },
234
- EventGroup: { inSignature: 'a(isvu)', outSignature: 'ai' },
235
- AboutToShow: { inSignature: 'i', outSignature: 'b' },
236
- AboutToShowGroup: { inSignature: 'ai', outSignature: 'aiai' },
237
- },
238
- signals: {
239
- LayoutUpdated: { signature: 'ui' },
240
- ItemsPropertiesUpdated: { signature: 'a(ia{sv})a(ias)' },
241
- },
242
- })
243
-
244
- const item = new Item('org.kde.StatusNotifierItem')
245
- const menu = new Menu('com.canonical.dbusmenu')
246
- const name = `org.kde.StatusNotifierItem-${process.pid}-1`
247
- bus.export(ITEM_PATH, item)
248
- bus.export(MENU_PATH, menu)
249
- await bus.requestName(name, 0)
250
-
251
- const register = async () => {
252
- const watcher = await bus.getProxyObject('org.kde.StatusNotifierWatcher', '/StatusNotifierWatcher')
253
- await watcher.getInterface('org.kde.StatusNotifierWatcher').RegisterStatusNotifierItem(name)
254
- }
255
- try {
256
- await register()
257
- } catch (error) {
258
- logger?.warn?.('没有找到状态栏宿主(StatusNotifierWatcher),等待桌面环境提供', error?.message ?? error)
259
- }
260
- // Re-register when a tray host (re)appears, e.g. after the panel restarts.
261
- try {
262
- const dbusObj = await bus.getProxyObject('org.freedesktop.DBus', '/org/freedesktop/DBus')
263
- dbusObj.getInterface('org.freedesktop.DBus').on('NameOwnerChanged', (owner, _old, now) => {
264
- if (owner === 'org.kde.StatusNotifierWatcher' && now) register().catch(() => {})
265
- })
266
- } catch {}
267
-
268
- const animate = () => {
269
- clearInterval(frameTimer)
270
- frameTimer = undefined
271
- frame = 0
272
- const frames = FRAME_COUNT[view.state] ?? 1
273
- const { fps = 1, loop = false } = ANIM[view.state] ?? {}
274
- if (frames < 2) return
275
- frameTimer = setInterval(() => {
276
- if (!loop && frame >= frames - 1) { clearInterval(frameTimer); frameTimer = undefined; return }
277
- frame = loop ? (frame + 1) % frames : frame + 1
278
- item.NewIcon()
279
- }, Math.round(1000 / Math.max(1, fps)))
280
- frameTimer.unref?.()
281
- }
282
-
283
- return {
284
- update(next) {
285
- const statusChanged = next.state !== view.state
286
- view = next
287
- layout = flattenMenu(view.menu ?? [])
288
- revision += 1
289
- if (statusChanged) animate()
290
- item.NewIcon()
291
- item.NewToolTip()
292
- if (statusChanged) item.NewStatus(item.Status)
293
- menu.LayoutUpdated(revision, 0)
294
- },
295
- async stop() {
296
- clearInterval(frameTimer)
297
- try {
298
- bus.unexport(ITEM_PATH, item)
299
- bus.unexport(MENU_PATH, menu)
300
- await bus.releaseName(name)
301
- } catch {}
302
- },
303
- }
304
- }
305
-
306
- const notifyActions = new Map()
307
- /** The id of the notification currently shown for each key (session), so the next one replaces it. */
308
- const notifyIds = new Map()
309
- /** Edge of the whale drawn into notifications. */
310
- const NOTIFY_ICON_SIZE = 64
311
-
312
- const notifyIcons = new Map()
313
- /**
314
- * The whale for a notification: inline pixels for the `image-data` hint (spec
315
- * 1.2; older servers read `image_data` / `icon_data`) and, when `iconDir` is
316
- * writable, a PNG path for `app_icon`, which servers that ignore image hints
317
- * (and history panes) show instead of a generic icon.
318
- */
319
- export function notifyIcon(state = 'idle', iconDir) {
320
- const key = `${state}|${iconDir ?? ''}`
321
- let icon = notifyIcons.get(key)
322
- if (icon === undefined) {
323
- const size = NOTIFY_ICON_SIZE
324
- icon = { size, rgba: rgbaIcon(size, state), path: '' }
325
- if (iconDir) {
326
- try {
327
- mkdirSync(iconDir, { recursive: true })
328
- const file = join(iconDir, `whale-${state}.png`)
329
- writeFileSync(file, pngIcon(size, state))
330
- icon.path = file
331
- } catch {}
332
- }
333
- notifyIcons.set(key, icon)
334
- }
335
- return icon
336
- }
337
-
338
- async function notifications() {
339
- const link = await connect()
340
- if (!link.notifications) {
341
- const obj = await link.bus.getProxyObject('org.freedesktop.Notifications', '/org/freedesktop/Notifications')
342
- const iface = obj.getInterface('org.freedesktop.Notifications')
343
- // One listener per connection: a reconnected bus gets a fresh proxy.
344
- iface.on('ActionInvoked', (id, key) => {
345
- if (key === 'default') notifyActions.get(id)?.()
346
- })
347
- iface.on('NotificationClosed', id => {
348
- notifyActions.delete(id)
349
- for (const [key, shown] of notifyIds) if (shown === id) notifyIds.delete(key)
350
- })
351
- link.notifications = iface
352
- }
353
- return { dbus: link.dbus, iface: link.notifications }
354
- }
355
-
356
- /**
357
- * Show one freedesktop notification; `onClick` runs when its default action
358
- * is invoked. A `key` (the session) replaces that key's previous notification
359
- * in place (`replaces_id`), so a session never stacks up several.
360
- */
361
- export async function linuxNotify({ title, body, sound = true, onClick, state = 'idle', iconDir, key }) {
362
- const { dbus, iface } = await notifications()
363
- const icon = notifyIcon(state, iconDir)
364
- const image = new dbus.Variant('(iiibiiay)', [icon.size, icon.size, icon.size * 4, true, 8, 4, icon.rgba])
365
- const hints = {
366
- urgency: new dbus.Variant('y', 1),
367
- 'desktop-entry': new dbus.Variant('s', 'deepseek-harness'),
368
- 'image-data': image,
369
- image_data: image,
370
- icon_data: image,
371
- }
372
- // freedesktop sound-naming spec; servers that play sounds honour these hints.
373
- if (sound) hints['sound-name'] = new dbus.Variant('s', 'message-new-instant')
374
- else hints['suppress-sound'] = new dbus.Variant('b', true)
375
- const replaces = key !== undefined ? (notifyIds.get(key) ?? 0) : 0
376
- const id = await iface.Notify('DeepSeek Harness', replaces, icon.path, title, body, ['default', '打开'], hints, -1)
377
- if (replaces && replaces !== id) notifyActions.delete(replaces)
378
- if (onClick) notifyActions.set(id, onClick)
379
- if (key !== undefined) notifyIds.set(key, id)
380
- return id
381
- }
382
-
383
- /** Take back the notification shown for `key`, if it is still up. Resolves to whether one was closed. */
384
- export async function linuxWithdraw(key) {
385
- const id = notifyIds.get(key)
386
- if (id === undefined) return false
387
- notifyIds.delete(key)
388
- notifyActions.delete(id)
389
- const { iface } = await notifications()
390
- // Already gone (dismissed by the user): the server answers with an error, which is fine.
391
- try { await iface.CloseNotification(id) } catch { return false }
392
- return true
393
- }
1
+ /**
2
+ * Linux tray + notifications over the D-Bus session bus, in-process via the
3
+ * pure-JS `dbus-next` client: no compiled helper, so it runs on every CPU the
4
+ * distro runs on (x86_64, ARM64 Kunpeng/Phytium, LoongArch, MIPS).
5
+ *
6
+ * Tray: StatusNotifierItem (org.kde.StatusNotifierItem) + com.canonical.dbusmenu,
7
+ * the protocol shared by KDE, DDE (UOS / Deepin), UKUI (Kylin), GNOME with the
8
+ * AppIndicator extension, XFCE and LXQt.
9
+ * Notifications: org.freedesktop.Notifications, with click-to-open actions.
10
+ */
11
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
12
+ import { createRequire } from 'node:module'
13
+ import { join } from 'node:path'
14
+ import { pngIcon, renderIcon, rgbaIcon } from '../icon.js'
15
+ import { iconSpec } from '../whale.js'
16
+
17
+ const require = createRequire(import.meta.url)
18
+
19
+ const ITEM_PATH = '/StatusNotifierItem'
20
+ const MENU_PATH = '/MenuBar'
21
+ const ICON_SIZES = [22, 32, 48]
22
+ /** Give up on a session bus that does not answer Hello within this long. */
23
+ const CONNECT_TIMEOUT_MS = 10_000
24
+ /** Per-state frame count and timing (fps / loop) from lib/whale.js. */
25
+ const ANIM = iconSpec().anim
26
+ const FRAME_COUNT = Object.fromEntries(Object.entries(iconSpec().frames).map(([state, frames]) => [state, frames.length]))
27
+
28
+ /**
29
+ * Where the session bus lives. `DBUS_SESSION_BUS_ADDRESS` is what every
30
+ * desktop session exports; without it, systemd's per-user bus at
31
+ * `$XDG_RUNTIME_DIR/bus` is the next best guess (dbus-next would instead go
32
+ * looking for dbus-launch's `~/.dbus/session-bus/` files and throw).
33
+ *
34
+ * `unix:abstract=` addresses (dbus-launch sessions, still common on older
35
+ * X11 desktops) need the optional native `usocket` module in dbus-next, which
36
+ * is not installed; Node's own `net` dials abstract sockets when the path
37
+ * starts with a NUL byte, so rewrite them to `unix:path=\0…`.
38
+ */
39
+ export function sessionBusAddress(env = process.env) {
40
+ const address = env.DBUS_SESSION_BUS_ADDRESS?.trim()
41
+ if (address) {
42
+ return address.split(';').map(entry => entry.replace(/^unix:abstract=([^,]+)/u, (_, name) => `unix:path=\0${name}`)).join(';')
43
+ }
44
+ const runtime = env.XDG_RUNTIME_DIR?.trim()
45
+ if (runtime && existsSync(join(runtime, 'bus'))) return `unix:path=${join(runtime, 'bus')}`
46
+ throw new Error('没有 D-Bus 会话总线(不在图形桌面会话里?)')
47
+ }
48
+
49
+ let shared
50
+ /**
51
+ * Lazily open one session-bus connection for tray and notifications. Resolves
52
+ * once the bus has answered Hello; dbus-next never settles pending calls on a
53
+ * dead socket, so a refused or hung connection is turned into a rejection here.
54
+ */
55
+ async function connect() {
56
+ if (shared) {
57
+ await shared.ready
58
+ return shared
59
+ }
60
+ const dbus = require('dbus-next')
61
+ const bus = dbus.sessionBus({ busAddress: sessionBusAddress() })
62
+ const ready = new Promise((resolve, reject) => {
63
+ const timer = setTimeout(() => reject(new Error(`连接 D-Bus 会话总线超时(${CONNECT_TIMEOUT_MS / 1000} 秒)`)), CONNECT_TIMEOUT_MS)
64
+ timer.unref?.()
65
+ bus.once('connect', () => { clearTimeout(timer); resolve() })
66
+ bus.once('error', error => { clearTimeout(timer); reject(error) })
67
+ })
68
+ shared = { dbus, bus, ready }
69
+ // A dropped connection (bus restart) is forgotten, so the next notification reconnects.
70
+ bus.on('error', () => { if (shared?.bus === bus) shared = undefined })
71
+ try {
72
+ await ready
73
+ } catch (error) {
74
+ if (shared?.bus === bus) shared = undefined
75
+ try { bus.disconnect() } catch {}
76
+ throw error
77
+ }
78
+ return shared
79
+ }
80
+
81
+ const pixmapCache = new Map()
82
+ /** Pixmaps for one state + frame, rendered once and reused. */
83
+ function pixmaps(state, frame = 0) {
84
+ const key = `${state}:${frame}`
85
+ let cached = pixmapCache.get(key)
86
+ if (cached === undefined) {
87
+ cached = ICON_SIZES.map(size => [size, size, renderIcon(size, state, frame)])
88
+ pixmapCache.set(key, cached)
89
+ }
90
+ return cached
91
+ }
92
+
93
+ /**
94
+ * dbusmenu wants integer ids; rows (and their `children`) get them in a
95
+ * depth-first walk so submenus work on every panel that implements the protocol.
96
+ */
97
+ function flattenMenu(rows) {
98
+ const byId = new Map()
99
+ const walk = (list, parentId) => {
100
+ const ids = []
101
+ for (const row of list) {
102
+ const id = byId.size + 1
103
+ byId.set(id, { row, parentId, childIds: [] })
104
+ ids.push(id)
105
+ if (row.children?.length) byId.get(id).childIds = walk(row.children, id)
106
+ }
107
+ return ids
108
+ }
109
+ const rootIds = walk(rows, 0)
110
+ return { byId, rootIds }
111
+ }
112
+
113
+ export async function startLinuxTray({ onAction, logger }) {
114
+ const { dbus, bus } = await connect()
115
+ const { Interface, ACCESS_READ } = dbus.interface
116
+ const Variant = dbus.Variant
117
+ let view = { state: 'idle', title: 'DSH', tooltip: 'DeepSeek Harness', menu: [], badge: '' }
118
+ let layout = flattenMenu([])
119
+ let frame = 0
120
+ let frameTimer
121
+ let revision = 1
122
+
123
+ class Item extends Interface {
124
+ get Category() { return 'ApplicationStatus' }
125
+ get Id() { return 'dsh-notify-tray' }
126
+ get Title() { return 'DeepSeek Harness' }
127
+ get Status() { return view.state === 'attention' ? 'NeedsAttention' : 'Active' }
128
+ get WindowId() { return 0 }
129
+ get IconName() { return '' }
130
+ get IconPixmap() { return pixmaps(view.state, frame) }
131
+ get AttentionIconName() { return '' }
132
+ get AttentionIconPixmap() { return pixmaps(view.state, frame) }
133
+ get OverlayIconName() { return '' }
134
+ get OverlayIconPixmap() { return [] }
135
+ get ToolTip() {
136
+ const [head, ...rest] = view.tooltip.split('\n')
137
+ return ['', pixmaps(view.state, 0), head, rest.join('\n')]
138
+ }
139
+ get ItemIsMenu() { return false }
140
+ get Menu() { return MENU_PATH }
141
+ Activate() { onAction('show-app') }
142
+ SecondaryActivate() { onAction('show-app') }
143
+ ContextMenu() {}
144
+ Scroll() {}
145
+ NewIcon() {}
146
+ NewAttentionIcon() {}
147
+ NewToolTip() {}
148
+ NewTitle() {}
149
+ NewStatus(status) { return status }
150
+ }
151
+ const ro = signature => ({ signature, access: ACCESS_READ })
152
+ Item.configureMembers({
153
+ properties: {
154
+ Category: ro('s'), Id: ro('s'), Title: ro('s'), Status: ro('s'), WindowId: ro('i'),
155
+ IconName: ro('s'), IconPixmap: ro('a(iiay)'), AttentionIconName: ro('s'),
156
+ AttentionIconPixmap: ro('a(iiay)'), OverlayIconName: ro('s'), OverlayIconPixmap: ro('a(iiay)'),
157
+ ToolTip: ro('(sa(iiay)ss)'), ItemIsMenu: ro('b'), Menu: ro('o'),
158
+ },
159
+ methods: {
160
+ Activate: { inSignature: 'ii' },
161
+ SecondaryActivate: { inSignature: 'ii' },
162
+ ContextMenu: { inSignature: 'ii' },
163
+ Scroll: { inSignature: 'is' },
164
+ },
165
+ signals: {
166
+ NewIcon: { signature: '' },
167
+ NewAttentionIcon: { signature: '' },
168
+ NewToolTip: { signature: '' },
169
+ NewTitle: { signature: '' },
170
+ NewStatus: { signature: 's' },
171
+ },
172
+ })
173
+
174
+ // dbusmenu: item 0 is the root; every row (nested ones too) has an id from flattenMenu.
175
+ const props = (entry) => {
176
+ if (entry === undefined) return { 'children-display': new Variant('s', 'submenu') }
177
+ const { row, childIds } = entry
178
+ if (row.separator) return { type: new Variant('s', 'separator') }
179
+ const out = {
180
+ label: new Variant('s', row.label.replace(/_/gu, '__')),
181
+ enabled: new Variant('b', row.enabled !== false || childIds.length > 0),
182
+ visible: new Variant('b', true),
183
+ }
184
+ if (childIds.length > 0) out['children-display'] = new Variant('s', 'submenu')
185
+ return out
186
+ }
187
+ const node = (id, depth) => {
188
+ const entry = layout.byId.get(id)
189
+ const children = depth === 0 ? [] : entry.childIds.map(child => new Variant('(ia{sv}av)', node(child, depth - 1)))
190
+ return [id, props(entry), children]
191
+ }
192
+
193
+ class Menu extends Interface {
194
+ get Version() { return 3 }
195
+ get TextDirection() { return 'ltr' }
196
+ get Status() { return 'normal' }
197
+ get IconThemePath() { return [] }
198
+ GetLayout(parentId, recursionDepth) {
199
+ const depth = recursionDepth < 0 ? 99 : recursionDepth
200
+ if (parentId !== 0) {
201
+ return [revision, layout.byId.has(parentId) ? node(parentId, depth) : [parentId, {}, []]]
202
+ }
203
+ const children = depth === 0 ? [] : layout.rootIds.map(id => new Variant('(ia{sv}av)', node(id, depth - 1)))
204
+ return [revision, [0, props(undefined), children]]
205
+ }
206
+ GetGroupProperties(ids) {
207
+ return ids.map(id => [id, id === 0 ? props(undefined) : props(layout.byId.get(id) ?? { row: {}, childIds: [] })])
208
+ }
209
+ GetProperty(id, name) {
210
+ const all = id === 0 ? props(undefined) : props(layout.byId.get(id) ?? { row: {}, childIds: [] })
211
+ return all[name] ?? new Variant('s', '')
212
+ }
213
+ Event(id, eventId) {
214
+ if (eventId !== 'clicked') return
215
+ const row = layout.byId.get(id)?.row
216
+ if (row && !row.separator && row.enabled !== false && !row.children?.length) onAction(row.id)
217
+ }
218
+ EventGroup(events) {
219
+ for (const [id, eventId] of events) this.Event(id, eventId)
220
+ return []
221
+ }
222
+ AboutToShow() { return false }
223
+ AboutToShowGroup() { return [[], []] }
224
+ LayoutUpdated(rev, parent) { return [rev, parent] }
225
+ ItemsPropertiesUpdated() { return [[], []] }
226
+ }
227
+ Menu.configureMembers({
228
+ properties: { Version: ro('u'), TextDirection: ro('s'), Status: ro('s'), IconThemePath: ro('as') },
229
+ methods: {
230
+ GetLayout: { inSignature: 'iias', outSignature: 'u(ia{sv}av)' },
231
+ GetGroupProperties: { inSignature: 'aias', outSignature: 'a(ia{sv})' },
232
+ GetProperty: { inSignature: 'is', outSignature: 'v' },
233
+ Event: { inSignature: 'isvu' },
234
+ EventGroup: { inSignature: 'a(isvu)', outSignature: 'ai' },
235
+ AboutToShow: { inSignature: 'i', outSignature: 'b' },
236
+ AboutToShowGroup: { inSignature: 'ai', outSignature: 'aiai' },
237
+ },
238
+ signals: {
239
+ LayoutUpdated: { signature: 'ui' },
240
+ ItemsPropertiesUpdated: { signature: 'a(ia{sv})a(ias)' },
241
+ },
242
+ })
243
+
244
+ const item = new Item('org.kde.StatusNotifierItem')
245
+ const menu = new Menu('com.canonical.dbusmenu')
246
+ const name = `org.kde.StatusNotifierItem-${process.pid}-1`
247
+ bus.export(ITEM_PATH, item)
248
+ bus.export(MENU_PATH, menu)
249
+ await bus.requestName(name, 0)
250
+
251
+ const register = async () => {
252
+ const watcher = await bus.getProxyObject('org.kde.StatusNotifierWatcher', '/StatusNotifierWatcher')
253
+ await watcher.getInterface('org.kde.StatusNotifierWatcher').RegisterStatusNotifierItem(name)
254
+ }
255
+ try {
256
+ await register()
257
+ } catch (error) {
258
+ logger?.warn?.('没有找到状态栏宿主(StatusNotifierWatcher),等待桌面环境提供', error?.message ?? error)
259
+ }
260
+ // Re-register when a tray host (re)appears, e.g. after the panel restarts.
261
+ try {
262
+ const dbusObj = await bus.getProxyObject('org.freedesktop.DBus', '/org/freedesktop/DBus')
263
+ dbusObj.getInterface('org.freedesktop.DBus').on('NameOwnerChanged', (owner, _old, now) => {
264
+ if (owner === 'org.kde.StatusNotifierWatcher' && now) register().catch(() => {})
265
+ })
266
+ } catch {}
267
+
268
+ const animate = () => {
269
+ clearInterval(frameTimer)
270
+ frameTimer = undefined
271
+ frame = 0
272
+ const frames = FRAME_COUNT[view.state] ?? 1
273
+ const { fps = 1, loop = false } = ANIM[view.state] ?? {}
274
+ if (frames < 2) return
275
+ frameTimer = setInterval(() => {
276
+ if (!loop && frame >= frames - 1) { clearInterval(frameTimer); frameTimer = undefined; return }
277
+ frame = loop ? (frame + 1) % frames : frame + 1
278
+ item.NewIcon()
279
+ }, Math.round(1000 / Math.max(1, fps)))
280
+ frameTimer.unref?.()
281
+ }
282
+
283
+ return {
284
+ update(next) {
285
+ const statusChanged = next.state !== view.state
286
+ view = next
287
+ layout = flattenMenu(view.menu ?? [])
288
+ revision += 1
289
+ if (statusChanged) animate()
290
+ item.NewIcon()
291
+ item.NewToolTip()
292
+ if (statusChanged) item.NewStatus(item.Status)
293
+ menu.LayoutUpdated(revision, 0)
294
+ },
295
+ async stop() {
296
+ clearInterval(frameTimer)
297
+ try {
298
+ bus.unexport(ITEM_PATH, item)
299
+ bus.unexport(MENU_PATH, menu)
300
+ await bus.releaseName(name)
301
+ } catch {}
302
+ },
303
+ }
304
+ }
305
+
306
+ const notifyActions = new Map()
307
+ /** The id of the notification currently shown for each key (session), so the next one replaces it. */
308
+ const notifyIds = new Map()
309
+ /** Edge of the whale drawn into notifications. */
310
+ const NOTIFY_ICON_SIZE = 64
311
+
312
+ const notifyIcons = new Map()
313
+ /**
314
+ * The whale for a notification: inline pixels for the `image-data` hint (spec
315
+ * 1.2; older servers read `image_data` / `icon_data`) and, when `iconDir` is
316
+ * writable, a PNG path for `app_icon`, which servers that ignore image hints
317
+ * (and history panes) show instead of a generic icon.
318
+ */
319
+ export function notifyIcon(state = 'idle', iconDir) {
320
+ const key = `${state}|${iconDir ?? ''}`
321
+ let icon = notifyIcons.get(key)
322
+ if (icon === undefined) {
323
+ const size = NOTIFY_ICON_SIZE
324
+ icon = { size, rgba: rgbaIcon(size, state), path: '' }
325
+ if (iconDir) {
326
+ try {
327
+ mkdirSync(iconDir, { recursive: true })
328
+ const file = join(iconDir, `whale-${state}.png`)
329
+ writeFileSync(file, pngIcon(size, state))
330
+ icon.path = file
331
+ } catch {}
332
+ }
333
+ notifyIcons.set(key, icon)
334
+ }
335
+ return icon
336
+ }
337
+
338
+ async function notifications() {
339
+ const link = await connect()
340
+ if (!link.notifications) {
341
+ const obj = await link.bus.getProxyObject('org.freedesktop.Notifications', '/org/freedesktop/Notifications')
342
+ const iface = obj.getInterface('org.freedesktop.Notifications')
343
+ // One listener per connection: a reconnected bus gets a fresh proxy.
344
+ iface.on('ActionInvoked', (id, key) => {
345
+ if (key === 'default') notifyActions.get(id)?.()
346
+ })
347
+ iface.on('NotificationClosed', id => {
348
+ notifyActions.delete(id)
349
+ for (const [key, shown] of notifyIds) if (shown === id) notifyIds.delete(key)
350
+ })
351
+ link.notifications = iface
352
+ }
353
+ return { dbus: link.dbus, iface: link.notifications }
354
+ }
355
+
356
+ /**
357
+ * Show one freedesktop notification; `onClick` runs when its default action
358
+ * is invoked. A `key` (the session) replaces that key's previous notification
359
+ * in place (`replaces_id`), so a session never stacks up several.
360
+ */
361
+ export async function linuxNotify({ title, body, sound = true, onClick, state = 'idle', iconDir, key }) {
362
+ const { dbus, iface } = await notifications()
363
+ const icon = notifyIcon(state, iconDir)
364
+ const image = new dbus.Variant('(iiibiiay)', [icon.size, icon.size, icon.size * 4, true, 8, 4, icon.rgba])
365
+ const hints = {
366
+ urgency: new dbus.Variant('y', 1),
367
+ 'desktop-entry': new dbus.Variant('s', 'deepseek-harness'),
368
+ 'image-data': image,
369
+ image_data: image,
370
+ icon_data: image,
371
+ }
372
+ // freedesktop sound-naming spec; servers that play sounds honour these hints.
373
+ if (sound) hints['sound-name'] = new dbus.Variant('s', 'message-new-instant')
374
+ else hints['suppress-sound'] = new dbus.Variant('b', true)
375
+ const replaces = key !== undefined ? (notifyIds.get(key) ?? 0) : 0
376
+ const id = await iface.Notify('DeepSeek Harness', replaces, icon.path, title, body, ['default', '打开'], hints, -1)
377
+ if (replaces && replaces !== id) notifyActions.delete(replaces)
378
+ if (onClick) notifyActions.set(id, onClick)
379
+ if (key !== undefined) notifyIds.set(key, id)
380
+ return id
381
+ }
382
+
383
+ /** Take back the notification shown for `key`, if it is still up. Resolves to whether one was closed. */
384
+ export async function linuxWithdraw(key) {
385
+ const id = notifyIds.get(key)
386
+ if (id === undefined) return false
387
+ notifyIds.delete(key)
388
+ notifyActions.delete(id)
389
+ const { iface } = await notifications()
390
+ // Already gone (dismissed by the user): the server answers with an error, which is fine.
391
+ try { await iface.CloseNotification(id) } catch { return false }
392
+ return true
393
+ }