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/tray/index.js CHANGED
@@ -1,142 +1,142 @@
1
- /**
2
- * Tray front door: starts the right per-platform helper and feeds it views.
3
- *
4
- * - macOS: `osascript -l JavaScript assets/tray-darwin.js` (NSStatusItem)
5
- * - Linux: in-process StatusNotifierItem over D-Bus (lib/tray/linux.js)
6
- * - Windows: none. Windows has no status bar of this kind (and the desktop
7
- * app keeps a tray icon of its own); lib/index.js never asks.
8
- *
9
- * The macOS helper reads the whale geometry from icon.json once, then an
10
- * atomically rewritten view.json for state, and reports menu clicks as JSON
11
- * lines on stdout. It also watches the host pid, so a crashed host never
12
- * leaves an orphan icon behind. `{"quit": true}` in the view asks it to take
13
- * its icon down and exit on its own.
14
- */
15
- import { spawn } from 'node:child_process'
16
- import { mkdir, rename, writeFile } from 'node:fs/promises'
17
- import { dirname, join } from 'node:path'
18
- import { fileURLToPath } from 'node:url'
19
- import { createInterface } from 'node:readline'
20
-
21
- const ASSETS = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'assets')
22
- /** Give up restarting a helper that keeps dying this many times in a row. */
23
- const MAX_RESTARTS = 5
24
- /** How long a helper gets to exit on its own after `quit` before it is killed. */
25
- const QUIT_GRACE_MS = 1500
26
-
27
- function helperCommand(viewFile) {
28
- const pid = String(process.pid)
29
- if (process.platform === 'darwin') {
30
- return ['/usr/bin/osascript', ['-l', 'JavaScript', join(ASSETS, 'tray-darwin.js'), viewFile, pid]]
31
- }
32
- return undefined
33
- }
34
-
35
- const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
36
-
37
- /**
38
- * Replace `file` with `tmp`, retrying the transient EPERM/EBUSY a rename can
39
- * hit while the helper has the file open for its (sub-millisecond) read.
40
- */
41
- async function replaceFile(tmp, file) {
42
- for (let attempt = 0; ; attempt += 1) {
43
- try {
44
- await rename(tmp, file)
45
- return
46
- } catch (error) {
47
- if (attempt >= 5 || !['EPERM', 'EBUSY', 'EACCES'].includes(error?.code)) throw error
48
- await sleep(20 * (attempt + 1))
49
- }
50
- }
51
- }
52
-
53
- /**
54
- * @param {object} options
55
- * @param {string} options.stateDir - directory for view.json / icon.json.
56
- * @param {object} [options.icon] - lib/whale.js iconSpec(), written to icon.json.
57
- * @param {(action: string) => void} options.onAction - menu click handler.
58
- * @param {object} [options.logger]
59
- */
60
- export async function startTray({ stateDir, icon, onAction, logger }) {
61
- if (process.platform === 'linux' || process.platform === 'freebsd') {
62
- const { startLinuxTray } = await import('./linux.js')
63
- const tray = await startLinuxTray({ onAction, logger })
64
- return { ...tray, kind: 'sni', get alive() { return true } }
65
- }
66
-
67
- const viewFile = join(stateDir, 'view.json')
68
- const command = helperCommand(viewFile)
69
- if (command === undefined) throw new Error(`不支持的平台:${process.platform}`)
70
- await mkdir(dirname(viewFile), { recursive: true })
71
- // The geometry (a few hundred KB of frames) is written once, next to the view.
72
- if (icon) await writeFile(join(stateDir, 'icon.json'), JSON.stringify(icon))
73
-
74
- let child
75
- let stopped = false
76
- let restarts = 0
77
- let lastView
78
- let writing = Promise.resolve()
79
-
80
- const write = view => {
81
- lastView = view
82
- // Serialize writes so an older view never lands after a newer one.
83
- writing = writing.then(async () => {
84
- const tmp = `${viewFile}.tmp`
85
- await writeFile(tmp, JSON.stringify(lastView))
86
- await replaceFile(tmp, viewFile)
87
- }).catch(error => logger?.warn?.('写入托盘状态失败', error))
88
- return writing
89
- }
90
-
91
- const launch = () => {
92
- const [file, args] = command
93
- child = spawn(file, args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })
94
- const startedAt = Date.now()
95
- createInterface({ input: child.stdout }).on('line', line => {
96
- try {
97
- const { action } = JSON.parse(line)
98
- if (action === 'hide-tray') stopped = true
99
- if (typeof action === 'string') onAction(action)
100
- } catch {}
101
- })
102
- child.stderr.on('data', chunk => logger?.debug?.('tray helper:', String(chunk).trim()))
103
- child.on('error', error => {
104
- child = undefined
105
- logger?.warn?.('托盘进程启动失败', error)
106
- })
107
- // 'close' (not 'exit') fires only after stdout has drained, so a final
108
- // {"action":"hide-tray"} line is handled before we decide to restart.
109
- child.on('close', code => {
110
- child = undefined
111
- if (stopped) return
112
- restarts = Date.now() - startedAt > 60_000 ? 1 : restarts + 1
113
- if (restarts > MAX_RESTARTS) {
114
- logger?.warn?.(`托盘进程连续退出 ${MAX_RESTARTS} 次,已停用(退出码 ${code})`)
115
- return
116
- }
117
- setTimeout(() => { if (!stopped) launch() }, 1000 * restarts)
118
- })
119
- }
120
-
121
- await write({ state: 'idle', title: '…', tooltip: 'DeepSeek Harness', menu: [], badge: '' })
122
- launch()
123
-
124
- return {
125
- kind: process.platform,
126
- update(view) {
127
- return write(view)
128
- },
129
- get alive() { return child !== undefined },
130
- async stop() {
131
- stopped = true
132
- const running = child
133
- if (!running) return
134
- // Ask nicely first: the helper hides its icon and exits by itself.
135
- const exited = new Promise(resolve => running.once('close', resolve))
136
- const timer = setTimeout(() => running.kill(), QUIT_GRACE_MS)
137
- await write({ ...lastView, quit: true })
138
- await exited
139
- clearTimeout(timer)
140
- },
141
- }
142
- }
1
+ /**
2
+ * Tray front door: starts the right per-platform helper and feeds it views.
3
+ *
4
+ * - macOS: `osascript -l JavaScript assets/tray-darwin.js` (NSStatusItem)
5
+ * - Linux: in-process StatusNotifierItem over D-Bus (lib/tray/linux.js)
6
+ * - Windows: none. Windows has no status bar of this kind (and the desktop
7
+ * app keeps a tray icon of its own); lib/index.js never asks.
8
+ *
9
+ * The macOS helper reads the whale geometry from icon.json once, then an
10
+ * atomically rewritten view.json for state, and reports menu clicks as JSON
11
+ * lines on stdout. It also watches the host pid, so a crashed host never
12
+ * leaves an orphan icon behind. `{"quit": true}` in the view asks it to take
13
+ * its icon down and exit on its own.
14
+ */
15
+ import { spawn } from 'node:child_process'
16
+ import { mkdir, rename, writeFile } from 'node:fs/promises'
17
+ import { dirname, join } from 'node:path'
18
+ import { fileURLToPath } from 'node:url'
19
+ import { createInterface } from 'node:readline'
20
+
21
+ const ASSETS = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'assets')
22
+ /** Give up restarting a helper that keeps dying this many times in a row. */
23
+ const MAX_RESTARTS = 5
24
+ /** How long a helper gets to exit on its own after `quit` before it is killed. */
25
+ const QUIT_GRACE_MS = 1500
26
+
27
+ function helperCommand(viewFile) {
28
+ const pid = String(process.pid)
29
+ if (process.platform === 'darwin') {
30
+ return ['/usr/bin/osascript', ['-l', 'JavaScript', join(ASSETS, 'tray-darwin.js'), viewFile, pid]]
31
+ }
32
+ return undefined
33
+ }
34
+
35
+ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
36
+
37
+ /**
38
+ * Replace `file` with `tmp`, retrying the transient EPERM/EBUSY a rename can
39
+ * hit while the helper has the file open for its (sub-millisecond) read.
40
+ */
41
+ async function replaceFile(tmp, file) {
42
+ for (let attempt = 0; ; attempt += 1) {
43
+ try {
44
+ await rename(tmp, file)
45
+ return
46
+ } catch (error) {
47
+ if (attempt >= 5 || !['EPERM', 'EBUSY', 'EACCES'].includes(error?.code)) throw error
48
+ await sleep(20 * (attempt + 1))
49
+ }
50
+ }
51
+ }
52
+
53
+ /**
54
+ * @param {object} options
55
+ * @param {string} options.stateDir - directory for view.json / icon.json.
56
+ * @param {object} [options.icon] - lib/whale.js iconSpec(), written to icon.json.
57
+ * @param {(action: string) => void} options.onAction - menu click handler.
58
+ * @param {object} [options.logger]
59
+ */
60
+ export async function startTray({ stateDir, icon, onAction, logger }) {
61
+ if (process.platform === 'linux' || process.platform === 'freebsd') {
62
+ const { startLinuxTray } = await import('./linux.js')
63
+ const tray = await startLinuxTray({ onAction, logger })
64
+ return { ...tray, kind: 'sni', get alive() { return true } }
65
+ }
66
+
67
+ const viewFile = join(stateDir, 'view.json')
68
+ const command = helperCommand(viewFile)
69
+ if (command === undefined) throw new Error(`不支持的平台:${process.platform}`)
70
+ await mkdir(dirname(viewFile), { recursive: true })
71
+ // The geometry (a few hundred KB of frames) is written once, next to the view.
72
+ if (icon) await writeFile(join(stateDir, 'icon.json'), JSON.stringify(icon))
73
+
74
+ let child
75
+ let stopped = false
76
+ let restarts = 0
77
+ let lastView
78
+ let writing = Promise.resolve()
79
+
80
+ const write = view => {
81
+ lastView = view
82
+ // Serialize writes so an older view never lands after a newer one.
83
+ writing = writing.then(async () => {
84
+ const tmp = `${viewFile}.tmp`
85
+ await writeFile(tmp, JSON.stringify(lastView))
86
+ await replaceFile(tmp, viewFile)
87
+ }).catch(error => logger?.warn?.('写入托盘状态失败', error))
88
+ return writing
89
+ }
90
+
91
+ const launch = () => {
92
+ const [file, args] = command
93
+ child = spawn(file, args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })
94
+ const startedAt = Date.now()
95
+ createInterface({ input: child.stdout }).on('line', line => {
96
+ try {
97
+ const { action } = JSON.parse(line)
98
+ if (action === 'hide-tray') stopped = true
99
+ if (typeof action === 'string') onAction(action)
100
+ } catch {}
101
+ })
102
+ child.stderr.on('data', chunk => logger?.debug?.('tray helper:', String(chunk).trim()))
103
+ child.on('error', error => {
104
+ child = undefined
105
+ logger?.warn?.('托盘进程启动失败', error)
106
+ })
107
+ // 'close' (not 'exit') fires only after stdout has drained, so a final
108
+ // {"action":"hide-tray"} line is handled before we decide to restart.
109
+ child.on('close', code => {
110
+ child = undefined
111
+ if (stopped) return
112
+ restarts = Date.now() - startedAt > 60_000 ? 1 : restarts + 1
113
+ if (restarts > MAX_RESTARTS) {
114
+ logger?.warn?.(`托盘进程连续退出 ${MAX_RESTARTS} 次,已停用(退出码 ${code})`)
115
+ return
116
+ }
117
+ setTimeout(() => { if (!stopped) launch() }, 1000 * restarts)
118
+ })
119
+ }
120
+
121
+ await write({ state: 'idle', title: '…', tooltip: 'DeepSeek Harness', menu: [], badge: '' })
122
+ launch()
123
+
124
+ return {
125
+ kind: process.platform,
126
+ update(view) {
127
+ return write(view)
128
+ },
129
+ get alive() { return child !== undefined },
130
+ async stop() {
131
+ stopped = true
132
+ const running = child
133
+ if (!running) return
134
+ // Ask nicely first: the helper hides its icon and exits by itself.
135
+ const exited = new Promise(resolve => running.once('close', resolve))
136
+ const timer = setTimeout(() => running.kill(), QUIT_GRACE_MS)
137
+ await write({ ...lastView, quit: true })
138
+ await exited
139
+ clearTimeout(timer)
140
+ },
141
+ }
142
+ }