desky-agent 0.0.0-stage → 0.3.0

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.
Files changed (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +49 -2
  3. package/assets/clawd.ico +0 -0
  4. package/assets/clawd.png +0 -0
  5. package/bin/cli.js +206 -0
  6. package/electron/icons.js +79 -0
  7. package/electron/main.js +219 -0
  8. package/firmware/boot_app0.bin +0 -0
  9. package/firmware/bootloader.bin +0 -0
  10. package/firmware/firmware.bin +0 -0
  11. package/firmware/manifest.json +33 -0
  12. package/firmware/partitions.bin +0 -0
  13. package/package.json +38 -4
  14. package/src/autostart.js +106 -0
  15. package/src/board.js +69 -0
  16. package/src/core.js +172 -0
  17. package/src/daemon.js +446 -0
  18. package/src/firmware.js +207 -0
  19. package/src/flasher.js +113 -0
  20. package/src/hook.js +86 -0
  21. package/src/install.js +375 -0
  22. package/src/link.js +207 -0
  23. package/src/paths.js +44 -0
  24. package/src/updater.js +138 -0
  25. package/src/webserial.js +130 -0
  26. package/ui/app.html +1470 -0
  27. package/ui/clawd3d.js +375 -0
  28. package/ui/models/A04_cap_J2.stl +0 -0
  29. package/ui/models/A04_cap_J3.stl +0 -0
  30. package/ui/models/A04_cap_J4.stl +0 -0
  31. package/ui/models/B0_base.stl +0 -0
  32. package/ui/models/B1_body.stl +0 -0
  33. package/ui/models/B2_face_plate.stl +0 -0
  34. package/ui/models/B3_side_left.stl +0 -0
  35. package/ui/models/B4_side_right.stl +0 -0
  36. package/ui/models/C1_column.stl +0 -0
  37. package/ui/models/C2_column_lid.stl +0 -0
  38. package/ui/models/D1_desk_frame.stl +0 -0
  39. package/ui/models/D2_desk_top.stl +0 -0
  40. package/ui/models/L1_laptop.stl +0 -0
  41. package/ui/models/P1_mug.stl +0 -0
  42. package/ui/models/P2_plant.stl +0 -0
  43. package/ui/models/R1_arm_left.stl +0 -0
  44. package/ui/models/R2_arm_right.stl +0 -0
  45. package/ui/models/S1_seat.stl +0 -0
  46. package/ui/models/S2_spacer.stl +0 -0
  47. package/ui/vendor/OrbitControls.js +1532 -0
  48. package/ui/vendor/RoomEnvironment.js +144 -0
  49. package/ui/vendor/STLLoader.js +410 -0
  50. package/ui/vendor/three.LICENSE +21 -0
  51. package/ui/vendor/three.module.min.js +6 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Oleg
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,50 @@
1
- # Temporary Holding Version
1
+ # desky-agent
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Desky — настольный робот, который показывает, что делает Claude Code: печатает, пока агент работает, смотрит в экран, когда агент читает, поворачивается к тебе с трелью, когда агент ждёт ответа, и засыпает в тишине.
4
+
5
+ Этот пакет ставит на компьютер всё, что нужно роботу: приложение в трее, хуки Claude Code и запуск при входе в систему. Windows, macOS, Linux.
6
+
7
+ *A desk robot that acts out what Claude Code is doing. This package installs the tray app, the Claude Code hooks and start-at-login in one command.*
8
+
9
+ ## Установка
10
+
11
+ ```
12
+ npx desky-agent
13
+ ```
14
+
15
+ Нужен Node 18 или новее. Вопросов установщик не задаёт, поэтому команду может запустить и агент. После установки перезапусти открытые сессии Claude Code.
16
+
17
+ Что появится:
18
+
19
+ - **Desky в трее** (на macOS — в строке меню). Держит USB-порт платы и получает события от хуков, даже когда окно закрыто. Значок показывает состояние: серый — плата не подключена, глаза закрыты — спит, смотрит вниз — читает, руки вверх — ждёт тебя.
20
+ - **Пульт** — открывается кликом по значку: сессии, ползунки суставов, сценки, калибровка серво, звуки, настройки, монитор порта.
21
+ - **Хуки** в `~/.claude/settings.json`. Чужие хуки не трогаются, прежний файл остаётся рядом как `settings.json.bak`. Если Desky не запущен, первый же хук поднимет его в трее.
22
+ - **Запуск при входе** и ярлык «Desky» (рабочий стол и «Пуск» на Windows, `~/Applications` на macOS, меню приложений на Linux).
23
+
24
+ Всё ставится в `~/.clawd-desk`.
25
+
26
+ ## Команды
27
+
28
+ ```
29
+ npx desky-agent поставить или обновить
30
+ npx desky-agent open открыть пульт
31
+ npx desky-agent start запустить в трее, без окна
32
+ npx desky-agent stop выйти и отпустить порт (хуки не запустят Desky до open или start)
33
+ npx desky-agent status плата, состояние, сессии
34
+ npx desky-agent doctor проверить всё по порядку и подсказать, что исправить
35
+ npx desky-agent firmware версия прошивки в пакете и на плате
36
+ npx desky-agent firmware update перепрошить плату версией из пакета (калибровка остаётся)
37
+ npx desky-agent uninstall убрать всё, кроме настроек
38
+ ```
39
+
40
+ ## Прошивка
41
+
42
+ Пакет везёт прошивку своей версии. Если на плате прошивка старше, `npx desky-agent` или приложение в трее обновляют её сами: пишется одна строка «прошивка Desky обновлена: 0.1.0 → 0.2.0». Калибровка и серийный номер в памяти робота при этом не стираются. Python и PlatformIO не нужны.
43
+
44
+ - Не отключай плату, пока идёт обновление. Если оно всё же прервалось, следующий запуск `npx desky-agent` допишет прошивку сам.
45
+ - Если прошивка на плате новее пакета, пакет её не трогает и просит обновить себя: `npx desky-agent@latest`.
46
+ - Чужие платы не прошиваются: только ESP32-S3, которая отвечает как Desky. Молчащую плату пакет прошьёт, только если обновление прервалось на этом компьютере или ты подтвердил вопрос (или передал `--yes`).
47
+
48
+ ## Плата
49
+
50
+ Waveshare ESP32-S3-Zero с прошивкой Desky, по USB. Порт находится сам (`COM…`, `/dev/cu.usbmodem…`, `/dev/ttyACM…`) и открывается без перезагрузки платы. На Linux для доступа к порту нужна группа `dialout`.
Binary file
Binary file
package/bin/cli.js ADDED
@@ -0,0 +1,206 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ // desky-agent: put Desky on this computer and drive it from a terminal (or an agent).
4
+
5
+ const fs = require('fs');
6
+ const paths = require('../src/paths');
7
+
8
+ const HELP = `desky-agent ${require('../package.json').version}: Desky Agent — Desky, a desk robot that shows what Claude Code is doing
9
+
10
+ npx desky-agent встановити або оновити: застосунок у треї, хуки, автозапуск
11
+ npx desky-agent open відкрити пульт
12
+ npx desky-agent start запустити в треї, без вікна
13
+ npx desky-agent stop вийти й звільнити порт (хуки не запустять Desky до open або start)
14
+ npx desky-agent status плата, стан, сесії
15
+ npx desky-agent doctor перевірити все по черзі
16
+ npx desky-agent firmware прошивка в пакеті й на платі
17
+ npx desky-agent firmware update
18
+ перепрошити плату версією з пакета (калібрування залишається)
19
+ npx desky-agent uninstall прибрати все, крім налаштувань
20
+ npx desky-agent run програма без вікна й трею, лог у консоль (налагодження)
21
+
22
+ --no-open під час встановлення не відкривати вікно
23
+ --yes плата мовчить на who після перерваного оновлення: прошити без питання`;
24
+
25
+ const NAMES = { wake: 'прокинувся', listen: 'слухає', work: 'працює', read: 'читає', ask: 'чекає на тебе',
26
+ error: 'помилка', done: 'закінчив', idle: 'нічого не робить', sleep: 'спить' };
27
+
28
+ function fail(text) {
29
+ console.error('помилка: ' + text);
30
+ process.exit(1);
31
+ }
32
+
33
+ async function startApp(extra) {
34
+ const ins = require('../src/install');
35
+ if (!fs.existsSync(paths.LAUNCH)) fail('Desky не встановлено: npx desky-agent');
36
+ paths.markStopped(false);
37
+ if (extra.length && (await ins.get('/status'))) return console.log('уже працює');
38
+ require('../src/hook').launch(extra);
39
+ if (!(await ins.waitFor(async () => Boolean(await ins.get('/status')), 20000))) fail('не запустився, лог: ' + paths.LOG);
40
+ console.log(extra.length ? 'запущено, значок у треї' : 'пульт відкрито');
41
+ }
42
+
43
+ async function status() {
44
+ const st = await require('../src/install').get('/status');
45
+ if (!st) return console.log(fs.existsSync(paths.STOPPED) ? 'зупинено (desky-agent start або open)' : 'не запущено');
46
+ const link = st.connected ? `плата на ${st.port}` : 'плату не під\'єднано';
47
+ const OURS = ['desky-agent', 'clawdydesk']; // clawdydesk: the same app before the rename (0.2.4 and older)
48
+ const who = OURS.includes(st.app) ? `Desky Agent ${st.version}` : 'стара програма на Python (agent/)';
49
+ console.log(`${who}; ${link}; показує: ${NAMES[st.state] || st.state}; сесій: ${st.sessions}`
50
+ + (st.manual ? '; ручне керування' : ''));
51
+ if (st.board) {
52
+ console.log(` плата: прошивка ${st.board.fw || 'без версії'}, протокол ${st.board.proto}`
53
+ + (st.board.sn ? `, номер ${st.board.sn}` : '') + (st.firmware ? ` (${st.firmware.why})` : ''));
54
+ }
55
+ for (const [sid, s] of Object.entries(st.by_session || {})) console.log(` ${sid} ${NAMES[s] || s}`);
56
+ return st;
57
+ }
58
+
59
+ async function doctor() {
60
+ const ins = require('../src/install');
61
+ const autostart = require('../src/autostart');
62
+ const { candidates } = require('../src/link');
63
+ const ok = (good, text, fix) => console.log((good ? ' ok ' : ' НІ ') + text + (good || !fix ? '' : '\n ' + fix));
64
+ console.log('Desky, перевірка:');
65
+ ok(fs.existsSync(paths.LAUNCH), 'застосунок встановлено (' + ins.BUNDLE + ')', 'npx desky-agent');
66
+ let wired = false;
67
+ let nodeOk = true;
68
+ try {
69
+ const hooks = JSON.parse(fs.readFileSync(ins.SETTINGS, 'utf8')).hooks || {};
70
+ const mine = Object.values(hooks).flat().flatMap(g => g.hooks || []).filter(ins.ours);
71
+ wired = mine.some(h => /hook\.js/.test((h.args || []).join(' ')));
72
+ nodeOk = mine.every(h => fs.existsSync(h.command));
73
+ } catch (e) { /* no settings */ }
74
+ ok(wired, 'хуки в ' + ins.SETTINGS, 'npx desky-agent');
75
+ ok(nodeOk, 'Node для хуків на місці', 'Node переїхав (nvm?): запусти npx desky-agent ще раз');
76
+ ok(autostart.isEnabled(), 'запуск під час входу', 'увімкни в меню значка в треї або npx desky-agent');
77
+ const st = await ins.get('/status');
78
+ ok(Boolean(st), 'програма відповідає на 127.0.0.1:' + paths.port(),
79
+ fs.existsSync(paths.STOPPED) ? 'зупинена: npx desky-agent start' : 'npx desky-agent start; лог: ' + paths.LOG);
80
+ if (st && !['desky-agent', 'clawdydesk'].includes(st.app)) ok(false, 'це нова програма', 'відповідає стара на Python: npx desky-agent її замінить');
81
+ let devs = st && st.connected ? [st.port] : [];
82
+ if (!st) devs = await candidates();
83
+ ok(devs.length > 0, 'плата Espressif по USB (303A:1001)' + (devs.length ? ': ' + devs.join(', ') : ''),
84
+ 'під\'єднай кабелем з даними (не лише для заряджання)'
85
+ + (process.platform === 'linux' ? '; на Linux потрібна група dialout' : ''));
86
+ if (st) ok(st.connected, 'плата відповіла на "who"', 'порт тримає інша програма (монітор, пульт) або не та прошивка');
87
+ const refused = st && st.port ? require('../src/firmware').refusedChip({ path: st.port }) : null;
88
+ if (refused) {
89
+ ok(false, `на ${st.port} ${refused}, а прошивка Desky лише для ESP32-S3`,
90
+ 'Desky працює з тією прошивкою, що вже стоїть; оновлень для цієї плати не буде');
91
+ } else if (st && st.connected && st.firmware) {
92
+ const fixes = { update: 'npx desky-agent оновить прошивку', 'upgrade-package': 'npx desky-agent@latest',
93
+ mismatch: 'напиши нам: такого не мало б бути' };
94
+ ok(st.firmware.action === 'ok' || st.firmware.action === 'newer', st.firmware.why, fixes[st.firmware.action]);
95
+ }
96
+ }
97
+
98
+ function askYes(question) {
99
+ const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
100
+ return new Promise(resolve => rl.question(question, a => {
101
+ rl.close();
102
+ resolve(/^\s*(y|yes|т|так|д|да)\s*$/i.test(a));
103
+ }));
104
+ }
105
+
106
+ function describe({ usb, who, busy }, bundle) {
107
+ const fwm = require('../src/firmware');
108
+ if (busy) return `${usb.path}: зайнятий іншою програмою`;
109
+ if (!who) {
110
+ return `${usb.path}: плата 303A:1001 мовчить на who` + (fwm.markerMatches(fwm.readMarker(), usb)
111
+ ? ' і тут перервалося оновлення: npx desky-agent firmware update' : ' (не Desky або прошивка не запустилася)');
112
+ }
113
+ const d = fwm.decide({ who, usb, bundle, refused: fwm.refusedChip(usb) });
114
+ const hint = d.action === 'flash' ? '\n оновиться під час запуску Desky або зараз: npx desky-agent firmware update' : '';
115
+ return `${usb.path}: Desky, прошивка ${who.fw || 'без версії'}, протокол ${who.proto}`
116
+ + (who.sn ? `, номер ${who.sn}` : '') + ` (${d.why})` + hint;
117
+ }
118
+
119
+ async function firmwareCmd(args) {
120
+ const fwm = require('../src/firmware');
121
+ const ins = require('../src/install');
122
+ let bundle = null;
123
+ try {
124
+ bundle = fwm.loadBundle();
125
+ } catch (e) {
126
+ console.log('прошивка в пакеті не пройшла перевірку: ' + e.message);
127
+ }
128
+ console.log(bundle ? `у пакеті: прошивка ${bundle.version} для ESP32-S3`
129
+ : 'у цій копії пакета прошивки немає (її кладе туди npm pack перед публікацією)');
130
+
131
+ const st = await ins.get('/status');
132
+ if (!args.includes('update')) {
133
+ if (st && ['desky-agent', 'clawdydesk'].includes(st.app)) { // the app holds the port and already knows the board
134
+ if (st.firmware_update) console.log('останнє оновлення: ' + st.firmware_update.text);
135
+ if (!st.connected || !st.board) return console.log('плата не на зв\'язку з Desky');
136
+ return console.log(describe({ usb: { path: st.port, serialNumber: null }, who: st.board }, bundle));
137
+ }
138
+ if (st) return console.log('порт тримає стара програма на Python: npx desky-agent її замінить');
139
+ const boards = await require('../src/updater').scan();
140
+ if (!boards.length) return console.log('плату не знайдено: під\'єднай Desky кабелем з даними');
141
+ for (const b of boards) console.log(describe(b, bundle));
142
+ return undefined;
143
+ }
144
+
145
+ if (!bundle) fail('нема чим прошивати: у цій копії пакета немає прошивки');
146
+ if (st) {
147
+ console.log('зупиняю Desky, щоб звільнити порт');
148
+ if (!(await ins.stopRunning())) fail('Desky не зупинився: закрий його в треї й запусти ще раз');
149
+ }
150
+ const r = await ins.firmware({ force: true, yes: args.includes('--yes') || args.includes('-y'),
151
+ ask: process.stdin.isTTY ? askYes : null, quiet: false });
152
+ if (st && fs.existsSync(paths.LAUNCH) && !fs.existsSync(paths.STOPPED)) {
153
+ require('../src/hook').launch(['--background']);
154
+ console.log('Desky знову в треї');
155
+ }
156
+ if (!r.boards) console.log('плату не знайдено: під\'єднай Desky кабелем з даними');
157
+ if (r.failed) process.exitCode = 1;
158
+ return r;
159
+ }
160
+
161
+ async function main() {
162
+ const args = process.argv.slice(2);
163
+ const cmd = args.find(a => !a.startsWith('-')) || 'install';
164
+ const ins = () => require('../src/install');
165
+ switch (cmd) {
166
+ case 'install':
167
+ return ins().install({ open: !args.includes('--no-open'), yes: args.includes('--yes') || args.includes('-y') });
168
+ case 'firmware':
169
+ return firmwareCmd(args);
170
+ case 'open':
171
+ return startApp([]);
172
+ case 'start':
173
+ return startApp(['--background']);
174
+ case 'stop':
175
+ paths.markStopped(true);
176
+ if (!(await ins().get('/status'))) return console.log('не запущено');
177
+ return console.log((await ins().stopRunning()) ? 'зупинено, порт вільний; хуки не запустять Desky до open або start'
178
+ : 'не зупинився');
179
+ case 'status':
180
+ return status();
181
+ case 'doctor':
182
+ return doctor();
183
+ case 'uninstall':
184
+ return ins().uninstall();
185
+ case 'run': {
186
+ process.env.CLAWD_LOG_CONSOLE = '1';
187
+ const { Daemon } = require('../src/daemon');
188
+ const d = new Daemon({ onStop: () => d.close().then(() => process.exit(0)) });
189
+ await d.listen().catch(e => fail(e.code === 'EADDRINUSE' ? 'порт зайнятий: Desky уже запущено (desky-agent stop)' : e.message));
190
+ d.start();
191
+ process.on('SIGINT', () => d.close().then(() => process.exit(0)));
192
+ return undefined;
193
+ }
194
+ case 'help':
195
+ return console.log(HELP);
196
+ default:
197
+ console.log(HELP);
198
+ return process.exit(2);
199
+ }
200
+ }
201
+
202
+ if (process.argv.includes('--help') || process.argv.includes('-h')) {
203
+ console.log(HELP);
204
+ } else {
205
+ main().catch(e => fail(e.message || e));
206
+ }
@@ -0,0 +1,79 @@
1
+ 'use strict';
2
+ // Tray icons: the pixel Desky from the app's favicon, drawn here as PNGs so there are no image files to keep in
3
+ // step. One pose per thing worth seeing at a glance in the tray.
4
+
5
+ const zlib = require('zlib');
6
+
7
+ const ORANGE = [0xd9, 0x77, 0x4b, 255];
8
+ // the body in the tray for each colour Desky is printed in (src/core.js COLORS); graphite a shade lighter, to be seen
9
+ // on a dark taskbar
10
+ const BODY = { orange: ORANGE, white: [0xec, 0xe8, 0xe1, 255], mint: [0x7c, 0xc4, 0xa4, 255], blue: [0x6f, 0xa3, 0xd8, 255],
11
+ graphite: [0x6a, 0x67, 0x63, 255] };
12
+ const GREY = [0x8a, 0x85, 0x80, 255];
13
+ const EYE = [0x22, 0x22, 0x22, 255];
14
+
15
+ /** 16x16 grid of the pose: [x, y, w, h, colour] rectangles. */
16
+ function pose(kind, body) {
17
+ const r = [[2, 3, 12, 9, body], [3, 12, 2, 3, body], [11, 12, 2, 3, body]];
18
+ if (kind === 'ask') r.push([0, 0, 2, 6, body], [14, 0, 2, 6, body]); // arms up: a call for you
19
+ else r.push([0, 6, 2, 3, body], [14, 6, 2, 3, body]);
20
+ if (kind === 'sleep') r.push([5, 7, 2, 1, EYE], [9, 7, 2, 1, EYE]); // eyes shut
21
+ else if (kind === 'read') r.push([5, 7, 2, 3, EYE], [9, 7, 2, 3, EYE]); // looking down at the screen
22
+ else r.push([5, 5, 2, 3, EYE], [9, 5, 2, 3, EYE]);
23
+ return r;
24
+ }
25
+
26
+ const CRC = new Int32Array(256).map((_, n) => {
27
+ let c = n;
28
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
29
+ return c;
30
+ });
31
+ function crc32(buf) {
32
+ let c = -1;
33
+ for (const b of buf) c = CRC[(c ^ b) & 0xff] ^ (c >>> 8);
34
+ return (c ^ -1) >>> 0;
35
+ }
36
+ function chunk(type, data) {
37
+ const len = Buffer.alloc(4);
38
+ len.writeUInt32BE(data.length);
39
+ const td = Buffer.concat([Buffer.from(type, 'ascii'), data]);
40
+ const crc = Buffer.alloc(4);
41
+ crc.writeUInt32BE(crc32(td));
42
+ return Buffer.concat([len, td, crc]);
43
+ }
44
+
45
+ function png(rects, scale) {
46
+ const size = 16 * scale;
47
+ const rgba = Buffer.alloc(size * size * 4);
48
+ for (const [x, y, w, h, c] of rects) {
49
+ for (let yy = y * scale; yy < (y + h) * scale; yy++) {
50
+ for (let xx = x * scale; xx < (x + w) * scale; xx++) Buffer.from(c).copy(rgba, (yy * size + xx) * 4);
51
+ }
52
+ }
53
+ const raw = Buffer.alloc(size * (size * 4 + 1));
54
+ for (let y = 0; y < size; y++) rgba.copy(raw, y * (size * 4 + 1) + 1, y * size * 4, (y + 1) * size * 4);
55
+ const ihdr = Buffer.alloc(13);
56
+ ihdr.writeUInt32BE(size, 0);
57
+ ihdr.writeUInt32BE(size, 4);
58
+ ihdr[8] = 8; // 8 bits per channel
59
+ ihdr[9] = 6; // RGBA
60
+ return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk('IHDR', ihdr),
61
+ chunk('IDAT', zlib.deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]);
62
+ }
63
+
64
+ /** What the tray shows: no board (grey), asleep, reading, a call for you, or plain Desky. */
65
+ function trayKind(st) {
66
+ if (!st || !st.connected) return 'off';
67
+ if (st.state === 'sleep') return 'sleep';
68
+ if (st.state === 'read') return 'read';
69
+ if (st.state === 'ask') return 'ask';
70
+ return 'on';
71
+ }
72
+
73
+ /** PNG buffers at 1x, 2x and 3x for a tray kind, in Desky's colour. */
74
+ function trayPngs(kind, color) {
75
+ const rects = pose(kind === 'off' ? 'on' : kind, kind === 'off' ? GREY : BODY[color] || ORANGE);
76
+ return [1, 2, 3].map(scale => ({ scale, buffer: png(rects, scale) }));
77
+ }
78
+
79
+ module.exports = { trayPngs, trayKind, png, pose };
@@ -0,0 +1,219 @@
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
+
20
+ const NAMES = { wake: 'прокинувся', listen: 'слухає', work: 'працює', read: 'читає', ask: 'чекає на тебе',
21
+ error: 'помилка', done: 'закінчив', idle: 'нічого не робить', sleep: 'спить' };
22
+ const MAC = process.platform === 'darwin';
23
+ const quietLaunch = argv => argv.includes('--background') || argv.includes('--login');
24
+
25
+ app.setName('Desky');
26
+ if (process.platform === 'win32') app.setAppUserModelId('desk.clawd.app');
27
+
28
+ let daemon = null;
29
+ let tray = null;
30
+ let win = null;
31
+ let shownKey = '';
32
+ let fwShown = '';
33
+ let quitting = false;
34
+
35
+ if (!app.requestSingleInstanceLock()) {
36
+ app.exit(0);
37
+ } else {
38
+ app.on('second-instance', (_e, argv) => {
39
+ if (quietLaunch(argv)) return;
40
+ paths.markStopped(false);
41
+ openWindow();
42
+ });
43
+ app.on('window-all-closed', () => { /* stay in the tray */ });
44
+ app.whenReady().then(boot).catch(e => {
45
+ log('не запустився: ' + (e.stack || e));
46
+ dialog.showErrorBox('Desky Agent', 'Desky не запустився: ' + e.message + '\n\nЛог: ' + paths.LOG);
47
+ app.exit(1);
48
+ });
49
+ }
50
+
51
+ async function boot() {
52
+ if (MAC && app.dock) app.dock.hide();
53
+ if (!quietLaunch(process.argv) || process.argv.includes('--login')) paths.markStopped(false);
54
+ menu();
55
+
56
+ daemon = new Daemon({ onStop: () => quit() });
57
+ try {
58
+ await daemon.listen();
59
+ } catch (e) {
60
+ if (e.code !== 'EADDRINUSE') throw e;
61
+ // the old Python daemon (agent/) or a stray instance: ask it to go, then take the port
62
+ await post('/stop');
63
+ await new Promise(r => setTimeout(r, 2500));
64
+ daemon.server.removeAllListeners('error');
65
+ await daemon.listen().catch(() => {
66
+ throw new Error('порт 127.0.0.1:' + paths.port() + ' зайнятий іншою програмою');
67
+ });
68
+ }
69
+ daemon.start();
70
+
71
+ tray = new Tray(image('off'));
72
+ tray.setToolTip('Desky');
73
+ if (!MAC) tray.on('click', () => openWindow()); // Windows, Linux: a click opens; the menu is on right click
74
+ refresh();
75
+ setInterval(refresh, 1000);
76
+
77
+ if (!quietLaunch(process.argv)) openWindow();
78
+ }
79
+
80
+ function post(p) {
81
+ return new Promise(resolve => {
82
+ const req = http.request({ host: '127.0.0.1', port: paths.port(), path: p, method: 'POST', timeout: 1500,
83
+ headers: { 'Content-Type': 'application/json', 'Content-Length': 2 } }, res => {
84
+ res.resume();
85
+ res.on('end', resolve);
86
+ });
87
+ req.on('error', resolve);
88
+ req.on('timeout', () => req.destroy());
89
+ req.end('{}');
90
+ });
91
+ }
92
+
93
+ function image(kind) {
94
+ const img = nativeImage.createEmpty();
95
+ const color = daemon && daemon.cfg ? daemon.cfg.color : 'orange';
96
+ for (const { scale, buffer } of trayPngs(kind, color)) img.addRepresentation({ scaleFactor: scale, buffer });
97
+ return img;
98
+ }
99
+
100
+ // ---------------------------------------------------------------- the tray
101
+ function refresh() {
102
+ const st = daemon.status();
103
+ const kind = trayKind(st);
104
+ const name = NAMES[st.state] || st.state;
105
+ const fw = st.firmware_update;
106
+ const updating = Boolean(fw && fw.state === 'updating');
107
+ const line = updating ? 'Оновлюю прошивку…' : st.connected ? `Desky ${name}` : 'Плату не під\'єднано';
108
+ if (fw && fw.text !== fwShown) { // one line when the update starts and one when it ends
109
+ fwShown = fw.text;
110
+ try {
111
+ if (Notification.isSupported()) new Notification({ title: 'Desky Agent', body: fw.text, silent: true }).show();
112
+ } catch (e) { /* the tray line and the log still say it */ }
113
+ }
114
+ const key = [kind, line, st.manual, st.connected, autostart.isEnabledCached(), daemon.cfg.color].join('|');
115
+ if (key === shownKey) return;
116
+ shownKey = key;
117
+ tray.setImage(image(kind));
118
+ tray.setToolTip(updating ? 'Desky: ' + fw.text
119
+ : st.connected ? `Desky: ${name} · ${st.port}` : 'Desky: плату не під\'єднано');
120
+ tray.setContextMenu(Menu.buildFromTemplate([
121
+ { label: line, enabled: false },
122
+ { label: updating ? 'Не від\'єднуй плату' : st.connected ? `Порт ${st.port}` : 'Під\'єднай кабелем, Desky знайдеться сам',
123
+ enabled: false },
124
+ { type: 'separator' },
125
+ { label: 'Відкрити пульт', click: () => openWindow() },
126
+ { label: 'Повернути агенту', visible: st.manual, click: () => daemon.setManual(false) },
127
+ { label: 'Перезапустити плату', enabled: st.connected, click: () => daemon.link.reset() },
128
+ { type: 'separator' },
129
+ { label: 'Запускати під час входу', type: 'checkbox', checked: autostart.isEnabledCached(),
130
+ click: item => {
131
+ try {
132
+ if (item.checked) autostart.enable();
133
+ else autostart.disable();
134
+ } catch (e) {
135
+ dialog.showErrorBox('Desky Agent', 'Не вдалося: ' + e.message);
136
+ }
137
+ autostart.forget();
138
+ shownKey = '';
139
+ refresh();
140
+ } },
141
+ { label: 'Тека з логом', click: () => shell.openPath(paths.STATE) },
142
+ { type: 'separator' },
143
+ { label: 'Вийти', click: () => quit() },
144
+ ]));
145
+ }
146
+
147
+ // ---------------------------------------------------------------- the window
148
+ function bounds() {
149
+ try {
150
+ const b = JSON.parse(fs.readFileSync(paths.WINDOW, 'utf8'));
151
+ if (b.width > 400 && b.height > 300) return b;
152
+ } catch (e) { /* first time */ }
153
+ return { width: 1300, height: 960 };
154
+ }
155
+
156
+ function openWindow() {
157
+ if (!daemon) return;
158
+ if (win) {
159
+ if (win.isMinimized()) win.restore();
160
+ win.show();
161
+ win.focus();
162
+ return;
163
+ }
164
+ win = new BrowserWindow({
165
+ ...bounds(), minWidth: 900, minHeight: 600, title: 'Desky Agent', show: false, backgroundColor: '#161514',
166
+ autoHideMenuBar: true, icon: image('on'),
167
+ webPreferences: { contextIsolation: true, sandbox: true, nodeIntegration: false },
168
+ });
169
+ win.loadURL(`http://127.0.0.1:${daemon.httpPort}/`);
170
+ win.once('ready-to-show', () => win.show());
171
+ win.webContents.setWindowOpenHandler(({ url }) => {
172
+ if (/^https?:/.test(url)) shell.openExternal(url);
173
+ return { action: 'deny' };
174
+ });
175
+ win.webContents.on('will-navigate', (e, url) => {
176
+ if (!url.startsWith(`http://127.0.0.1:${daemon.httpPort}/`)) {
177
+ e.preventDefault();
178
+ shell.openExternal(url);
179
+ }
180
+ });
181
+ win.on('close', () => {
182
+ try {
183
+ fs.mkdirSync(paths.STATE, { recursive: true });
184
+ const b = win.getNormalBounds();
185
+ fs.writeFileSync(paths.WINDOW, JSON.stringify(b));
186
+ } catch (e) { /* not worth failing for */ }
187
+ });
188
+ win.on('closed', () => {
189
+ win = null;
190
+ if (MAC && app.dock) app.dock.hide();
191
+ });
192
+ if (MAC && app.dock) app.dock.show();
193
+ }
194
+
195
+ function menu() {
196
+ if (!MAC) {
197
+ Menu.setApplicationMenu(null);
198
+ return;
199
+ }
200
+ // macOS: Cmd+C / Cmd+V in the app's text fields need an Edit menu
201
+ Menu.setApplicationMenu(Menu.buildFromTemplate([
202
+ { label: 'Desky Agent', submenu: [{ role: 'about' }, { type: 'separator' }, { role: 'hide' }, { type: 'separator' },
203
+ { label: 'Закрити вікно', accelerator: 'Cmd+W', click: () => win && win.close() },
204
+ { label: 'Вийти з Desky Agent', accelerator: 'Cmd+Q', click: () => quit() }] },
205
+ { role: 'editMenu' },
206
+ { role: 'windowMenu' },
207
+ ]));
208
+ }
209
+
210
+ /** Leave the tray and free the port. Hooks do not start Desky again until it is opened or the next login. */
211
+ async function quit() {
212
+ if (quitting) return;
213
+ quitting = true;
214
+ paths.markStopped(true);
215
+ if (win) win.destroy();
216
+ if (tray) tray.destroy();
217
+ if (daemon) await daemon.close();
218
+ app.exit(0);
219
+ }
Binary file
Binary file
Binary file
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "clawd-desk",
3
+ "version": "0.3.0",
4
+ "chip": "esp32s3",
5
+ "board": "waveshare-esp32-s3-zero",
6
+ "flash_size": "4MB",
7
+ "parts": [
8
+ {
9
+ "file": "bootloader.bin",
10
+ "address": "0x0",
11
+ "size": 15104,
12
+ "sha256": "e01a2300de23c8d601e9f2a37684b5dbc83ae37132d5a8833e23520afd895f92"
13
+ },
14
+ {
15
+ "file": "partitions.bin",
16
+ "address": "0x8000",
17
+ "size": 3072,
18
+ "sha256": "148b959cbff1c38aa8e1d5c0ba9d612c54997b945e56a63f41223eef650653a1"
19
+ },
20
+ {
21
+ "file": "boot_app0.bin",
22
+ "address": "0xE000",
23
+ "size": 8192,
24
+ "sha256": "f94c5d786a7a8fab06ac5d10e33bf37711a6697636dc037559ea19cc410a17f0"
25
+ },
26
+ {
27
+ "file": "firmware.bin",
28
+ "address": "0x10000",
29
+ "size": 338304,
30
+ "sha256": "0e39e3031dc1eba11c8fe993488c72dc8fa47a0ba57389c442147449d9a94cc9"
31
+ }
32
+ ]
33
+ }
Binary file