desky-agent 0.3.0 → 0.3.1

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.
@@ -0,0 +1,58 @@
1
+ 'use strict';
2
+ // node selfupdate.js <version> <npm-cli.js>: started by the app (release.start), outlives it.
3
+ //
4
+ // Runs "npm exec desky-agent@<version>", the installer of the new version: it stops the running app, installs, wires
5
+ // the hooks again and starts the app with its window open. Everything it prints goes to state/update.log. What came
6
+ // of it goes to state/app-update.json for the app to show once. If the new app did not come up, the old one (or
7
+ // whatever is installed now) is started again, so Desky is never left off after a click.
8
+
9
+ const fs = require('fs');
10
+ const os = require('os');
11
+ const path = require('path');
12
+ const { spawnSync } = require('child_process');
13
+ const paths = require('./paths');
14
+ const release = require('./release');
15
+ const { launch } = require('./hook');
16
+
17
+ const [version, npm] = process.argv.slice(2);
18
+ const PKG = require('../package.json').name;
19
+ const INSTALLED = path.join(paths.HOME, 'node_modules', PKG, 'package.json');
20
+
21
+ function installedVersion() {
22
+ try {
23
+ return JSON.parse(fs.readFileSync(INSTALLED, 'utf8')).version;
24
+ } catch (e) {
25
+ return null;
26
+ }
27
+ }
28
+
29
+ function main() {
30
+ if (!release.PLAIN.test(String(version)) || !npm) process.exit(2);
31
+ fs.mkdirSync(paths.STATE, { recursive: true });
32
+ const out = fs.openSync(release.UPDATE_LOG, 'w');
33
+ fs.writeSync(out, `${new Date().toISOString()} оновлення Desky до ${version}\n`);
34
+ const env = { ...process.env };
35
+ delete env.ELECTRON_RUN_AS_NODE;
36
+ const r = spawnSync(process.execPath,
37
+ [npm, 'exec', '--yes', `--package=${PKG}@${version}`, '--', PKG, 'install'],
38
+ { stdio: ['ignore', out, out], cwd: os.homedir(), env, windowsHide: true, timeout: 15 * 60 * 1000 });
39
+ const now = installedVersion();
40
+ fs.writeSync(out, `\n${new Date().toISOString()} npm exec: код ${r.status}${r.error ? ', ' + r.error.message : ''}`
41
+ + `, стоїть ${now || 'нічого'}\n`);
42
+ fs.closeSync(out);
43
+
44
+ if (now === version) {
45
+ // the firmware step may have failed (exit 1) while the app updated: that one is in the log and the app says it
46
+ release.writeResult({ ok: true, version, text: `Desky оновлено до ${version}` });
47
+ return;
48
+ }
49
+ release.writeResult({ ok: false, version,
50
+ text: `оновлення до ${version} не вдалося. Лог: ${release.UPDATE_LOG}. Можна з термінала: npx desky-agent@latest` });
51
+ // the installer stops the app before it installs: bring back whatever is there now, with its window
52
+ paths.markStopped(false);
53
+ try {
54
+ launch([]);
55
+ } catch (e) { /* not installed at all any more: the log says why */ }
56
+ }
57
+
58
+ main();
package/src/updater.js CHANGED
@@ -1,138 +1,138 @@
1
- 'use strict';
2
- // Find the boards, decide, flash, check. Shared by the installer, "desky-agent firmware" and the tray app.
3
- // Whoever calls it must have the port free: the tray app stops its Link first, the CLI stops the tray app.
4
-
5
- const fw = require('./firmware');
6
- const link = require('./link');
7
-
8
- const sleep = ms => new Promise(r => setTimeout(r, ms));
9
-
10
- /** Open a port without resetting the board and ask "who": { usb, who, busy }. */
11
- async function probe(usb, ms = 8000) {
12
- let port;
13
- try {
14
- port = await link.openPort(usb.path);
15
- } catch (e) {
16
- return { usb, who: null, busy: true };
17
- }
18
- try {
19
- return { usb, who: await link.askWho(port, ms), busy: false };
20
- } finally {
21
- await new Promise(r => port.close(() => r()));
22
- }
23
- }
24
-
25
- async function scan() {
26
- let found = await link.ports();
27
- for (let i = 0; i < 5 && !found.length; i++) { // a board in the middle of a reboot is off USB for a moment
28
- await sleep(1000);
29
- found = await link.ports();
30
- }
31
- const out = [];
32
- for (const usb of found) out.push(await probe(usb));
33
- return out;
34
- }
35
-
36
- /** After the reset the board drops off USB and comes back (maybe under another name on macOS): find it by its USB
37
- * serial and wait for "who". The new program needs a few seconds to boot. */
38
- async function waitWho(usb, ms = 30000) {
39
- const end = Date.now() + ms;
40
- while (Date.now() < end) {
41
- const now = (await link.ports()).find(p => (usb.serialNumber && p.serialNumber ? p.serialNumber === usb.serialNumber
42
- : p.path === usb.path));
43
- if (now) {
44
- const r = await probe(now, Math.min(8000, Math.max(1000, end - Date.now())));
45
- if (r.who) return r.who;
46
- }
47
- await sleep(1000);
48
- }
49
- return null;
50
- }
51
-
52
- function bundle() {
53
- return fw.loadBundle();
54
- }
55
-
56
- /** Flash one board and check it: { ok, refused?, who?, text }, text being one Russian line for people.
57
- * The "update started" marker goes to state/ once the bootloader said ESP32-S3, before the first byte; it is
58
- * removed only when the board answers "who" with the new version. */
59
- async function update(usb, { bundle: b, from = null, sn = null, log = () => {}, onProgress = () => {}, deps = {} } = {}) {
60
- const writeParts = deps.writeParts || require('./flasher').writeParts;
61
- const wait = deps.waitWho || waitWho;
62
- const { ChipError } = require('./flasher');
63
- try {
64
- await writeParts({
65
- path: usb.path, bundle: b, log, onProgress,
66
- beforeWrite: async () => fw.writeMarker({ port: usb.path, usbSerial: usb.serialNumber, sn, from, to: b.version }),
67
- });
68
- } catch (e) {
69
- if (e instanceof ChipError || (e && e.chip)) {
70
- fw.rememberRefused(usb, e.chip);
71
- return { ok: false, refused: true, text: `${usb.path}: ${e.message}. Не чіпаю й більше не пробую` };
72
- }
73
- return { ok: false, text: `прошивка на ${usb.path} не оновилася: ${e.message}. Не від'єднуй плату й запусти `
74
- + 'npx desky-agent firmware update' };
75
- }
76
- const who = await wait(usb);
77
- if (who && who.fw === b.version) {
78
- fw.clearMarker();
79
- return { ok: true, who, text: `прошивку Desky оновлено: ${from || 'без версії'} → ${b.version} (${usb.path})` };
80
- }
81
- return { ok: false, who, text: who
82
- ? `після запису плата на ${usb.path} відповідає fw=${who.fw || '?'}, а чекали ${b.version}`
83
- : `після запису ${usb.path} не відповів на who. Запусти npx desky-agent firmware update` };
84
- }
85
-
86
- /** The whole pass over every 303A:1001 port, for the installer and the CLI.
87
- * force "firmware update": write the same version again too (never an older one)
88
- * yes a silent board counts as confirmed
89
- * ask(q) a terminal question for a silent board without a marker -> true/false; null: do not ask
90
- * quiet say nothing about boards that are fine
91
- * -> { flashed, failed, boards } */
92
- async function run({ force = false, yes = false, ask = null, quiet = false, say = console.log, log = () => {},
93
- onProgress = () => {}, deps = {} } = {}) {
94
- const result = { flashed: 0, failed: 0, boards: 0 };
95
- let b;
96
- try {
97
- b = (deps.bundle || bundle)();
98
- } catch (e) {
99
- say('прошивка в пакеті не пройшла перевірку: ' + e.message);
100
- result.failed += 1;
101
- return result;
102
- }
103
- const boards = await (deps.scan || scan)();
104
- result.boards = boards.length;
105
- for (const { usb, who, busy } of boards) {
106
- if (busy) {
107
- say(`${usb.path} зайнятий іншою програмою: прошивку на ньому не перевірив`);
108
- continue;
109
- }
110
- const base = { who, usb, bundle: b, marker: fw.readMarker(), refused: fw.refusedChip(usb), force };
111
- let d = fw.decide({ ...base, confirmed: yes });
112
- if (d.action === 'ask') {
113
- const sure = ask ? await ask(`${usb.path}: плата ESP32 (303A:1001) мовчить на who. Це твій Desky, у якого `
114
- + 'перервалося оновлення прошивки? Прошити? [y/N] ') : false;
115
- if (!sure) {
116
- say(`${d.why}: не чіпаю. Якщо це Desky після перерваного оновлення: npx desky-agent firmware update --yes`);
117
- continue;
118
- }
119
- d = fw.decide({ ...base, confirmed: true });
120
- }
121
- if (d.action === 'none') {
122
- if (!quiet) say(`${usb.path}: Desky, ${d.why}${who.sn ? ', номер ' + who.sn : ''}`);
123
- continue;
124
- }
125
- if (d.action === 'warn' || d.action === 'skip') {
126
- say(`${usb.path}: ${d.why}`);
127
- continue;
128
- }
129
- say(`${usb.path}: ${d.why}. Оновлюю прошивку, не від'єднуй плату…`);
130
- const r = await (deps.update || update)(usb, { bundle: b, from: who && who.fw, sn: who && who.sn, log, onProgress });
131
- say(r.text);
132
- if (r.ok) result.flashed += 1;
133
- else if (!r.refused) result.failed += 1;
134
- }
135
- return result;
136
- }
137
-
138
- module.exports = { run, update, scan, probe, waitWho, bundle };
1
+ 'use strict';
2
+ // Find the boards, decide, flash, check. Shared by the installer, "desky-agent firmware" and the tray app.
3
+ // Whoever calls it must have the port free: the tray app stops its Link first, the CLI stops the tray app.
4
+
5
+ const fw = require('./firmware');
6
+ const link = require('./link');
7
+
8
+ const sleep = ms => new Promise(r => setTimeout(r, ms));
9
+
10
+ /** Open a port without resetting the board and ask "who": { usb, who, busy }. */
11
+ async function probe(usb, ms = 8000) {
12
+ let port;
13
+ try {
14
+ port = await link.openPort(usb.path);
15
+ } catch (e) {
16
+ return { usb, who: null, busy: true };
17
+ }
18
+ try {
19
+ return { usb, who: await link.askWho(port, ms), busy: false };
20
+ } finally {
21
+ await new Promise(r => port.close(() => r()));
22
+ }
23
+ }
24
+
25
+ async function scan() {
26
+ let found = await link.ports();
27
+ for (let i = 0; i < 5 && !found.length; i++) { // a board in the middle of a reboot is off USB for a moment
28
+ await sleep(1000);
29
+ found = await link.ports();
30
+ }
31
+ const out = [];
32
+ for (const usb of found) out.push(await probe(usb));
33
+ return out;
34
+ }
35
+
36
+ /** After the reset the board drops off USB and comes back (maybe under another name on macOS): find it by its USB
37
+ * serial and wait for "who". The new program needs a few seconds to boot. */
38
+ async function waitWho(usb, ms = 30000) {
39
+ const end = Date.now() + ms;
40
+ while (Date.now() < end) {
41
+ const now = (await link.ports()).find(p => (usb.serialNumber && p.serialNumber ? p.serialNumber === usb.serialNumber
42
+ : p.path === usb.path));
43
+ if (now) {
44
+ const r = await probe(now, Math.min(8000, Math.max(1000, end - Date.now())));
45
+ if (r.who) return r.who;
46
+ }
47
+ await sleep(1000);
48
+ }
49
+ return null;
50
+ }
51
+
52
+ function bundle() {
53
+ return fw.loadBundle();
54
+ }
55
+
56
+ /** Flash one board and check it: { ok, refused?, who?, text }, text being one Russian line for people.
57
+ * The "update started" marker goes to state/ once the bootloader said ESP32-S3, before the first byte; it is
58
+ * removed only when the board answers "who" with the new version. */
59
+ async function update(usb, { bundle: b, from = null, sn = null, log = () => {}, onProgress = () => {}, deps = {} } = {}) {
60
+ const writeParts = deps.writeParts || require('./flasher').writeParts;
61
+ const wait = deps.waitWho || waitWho;
62
+ const { ChipError } = require('./flasher');
63
+ try {
64
+ await writeParts({
65
+ path: usb.path, bundle: b, log, onProgress,
66
+ beforeWrite: async () => fw.writeMarker({ port: usb.path, usbSerial: usb.serialNumber, sn, from, to: b.version }),
67
+ });
68
+ } catch (e) {
69
+ if (e instanceof ChipError || (e && e.chip)) {
70
+ fw.rememberRefused(usb, e.chip);
71
+ return { ok: false, refused: true, text: `${usb.path}: ${e.message}. Не чіпаю й більше не пробую` };
72
+ }
73
+ return { ok: false, text: `прошивка на ${usb.path} не оновилася: ${e.message}. Не від'єднуй плату й запусти `
74
+ + 'npx desky-agent firmware update' };
75
+ }
76
+ const who = await wait(usb);
77
+ if (who && who.fw === b.version) {
78
+ fw.clearMarker();
79
+ return { ok: true, who, text: `прошивку Desky оновлено: ${from || 'без версії'} → ${b.version} (${usb.path})` };
80
+ }
81
+ return { ok: false, who, text: who
82
+ ? `після запису плата на ${usb.path} відповідає fw=${who.fw || '?'}, а чекали ${b.version}`
83
+ : `після запису ${usb.path} не відповів на who. Запусти npx desky-agent firmware update` };
84
+ }
85
+
86
+ /** The whole pass over every 303A:1001 port, for the installer and the CLI.
87
+ * force "firmware update": write the same version again too (never an older one)
88
+ * yes a silent board counts as confirmed
89
+ * ask(q) a terminal question for a silent board without a marker -> true/false; null: do not ask
90
+ * quiet say nothing about boards that are fine
91
+ * -> { flashed, failed, boards } */
92
+ async function run({ force = false, yes = false, ask = null, quiet = false, say = console.log, log = () => {},
93
+ onProgress = () => {}, deps = {} } = {}) {
94
+ const result = { flashed: 0, failed: 0, boards: 0 };
95
+ let b;
96
+ try {
97
+ b = (deps.bundle || bundle)();
98
+ } catch (e) {
99
+ say('прошивка в пакеті не пройшла перевірку: ' + e.message);
100
+ result.failed += 1;
101
+ return result;
102
+ }
103
+ const boards = await (deps.scan || scan)();
104
+ result.boards = boards.length;
105
+ for (const { usb, who, busy } of boards) {
106
+ if (busy) {
107
+ say(`${usb.path} зайнятий іншою програмою: прошивку на ньому не перевірив`);
108
+ continue;
109
+ }
110
+ const base = { who, usb, bundle: b, marker: fw.readMarker(), refused: fw.refusedChip(usb), force };
111
+ let d = fw.decide({ ...base, confirmed: yes });
112
+ if (d.action === 'ask') {
113
+ const sure = ask ? await ask(`${usb.path}: плата ESP32 (303A:1001) мовчить на who. Це твій Desky, у якого `
114
+ + 'перервалося оновлення прошивки? Прошити? [y/N] ') : false;
115
+ if (!sure) {
116
+ say(`${d.why}: не чіпаю. Якщо це Desky після перерваного оновлення: npx desky-agent firmware update --yes`);
117
+ continue;
118
+ }
119
+ d = fw.decide({ ...base, confirmed: true });
120
+ }
121
+ if (d.action === 'none') {
122
+ if (!quiet) say(`${usb.path}: Desky, ${d.why}${who.sn ? ', номер ' + who.sn : ''}`);
123
+ continue;
124
+ }
125
+ if (d.action === 'warn' || d.action === 'skip') {
126
+ say(`${usb.path}: ${d.why}`);
127
+ continue;
128
+ }
129
+ say(`${usb.path}: ${d.why}. Оновлюю прошивку, не від'єднуй плату…`);
130
+ const r = await (deps.update || update)(usb, { bundle: b, from: who && who.fw, sn: who && who.sn, log, onProgress });
131
+ say(r.text);
132
+ if (r.ok) result.flashed += 1;
133
+ else if (!r.refused) result.failed += 1;
134
+ }
135
+ return result;
136
+ }
137
+
138
+ module.exports = { run, update, scan, probe, waitWho, bundle };