desky-agent 0.3.12 → 0.3.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/electron/main.js CHANGED
@@ -1,286 +1,302 @@
1
- 'use strict';
2
- // Desky in the tray: the daemon (port, hooks, the control app's HTTP) lives in this process, the tray icon shows
3
- // what Desky shows, and the control app opens in a window of its own.
4
- //
5
- // Desky open the window (a shortcut, the Applications folder); wakes Desky after "Выйти"
6
- // Desky --background tray only: a hook started it, or "desky-agent start"
7
- // Desky --login tray only, at login; a new login undoes an old "Выйти"
8
- //
9
- // One instance: a second launch hands its wish (open the window) to the first and quits.
10
-
11
- const fs = require('fs');
12
- const http = require('http');
13
- const path = require('path');
14
- const { app, BrowserWindow, Menu, Tray, Notification, nativeImage, shell, dialog } = require('electron');
15
- const paths = require('../src/paths');
16
- const { Daemon, log } = require('../src/daemon');
17
- const autostart = require('../src/autostart');
18
- const { trayPngs, trayKind } = require('./icons');
19
- const ICO = path.join(__dirname, '..', 'assets', 'clawd.ico');
20
- /** Windows draws a window's taskbar icon from the Start menu shortcut that carries the window's AppUserModelID.
21
- * An old install left "Electron.lnk" with our ID and no icon, so the taskbar showed Electron: drop shortcuts with
22
- * our ID that are not ours, and give ours the ID and the head. */
23
- function winShortcuts() {
24
- if (process.platform !== 'win32') return;
25
- try {
26
- const dir = path.join(process.env.APPDATA || '', 'Microsoft', 'Windows', 'Start Menu', 'Programs');
27
- const ours = path.join(dir, 'Desky Agent.lnk');
28
- for (const name of fs.readdirSync(dir)) {
29
- const f = path.join(dir, name);
30
- if (!name.toLowerCase().endsWith('.lnk') || f === ours) continue;
31
- let l;
32
- try { l = shell.readShortcutLink(f); } catch (e) { continue; }
33
- if (l.appUserModelId === 'desk.clawd.app') { fs.rmSync(f, { force: true }); log('прибрав старий ярлик ' + name); }
34
- }
35
- const want = { target: process.execPath, cwd: path.dirname(process.execPath), icon: ICO, iconIndex: 0,
36
- appUserModelId: 'desk.clawd.app', description: 'Desky Agent' };
37
- let have = null;
38
- try { have = shell.readShortcutLink(ours); } catch (e) {}
39
- if (!have || have.appUserModelId !== want.appUserModelId || have.icon !== ICO
40
- || path.resolve(have.target) !== path.resolve(want.target)) {
41
- shell.writeShortcutLink(ours, have ? 'replace' : 'create', want);
42
- }
43
- } catch (e) { log('ярлик у меню «Пуск»: ' + e.message); }
44
- }
45
-
46
- /** The app's own icon for the window and the taskbar (the head, all sizes); the tray keeps its live state icons. */
47
- function appIcon() {
48
- const img = nativeImage.createFromPath(process.platform === 'win32' ? ICO : path.join(__dirname, '..', 'assets', 'clawd.png'));
49
- return img.isEmpty() ? image('on') : img;
50
- }
51
-
52
- const NAMES = { wake: 'прокинувся', listen: 'слухає', work: 'працює', read: 'читає', ask: 'чекає на тебе',
53
- wait: 'чекає на фонову задачу', limit: 'скінчилися ліміти', error: 'помилка', done: 'закінчив',
54
- idle: 'нічого не робить', sleep: 'спить' };
55
- const MAC = process.platform === 'darwin';
56
- const quietLaunch = argv => argv.includes('--background') || argv.includes('--login');
57
-
58
- app.setName('Desky');
59
- if (process.platform === 'win32') app.setAppUserModelId('desk.clawd.app');
60
-
61
- let daemon = null;
62
- let tray = null;
63
- let win = null;
64
- let shownKey = '';
65
- let fwShown = '';
66
- let appShown = '';
67
- let quitting = false;
68
-
69
- if (!app.requestSingleInstanceLock()) {
70
- app.exit(0);
71
- } else {
72
- app.on('second-instance', (_e, argv) => {
73
- if (quietLaunch(argv)) return;
74
- paths.markStopped(false);
75
- openWindow();
76
- });
77
- app.on('window-all-closed', () => { /* stay in the tray */ });
78
- app.whenReady().then(boot).catch(e => {
79
- log('не запустився: ' + (e.stack || e));
80
- dialog.showErrorBox('Desky Agent', 'Desky не запустився: ' + e.message + '\n\nЛог: ' + paths.LOG);
81
- app.exit(1);
82
- });
83
- }
84
-
85
- async function boot() {
86
- if (MAC && app.dock) app.dock.hide();
87
- winShortcuts();
88
- if (!quietLaunch(process.argv) || process.argv.includes('--login')) paths.markStopped(false);
89
- menu();
90
-
91
- daemon = new Daemon({ onStop: () => quit() });
92
- try {
93
- await daemon.listen();
94
- } catch (e) {
95
- if (e.code !== 'EADDRINUSE') throw e;
96
- // the old Python daemon (agent/) or a stray instance: ask it to go, then take the port
97
- await post('/stop');
98
- await new Promise(r => setTimeout(r, 2500));
99
- daemon.server.removeAllListeners('error');
100
- await daemon.listen().catch(() => {
101
- throw new Error('порт 127.0.0.1:' + paths.port() + ' зайнятий іншою програмою');
102
- });
103
- }
104
- daemon.start();
105
-
106
- tray = new Tray(image('off'));
107
- tray.setToolTip('Desky');
108
- if (!MAC) tray.on('click', () => openWindow()); // Windows, Linux: a click opens; the menu is on right click
109
- refresh();
110
- setInterval(refresh, 1000);
111
-
112
- if (!quietLaunch(process.argv)) openWindow();
113
- }
114
-
115
- function post(p) {
116
- return new Promise(resolve => {
117
- const req = http.request({ host: '127.0.0.1', port: paths.port(), path: p, method: 'POST', timeout: 1500,
118
- headers: { 'Content-Type': 'application/json', 'Content-Length': 2 } }, res => {
119
- res.resume();
120
- res.on('end', resolve);
121
- });
122
- req.on('error', resolve);
123
- req.on('timeout', () => req.destroy());
124
- req.end('{}');
125
- });
126
- }
127
-
128
- function image(kind) {
129
- const img = nativeImage.createEmpty();
130
- const color = daemon && daemon.cfg ? daemon.cfg.color : 'orange';
131
- for (const { scale, buffer } of trayPngs(kind, color)) img.addRepresentation({ scaleFactor: scale, buffer });
132
- return img;
133
- }
134
-
135
- // ---------------------------------------------------------------- the tray
136
- function refresh() {
137
- const st = daemon.status();
138
- const kind = trayKind(st);
139
- const name = NAMES[st.state] || st.state;
140
- const fw = st.firmware_update;
141
- const updating = Boolean(fw && fw.state === 'updating');
142
- const line = updating ? 'Оновлюю прошивку…' : st.connected ? `Desky ${name}` : 'Плату не під\'єднано';
143
- if (fw && fw.text !== fwShown) { // one line when the update starts and one when it ends
144
- fwShown = fw.text;
145
- notify(fw.text);
146
- }
147
- const au = st.app_update || {};
148
- const appNews = au.text || (au.available ? `Вийшла нова версія Desky: ${au.latest}. Оновити можна в пульті` : '');
149
- if (appNews && appNews !== appShown) { // a new version once, then the update's start and end
150
- appShown = appNews;
151
- notify(appNews, () => openWindow());
152
- }
153
- const offer = au.available && au.can && au.state !== 'updating';
154
- const key = [kind, line, st.manual, st.connected, autostart.isEnabledCached(), daemon.cfg.color,
155
- offer && au.latest].join('|');
156
- if (key === shownKey) return;
157
- shownKey = key;
158
- tray.setImage(image(kind));
159
- tray.setToolTip(updating ? 'Desky: ' + fw.text
160
- : st.connected ? `Desky: ${name} · ${st.port}` : 'Desky: плату не під\'єднано');
161
- tray.setContextMenu(Menu.buildFromTemplate([
162
- { label: line, enabled: false },
163
- { label: updating ? 'Не від\'єднуй плату' : st.connected ? `Порт ${st.port}` : 'Під\'єднай кабелем, Desky знайдеться сам',
164
- enabled: false },
165
- { type: 'separator' },
166
- { label: 'Відкрити пульт', click: () => openWindow() },
167
- { label: 'Повернути агенту', visible: st.manual, click: () => daemon.setManual(false) },
168
- { label: 'Перезапустити плату', enabled: st.connected, click: () => daemon.link.reset() },
169
- { label: `Оновити Desky до ${au.latest}`, visible: Boolean(offer), click: () => {
170
- try {
171
- daemon.startAppUpdate();
172
- } catch (e) {
173
- dialog.showErrorBox('Desky Agent', 'Не вдалося: ' + e.message);
174
- }
175
- shownKey = '';
176
- refresh();
177
- } },
178
- { type: 'separator' },
179
- { label: 'Запускати під час входу', type: 'checkbox', checked: autostart.isEnabledCached(),
180
- click: item => {
181
- try {
182
- if (item.checked) autostart.enable();
183
- else autostart.disable();
184
- } catch (e) {
185
- dialog.showErrorBox('Desky Agent', 'Не вдалося: ' + e.message);
186
- }
187
- autostart.forget();
188
- shownKey = '';
189
- refresh();
190
- } },
191
- { label: 'Тека з логом', click: () => shell.openPath(paths.STATE) },
192
- { type: 'separator' },
193
- { label: 'Вийти', click: () => quit() },
194
- ]));
195
- }
196
-
197
- function notify(body, onClick) {
198
- try {
199
- if (!Notification.isSupported()) return;
200
- const n = new Notification({ title: 'Desky Agent', body, silent: true });
201
- if (onClick) n.on('click', onClick);
202
- n.show();
203
- } catch (e) { /* the tray, the window and the log still say it */ }
204
- }
205
-
206
- // ---------------------------------------------------------------- the window
207
- function bounds() {
208
- try {
209
- const b = JSON.parse(fs.readFileSync(paths.WINDOW, 'utf8'));
210
- if (b.width > 400 && b.height > 300) return b;
211
- } catch (e) { /* first time */ }
212
- return { width: 1300, height: 960 };
213
- }
214
-
215
- function openWindow() {
216
- if (!daemon) return;
217
- if (win) {
218
- if (win.isMinimized()) win.restore();
219
- win.show();
220
- win.focus();
221
- return;
222
- }
223
- win = new BrowserWindow({
224
- ...bounds(), minWidth: 900, minHeight: 600, title: 'Desky Agent', show: false, backgroundColor: '#161514',
225
- autoHideMenuBar: true, icon: appIcon(),
226
- webPreferences: { contextIsolation: true, sandbox: true, nodeIntegration: false },
227
- });
228
- // Windows takes the taskbar button from the exe, which is electron.exe renamed: give the window our icon and name
229
- // for the taskbar, the jump list and a pinned button
230
- if (process.platform === 'win32') {
231
- try {
232
- win.setAppDetails({ appId: 'desk.clawd.app', appIconPath: ICO, appIconIndex: 0,
233
- relaunchCommand: JSON.stringify(process.execPath), relaunchDisplayName: 'Desky Agent' });
234
- } catch (e) { /* the window icon still shows */ }
235
- }
236
- win.loadURL(`http://127.0.0.1:${daemon.httpPort}/`);
237
- win.once('ready-to-show', () => win.show());
238
- win.webContents.setWindowOpenHandler(({ url }) => {
239
- if (/^https?:/.test(url)) shell.openExternal(url);
240
- return { action: 'deny' };
241
- });
242
- win.webContents.on('will-navigate', (e, url) => {
243
- if (!url.startsWith(`http://127.0.0.1:${daemon.httpPort}/`)) {
244
- e.preventDefault();
245
- shell.openExternal(url);
246
- }
247
- });
248
- win.on('close', () => {
249
- try {
250
- fs.mkdirSync(paths.STATE, { recursive: true });
251
- const b = win.getNormalBounds();
252
- fs.writeFileSync(paths.WINDOW, JSON.stringify(b));
253
- } catch (e) { /* not worth failing for */ }
254
- });
255
- win.on('closed', () => {
256
- win = null;
257
- if (MAC && app.dock) app.dock.hide();
258
- });
259
- if (MAC && app.dock) app.dock.show();
260
- }
261
-
262
- function menu() {
263
- if (!MAC) {
264
- Menu.setApplicationMenu(null);
265
- return;
266
- }
267
- // macOS: Cmd+C / Cmd+V in the app's text fields need an Edit menu
268
- Menu.setApplicationMenu(Menu.buildFromTemplate([
269
- { label: 'Desky Agent', submenu: [{ role: 'about' }, { type: 'separator' }, { role: 'hide' }, { type: 'separator' },
270
- { label: 'Закрити вікно', accelerator: 'Cmd+W', click: () => win && win.close() },
271
- { label: 'Вийти з Desky Agent', accelerator: 'Cmd+Q', click: () => quit() }] },
272
- { role: 'editMenu' },
273
- { role: 'windowMenu' },
274
- ]));
275
- }
276
-
277
- /** Leave the tray and free the port. Hooks do not start Desky again until it is opened or the next login. */
278
- async function quit() {
279
- if (quitting) return;
280
- quitting = true;
281
- paths.markStopped(true);
282
- if (win) win.destroy();
283
- if (tray) tray.destroy();
284
- if (daemon) await daemon.close();
285
- app.exit(0);
286
- }
1
+ 'use strict';
2
+ // Desky in the tray: the daemon (port, hooks, the control app's HTTP) lives in this process, the tray icon shows
3
+ // what Desky shows, and the control app opens in a window of its own.
4
+ //
5
+ // Desky open the window (a shortcut, the Applications folder); wakes Desky after "Выйти"
6
+ // Desky --background tray only: a hook started it, or "desky-agent start"
7
+ // Desky --login tray only, at login; a new login undoes an old "Выйти"
8
+ //
9
+ // One instance: a second launch hands its wish (open the window) to the first and quits.
10
+
11
+ const fs = require('fs');
12
+ const http = require('http');
13
+ const path = require('path');
14
+ const { app, BrowserWindow, Menu, Tray, Notification, nativeImage, shell, dialog } = require('electron');
15
+ const paths = require('../src/paths');
16
+ const { Daemon, log } = require('../src/daemon');
17
+ const { NOT_CALM } = require('../src/core');
18
+ const autostart = require('../src/autostart');
19
+ const { trayPngs, trayKind } = require('./icons');
20
+ const ICO = path.join(__dirname, '..', 'assets', 'clawd.ico');
21
+ /** Windows draws a window's taskbar icon from the Start menu shortcut that carries the window's AppUserModelID.
22
+ * An old install left "Electron.lnk" with our ID and no icon, so the taskbar showed Electron: drop shortcuts with
23
+ * our ID that are not ours, and give ours the ID and the head. */
24
+ function winShortcuts() {
25
+ if (process.platform !== 'win32') return;
26
+ try {
27
+ const dir = path.join(process.env.APPDATA || '', 'Microsoft', 'Windows', 'Start Menu', 'Programs');
28
+ const ours = path.join(dir, 'Desky Agent.lnk');
29
+ for (const name of fs.readdirSync(dir)) {
30
+ const f = path.join(dir, name);
31
+ if (!name.toLowerCase().endsWith('.lnk') || f === ours) continue;
32
+ let l;
33
+ try { l = shell.readShortcutLink(f); } catch (e) { continue; }
34
+ if (l.appUserModelId === 'desk.clawd.app') { fs.rmSync(f, { force: true }); log('прибрав старий ярлик ' + name); }
35
+ }
36
+ const want = { target: process.execPath, cwd: path.dirname(process.execPath), icon: ICO, iconIndex: 0,
37
+ appUserModelId: 'desk.clawd.app', description: 'Desky Agent' };
38
+ let have = null;
39
+ try { have = shell.readShortcutLink(ours); } catch (e) {}
40
+ if (!have || have.appUserModelId !== want.appUserModelId || have.icon !== ICO
41
+ || path.resolve(have.target) !== path.resolve(want.target)) {
42
+ shell.writeShortcutLink(ours, have ? 'replace' : 'create', want);
43
+ }
44
+ } catch (e) { log('ярлик у меню «Пуск»: ' + e.message); }
45
+ }
46
+
47
+ /** The app's own icon for the window and the taskbar (the head, all sizes); the tray keeps its live state icons. */
48
+ function appIcon() {
49
+ const img = nativeImage.createFromPath(process.platform === 'win32' ? ICO : path.join(__dirname, '..', 'assets', 'clawd.png'));
50
+ return img.isEmpty() ? image('on') : img;
51
+ }
52
+
53
+ const NAMES = { wake: 'прокинувся', listen: 'слухає', work: 'працює', read: 'читає', ask: 'чекає на тебе',
54
+ wait: 'чекає на фонову задачу', limit: 'скінчилися ліміти', error: 'помилка', done: 'закінчив',
55
+ idle: 'нічого не робить', sleep: 'спить' };
56
+ const MAC = process.platform === 'darwin';
57
+ const quietLaunch = argv => argv.includes('--background') || argv.includes('--login');
58
+
59
+ app.setName('Desky');
60
+ if (process.platform === 'win32') app.setAppUserModelId('desk.clawd.app');
61
+
62
+ let daemon = null;
63
+ let tray = null;
64
+ let win = null;
65
+ let shownKey = '';
66
+ let fwShown = '';
67
+ let appShown = '';
68
+ let quitting = false;
69
+
70
+ if (!app.requestSingleInstanceLock()) {
71
+ app.exit(0);
72
+ } else {
73
+ app.on('second-instance', (_e, argv) => {
74
+ if (quietLaunch(argv)) return;
75
+ paths.markStopped(false);
76
+ openWindow();
77
+ });
78
+ app.on('window-all-closed', () => { /* stay in the tray */ });
79
+ app.whenReady().then(boot).catch(e => {
80
+ log('не запустився: ' + (e.stack || e));
81
+ dialog.showErrorBox('Desky Agent', 'Desky не запустився: ' + e.message + '\n\nЛог: ' + paths.LOG);
82
+ app.exit(1);
83
+ });
84
+ }
85
+
86
+ async function boot() {
87
+ if (MAC && app.dock) app.dock.hide();
88
+ winShortcuts();
89
+ if (!quietLaunch(process.argv) || process.argv.includes('--login')) paths.markStopped(false);
90
+ menu();
91
+
92
+ daemon = new Daemon({ onStop: () => quit() });
93
+ try {
94
+ await daemon.listen();
95
+ } catch (e) {
96
+ if (e.code !== 'EADDRINUSE') throw e;
97
+ // the old Python daemon (agent/) or a stray instance: ask it to go, then take the port
98
+ await post('/stop');
99
+ await new Promise(r => setTimeout(r, 2500));
100
+ daemon.server.removeAllListeners('error');
101
+ await daemon.listen().catch(() => {
102
+ throw new Error('порт 127.0.0.1:' + paths.port() + ' зайнятий іншою програмою');
103
+ });
104
+ }
105
+ daemon.start();
106
+
107
+ tray = new Tray(image('off'));
108
+ tray.setToolTip('Desky');
109
+ if (!MAC) tray.on('click', () => openWindow()); // Windows, Linux: a click opens; the menu is on right click
110
+ refresh();
111
+ setInterval(refresh, 1000);
112
+
113
+ if (!quietLaunch(process.argv)) openWindow();
114
+ }
115
+
116
+ function post(p) {
117
+ return new Promise(resolve => {
118
+ const req = http.request({ host: '127.0.0.1', port: paths.port(), path: p, method: 'POST', timeout: 1500,
119
+ headers: { 'Content-Type': 'application/json', 'Content-Length': 2 } }, res => {
120
+ res.resume();
121
+ res.on('end', resolve);
122
+ });
123
+ req.on('error', resolve);
124
+ req.on('timeout', () => req.destroy());
125
+ req.end('{}');
126
+ });
127
+ }
128
+
129
+ function image(kind) {
130
+ const img = nativeImage.createEmpty();
131
+ const color = daemon && daemon.cfg ? daemon.cfg.color : 'orange';
132
+ for (const { scale, buffer } of trayPngs(kind, color)) img.addRepresentation({ scaleFactor: scale, buffer });
133
+ return img;
134
+ }
135
+
136
+ // ---------------------------------------------------------------- the tray
137
+ function refresh() {
138
+ const st = daemon.status();
139
+ const kind = trayKind(st);
140
+ const name = NAMES[st.state] || st.state;
141
+ const fw = st.firmware_update;
142
+ const updating = Boolean(fw && fw.state === 'updating');
143
+ const line = updating ? 'Оновлюю прошивку…' : st.connected ? `Desky ${name}` : 'Плату не під\'єднано';
144
+ if (fw && fw.text !== fwShown) { // one line when the update starts and one when it ends
145
+ fwShown = fw.text;
146
+ notify(fw.text);
147
+ }
148
+ const au = st.app_update || {};
149
+ const appNews = au.text || (au.available ? `Вийшла нова версія Desky: ${au.latest}. Оновити можна в пульті` : '');
150
+ if (appNews && appNews !== appShown) { // a new version once, then the update's start and end
151
+ appShown = appNews;
152
+ notify(appNews, () => openWindow());
153
+ }
154
+ const offer = au.available && au.can && au.state !== 'updating';
155
+ // quiet mode: every emotion that is not calm switched off (the pult's "Лише спокійні"; src/core.js NOT_CALM)
156
+ const off = daemon.cfg.emotions_off || [];
157
+ const quietMode = NOT_CALM.every(k => off.includes(k));
158
+ const key = [kind, line, st.manual, st.connected, autostart.isEnabledCached(), daemon.cfg.color,
159
+ offer && au.latest, off.join(',')].join('|');
160
+ if (key === shownKey) return;
161
+ shownKey = key;
162
+ tray.setImage(image(kind));
163
+ tray.setToolTip(updating ? 'Desky: ' + fw.text
164
+ : st.connected ? `Desky: ${name} · ${st.port}` : 'Desky: плату не під\'єднано');
165
+ tray.setContextMenu(Menu.buildFromTemplate([
166
+ { label: line, enabled: false },
167
+ { label: updating ? 'Не від\'єднуй плату' : st.connected ? `Порт ${st.port}` : 'Під\'єднай кабелем, Desky знайдеться сам',
168
+ enabled: false },
169
+ { type: 'separator' },
170
+ { label: 'Відкрити пульт', click: () => openWindow() },
171
+ { label: 'Повернути агенту', visible: st.manual, click: () => daemon.setManual(false) },
172
+ { label: 'Перезапустити плату', enabled: st.connected, click: () => daemon.link.reset() },
173
+ { label: `Оновити Desky до ${au.latest}`, visible: Boolean(offer), click: () => {
174
+ try {
175
+ daemon.startAppUpdate();
176
+ } catch (e) {
177
+ dialog.showErrorBox('Desky Agent', 'Не вдалося: ' + e.message);
178
+ }
179
+ shownKey = '';
180
+ refresh();
181
+ } },
182
+ { type: 'separator' },
183
+ { label: 'Тихий режим', type: 'checkbox', checked: quietMode, toolTip: 'лише спокійні емоції: без друку, кивків і радості',
184
+ click: item => {
185
+ // on: the calm ones the owner switched off stay off; off: back to what was switched off by hand
186
+ const rest = off.filter(k => !NOT_CALM.includes(k));
187
+ try {
188
+ daemon.saveConfig({ emotions_off: item.checked ? [...rest, ...NOT_CALM] : rest });
189
+ } catch (e) {
190
+ dialog.showErrorBox('Desky Agent', 'Не вдалося: ' + e.message);
191
+ }
192
+ shownKey = '';
193
+ refresh();
194
+ } },
195
+ { label: 'Запускати під час входу', type: 'checkbox', checked: autostart.isEnabledCached(),
196
+ click: item => {
197
+ try {
198
+ if (item.checked) autostart.enable();
199
+ else autostart.disable();
200
+ } catch (e) {
201
+ dialog.showErrorBox('Desky Agent', 'Не вдалося: ' + e.message);
202
+ }
203
+ autostart.forget();
204
+ shownKey = '';
205
+ refresh();
206
+ } },
207
+ { label: 'Тека з логом', click: () => shell.openPath(paths.STATE) },
208
+ { type: 'separator' },
209
+ { label: 'Вийти', click: () => quit() },
210
+ ]));
211
+ }
212
+
213
+ function notify(body, onClick) {
214
+ try {
215
+ if (!Notification.isSupported()) return;
216
+ const n = new Notification({ title: 'Desky Agent', body, silent: true });
217
+ if (onClick) n.on('click', onClick);
218
+ n.show();
219
+ } catch (e) { /* the tray, the window and the log still say it */ }
220
+ }
221
+
222
+ // ---------------------------------------------------------------- the window
223
+ function bounds() {
224
+ try {
225
+ const b = JSON.parse(fs.readFileSync(paths.WINDOW, 'utf8'));
226
+ if (b.width > 400 && b.height > 300) return b;
227
+ } catch (e) { /* first time */ }
228
+ return { width: 1300, height: 960 };
229
+ }
230
+
231
+ function openWindow() {
232
+ if (!daemon) return;
233
+ if (win) {
234
+ if (win.isMinimized()) win.restore();
235
+ win.show();
236
+ win.focus();
237
+ return;
238
+ }
239
+ win = new BrowserWindow({
240
+ ...bounds(), minWidth: 900, minHeight: 600, title: 'Desky Agent', show: false, backgroundColor: '#161514',
241
+ autoHideMenuBar: true, icon: appIcon(),
242
+ webPreferences: { contextIsolation: true, sandbox: true, nodeIntegration: false },
243
+ });
244
+ // Windows takes the taskbar button from the exe, which is electron.exe renamed: give the window our icon and name
245
+ // for the taskbar, the jump list and a pinned button
246
+ if (process.platform === 'win32') {
247
+ try {
248
+ win.setAppDetails({ appId: 'desk.clawd.app', appIconPath: ICO, appIconIndex: 0,
249
+ relaunchCommand: JSON.stringify(process.execPath), relaunchDisplayName: 'Desky Agent' });
250
+ } catch (e) { /* the window icon still shows */ }
251
+ }
252
+ win.loadURL(`http://127.0.0.1:${daemon.httpPort}/`);
253
+ win.once('ready-to-show', () => win.show());
254
+ win.webContents.setWindowOpenHandler(({ url }) => {
255
+ if (/^https?:/.test(url)) shell.openExternal(url);
256
+ return { action: 'deny' };
257
+ });
258
+ win.webContents.on('will-navigate', (e, url) => {
259
+ if (!url.startsWith(`http://127.0.0.1:${daemon.httpPort}/`)) {
260
+ e.preventDefault();
261
+ shell.openExternal(url);
262
+ }
263
+ });
264
+ win.on('close', () => {
265
+ try {
266
+ fs.mkdirSync(paths.STATE, { recursive: true });
267
+ const b = win.getNormalBounds();
268
+ fs.writeFileSync(paths.WINDOW, JSON.stringify(b));
269
+ } catch (e) { /* not worth failing for */ }
270
+ });
271
+ win.on('closed', () => {
272
+ win = null;
273
+ if (MAC && app.dock) app.dock.hide();
274
+ });
275
+ if (MAC && app.dock) app.dock.show();
276
+ }
277
+
278
+ function menu() {
279
+ if (!MAC) {
280
+ Menu.setApplicationMenu(null);
281
+ return;
282
+ }
283
+ // macOS: Cmd+C / Cmd+V in the app's text fields need an Edit menu
284
+ Menu.setApplicationMenu(Menu.buildFromTemplate([
285
+ { label: 'Desky Agent', submenu: [{ role: 'about' }, { type: 'separator' }, { role: 'hide' }, { type: 'separator' },
286
+ { label: 'Закрити вікно', accelerator: 'Cmd+W', click: () => win && win.close() },
287
+ { label: 'Вийти з Desky Agent', accelerator: 'Cmd+Q', click: () => quit() }] },
288
+ { role: 'editMenu' },
289
+ { role: 'windowMenu' },
290
+ ]));
291
+ }
292
+
293
+ /** Leave the tray and free the port. Hooks do not start Desky again until it is opened or the next login. */
294
+ async function quit() {
295
+ if (quitting) return;
296
+ quitting = true;
297
+ paths.markStopped(true);
298
+ if (win) win.destroy();
299
+ if (tray) tray.destroy();
300
+ if (daemon) await daemon.close();
301
+ app.exit(0);
302
+ }
Binary file
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clawd-desk",
3
- "version": "0.3.12",
3
+ "version": "0.3.13",
4
4
  "chip": "esp32s3",
5
5
  "board": "waveshare-esp32-s3-zero",
6
6
  "flash_size": "4MB",
@@ -26,8 +26,8 @@
26
26
  {
27
27
  "file": "firmware.bin",
28
28
  "address": "0x10000",
29
- "size": 340960,
30
- "sha256": "6c4958db2e620ff3ff4bf0813b45aab30cd4768b397f5606fbb40674ac1ab5f2"
29
+ "size": 341424,
30
+ "sha256": "e59b4c05d4517e7f2d04b4fdcc09506117fac9cf8c1bd662fd385db57a6e8949"
31
31
  }
32
32
  ]
33
33
  }