kamoji-dev 0.0.0-stage → 0.1.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,398 @@
1
+ // One development session: a Kamoji link (reconnected when it drops), the app's files, the logs.
2
+ // Environment-neutral: the command line (../dev.js: `kamoji dev`, `kamoji install`, `kamoji apps`, `kamoji
3
+ // shot`, `kamoji forget`) and the web IDE on developer.kamoji.bot extend it with how they read the app
4
+ // (runChecks), save a screenshot (saveShot) and make a Session (makeSession, with their crypto provider).
5
+ import { bundleHash, compareVersions } from './check.js'
6
+ import { KamojiError, Session, diffFiles } from './protocol.js'
7
+ import { classify, classifyBle } from '../logfilter.js'
8
+
9
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
10
+ export const kb = (n) => `${(n / 1024).toFixed(n < 10240 ? 1 : 0)} KB`
11
+ const secs = (ms) => `${(ms / 1000).toFixed(1)} s`
12
+ const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`
13
+ const names = (paths) => (paths.length <= 3 ? paths.join(', ') : `${paths.slice(0, 3).join(', ')} +${paths.length - 3} more`)
14
+
15
+ /** "1 file changed (main.lua, 0.4 KB), 1 file deleted (old.lua)" */
16
+ export function describeUpdate(changed, deleted) {
17
+ const parts = []
18
+ if (changed.length)
19
+ parts.push(`${plural(changed.length, 'file')} changed (${names(changed.map((f) => f.path))}, ${kb(changed.reduce((n, f) => n + f.data.length, 0))})`)
20
+ if (deleted.length) parts.push(`${plural(deleted.length, 'file')} deleted (${names(deleted)})`)
21
+ return parts.join(', ')
22
+ }
23
+
24
+ export const NOTE_NO_UPDATE =
25
+ 'This firmware installs whole mini apps only (sending only the changed files needs firmware 0.3.3): sending every file.'
26
+ export const NOTE_NO_BLE_LOG =
27
+ 'This firmware sends no app log over Bluetooth (needs firmware 0.3.3): plug in a USB cable for print() output, Lua errors and crashes.'
28
+
29
+ export function printProblems(ui, result) {
30
+ for (const p of result.problems) {
31
+ const where = p.where ? `${p.where}: ` : ''
32
+ if (p.level === 'error') ui.error(`${where}${p.message} [${p.id}]`)
33
+ else if (p.level === 'warning') ui.warn(`${where}${p.message} [${p.id}]`)
34
+ else ui.info(`${where}${p.message}`)
35
+ }
36
+ }
37
+
38
+ export class DevSession {
39
+ /**
40
+ * @param {object} o
41
+ * @param {string} [o.folder]
42
+ * @param {ReturnType<typeof makeUi>} o.ui
43
+ * @param {(opts:{onDisconnect:Function}) => Promise<{link:any, board:string, name?:string, revision?:string, firmware?:string}>} o.connector
44
+ * @param {(board:string) => {key:Buffer, created:boolean}} o.keys
45
+ * @param {import('./serial.js').SerialLog} [o.serial]
46
+ * @param {object} [o.timeouts]
47
+ * @param {boolean} [o.reboot] restart Kamoji by itself when the app's Bluetooth services need it
48
+ * @param {boolean} [o.lua]
49
+ * @param {boolean} [o.bleLogs] the app's log over Bluetooth (APP_LOG, firmware 0.3.3): on without a USB log, or --ble-logs
50
+ * @param {boolean} [o.reopen] open the app again after a reconnect (false for `kamoji logs`)
51
+ */
52
+ constructor(o) {
53
+ Object.assign(this, {
54
+ reboot: false,
55
+ lua: true,
56
+ bleLogs: false,
57
+ reopen: true,
58
+ restartHint: 'Press b + Enter to restart it (or use --reboot).',
59
+ ...o,
60
+ })
61
+ this.logsOn = null // the app id (or '' for all) Kamoji sends its log for, on this link
62
+ this.notes = new Set()
63
+ this.noUpdate = false
64
+ this.session = null
65
+ this.conn = null
66
+ this.connected = false
67
+ this.connecting = null
68
+ this.lastHash = null
69
+ this.lastList = null
70
+ this.busy = false
71
+ this.closed = false
72
+ this.appId = null
73
+ this.keepalive = null
74
+ }
75
+
76
+ // ------------------------------------------------------------------ connection
77
+
78
+ async connect() {
79
+ if (this.connected) return
80
+ this.connecting ??= this._connect().finally(() => (this.connecting = null))
81
+ return this.connecting
82
+ }
83
+
84
+ async _connect() {
85
+ const ui = this.ui
86
+ ui.info('Looking for Kamoji over Bluetooth…')
87
+ const conn = await this.connector({ onDisconnect: (reason) => this._lost(reason) })
88
+ this.conn = conn
89
+ const session = this.makeSession(conn.link, { timeouts: this.timeouts, onLog: (l) => this.bleLogLine(l) })
90
+ this.logsOn = null
91
+ this.noUpdate = false
92
+ this.session = session
93
+ let auth
94
+ let created
95
+ try {
96
+ ;({ auth, created } = await this.authorizeLink(session, conn))
97
+ } catch (e) {
98
+ await conn.link.disconnect?.()
99
+ throw e
100
+ }
101
+ this.connected = true
102
+ if (auth.status === 'authorized' && auth.enrolled)
103
+ ui.ok(`${conn.name ?? conn.board} trusts this computer now (signal ${auth.rssi ?? '?'} dBm; ${auth.devices} trusted device(s)).`)
104
+ else if (created && auth.status === 'authorized') ui.info('Kamoji already trusted this key.')
105
+ await session.linkFast()
106
+ const info = await session.info()
107
+ this.firmware = info.fw
108
+ ui.ok(
109
+ `Connected to ${conn.name ?? conn.board}${info.nick ? ` "${info.nick}"` : ''}: firmware ${info.fw}${conn.revision ? `, ${conn.revision}` : ''}.`,
110
+ )
111
+ this.lastList = await session.listApps()
112
+ const st = this.lastList.storage
113
+ ui.info(
114
+ `${this.lastList.apps.length} mini app(s) on it${st ? `, storage ${kb(st.used)} of ${kb(st.total)} used` : ''}.`,
115
+ )
116
+ await this.startBleLogs()
117
+ this._startKeepalive()
118
+ }
119
+
120
+ /** A Session on this link (the command line's uses node:crypto, the web IDE's WebCrypto). */
121
+ makeSession(link, opts) {
122
+ return new Session(link, { crypto: this.crypto, ...opts })
123
+ }
124
+
125
+ /** The key for this Kamoji, then AUTH. Returns { auth, created }. */
126
+ async authorizeLink(session, conn) {
127
+ const { key, created } = await this.keys(conn.board)
128
+ return { auth: await session.authorize(key), created }
129
+ }
130
+
131
+ /** The app's files, checked: core/check.js checkFiles' result. */
132
+ runChecks() {
133
+ throw new Error('DevSession.runChecks: not implemented')
134
+ }
135
+
136
+ /** Keep a screenshot; returns where it went (shown to the developer). */
137
+ saveShot(_dir, _name, _jpeg) {
138
+ throw new Error('DevSession.saveShot: not implemented')
139
+ }
140
+
141
+ _lost(reason) {
142
+ if (!this.connected) return
143
+ this.connected = false
144
+ this.session?.close()
145
+ if (this.closed) return
146
+ this.ui.warn(`Bluetooth link to Kamoji lost${reason !== undefined ? ` (${reason})` : ''}: it restarted, went out of range, or another device connected.`)
147
+ if (this.watching) this._reconnectLoop()
148
+ }
149
+
150
+ async _reconnectLoop() {
151
+ for (let attempt = 1; !this.closed && !this.connected; attempt++) {
152
+ await sleep(attempt <= 10 ? 3000 : 10000)
153
+ if (this.closed || this.connected) return
154
+ try {
155
+ await this.connect()
156
+ if (this.appId && this.reopen) await this.open()
157
+ return
158
+ } catch (e) {
159
+ if (attempt === 1 || attempt % 10 === 0) this.ui.info(`Reconnecting… (${e.message})`)
160
+ }
161
+ }
162
+ }
163
+
164
+ /** APP_LOG:ON for the app (all apps without one), once per link and app. A one-time note on older firmware. */
165
+ async startBleLogs() {
166
+ if (!this.bleLogs || !this.connected || this.notes.has('no-ble-log')) return
167
+ const want = this.appId ?? ''
168
+ if (this.logsOn === want) return
169
+ const r = await this.session.appLog(want || null)
170
+ if (r === true) this.logsOn = want
171
+ else if (r === false) this.note('no-ble-log', NOTE_NO_BLE_LOG)
172
+ else this.ui.warn("Kamoji didn't confirm its app log over Bluetooth (APP_LOG): no print() output for now.")
173
+ }
174
+
175
+ note(id, text) {
176
+ if (this.notes.has(id)) return
177
+ this.notes.add(id)
178
+ this.ui.info(text)
179
+ }
180
+
181
+ _startKeepalive() {
182
+ if (this.keepalive) clearInterval(this.keepalive)
183
+ this.keepalive = setInterval(() => {
184
+ if (!this.connected) return
185
+ this.session.linkAlive()
186
+ // While watching (`kamoji dev`), keep the link fast between saves: Kamoji holds it LINK_FAST_HOLD_MS (8 s)
187
+ // after the last LINK_FAST, then relaxes to an 800 ms interval, and the next reload waited ~8 s at that
188
+ // pace for the fast parameters to come back (12.7 s installs instead of 2-3 s, R8 test 2026-11-17).
189
+ if (this.busy || this.watching) this.session.linkFast()
190
+ }, 5000)
191
+ this.keepalive.unref?.()
192
+ }
193
+
194
+ async close() {
195
+ this.closed = true
196
+ if (this.keepalive) clearInterval(this.keepalive)
197
+ this.session?.close()
198
+ await this.conn?.link.disconnect?.()
199
+ await this.serial?.close()
200
+ }
201
+
202
+ // ------------------------------------------------------------------ the app
203
+
204
+ /** Check the folder; print problems; returns the check result (null = errors). */
205
+ check() {
206
+ const r = this.runChecks()
207
+ const shown = r.problems.filter((p) => p.level !== 'info' || p.id !== 'skipped' || this.ui.verbose)
208
+ printProblems(this.ui, { problems: shown })
209
+ if (r.errors.length) {
210
+ this.ui.error(`${r.errors.length} problem(s) to fix first: nothing was sent.`)
211
+ return null
212
+ }
213
+ return r
214
+ }
215
+
216
+ /**
217
+ * Check, install and open. Returns true when the app is on screen.
218
+ * @param {{force?: boolean, full?: boolean}} [o] force: even when nothing changed since the last
219
+ * install; full: every file (no changed-files update)
220
+ */
221
+ async deploy({ force = false, full = false } = {}) {
222
+ const ui = this.ui
223
+ const r = this.check()
224
+ if (!r) return false
225
+ const hash = bundleHash(r.files)
226
+ if (!force && hash === this.lastHash) {
227
+ ui.info('No change in the files: nothing sent.')
228
+ return true
229
+ }
230
+ this.appId = r.appId
231
+ const mf = r.manifest.min_firmware
232
+ await this.connect()
233
+ if (typeof mf === 'string' && this.firmware && compareVersions(this.firmware, mf) < 0) {
234
+ ui.error(
235
+ `${r.appId} needs firmware ${mf} or newer; this Kamoji runs ${this.firmware} [firmware-too-old]`,
236
+ 'Update Kamoji in the Kamoji app (Settings > Firmware), or lower min_firmware if the app does not need it.',
237
+ )
238
+ return false
239
+ }
240
+ const st = this.lastList?.storage
241
+ if (st && r.bytes > st.total - st.used) {
242
+ ui.error(
243
+ `${r.appId} is ${kb(r.bytes)}; Kamoji has ${kb(Math.max(0, st.total - st.used))} free [no-space]`,
244
+ 'Remove a mini app in the Kamoji app (Apps), or make this one smaller.',
245
+ )
246
+ return false
247
+ }
248
+ this.busy = true
249
+ const t0 = Date.now()
250
+ const progress = (p) => ui.progress(`sending ${p.file} (${p.index + 1}/${p.files}): ${kb(p.sent)} of ${kb(p.total)}`)
251
+ try {
252
+ await this.startBleLogs()
253
+ await this.session.linkFast()
254
+ // Firmware 0.3.3: only the changed files, when the app is on Kamoji already (Enter = every file).
255
+ if (!full && !this.noUpdate && this.lastList?.apps.some((a) => a.id === r.appId)) {
256
+ const done = await this.updateChanged(r, hash, t0, progress)
257
+ if (done !== undefined) return done
258
+ }
259
+ const res = await this.session.install(r.appId, r.files, progress)
260
+ const t1 = Date.now()
261
+ this.lastHash = hash
262
+ const rate = res.bytes / Math.max(0.001, (t1 - t0) / 1000)
263
+ ui.ok(`Installed ${r.appId} ${res.version} in ${secs(t1 - t0)} (${r.files.length} file(s), ${kb(res.bytes)}, ${kb(rate)}/s).`)
264
+ await this.afterInstall(r, t0)
265
+ return true
266
+ } catch (e) {
267
+ this._explain(e)
268
+ return false
269
+ } finally {
270
+ this.busy = false
271
+ }
272
+ }
273
+
274
+ /**
275
+ * The changed-files update (APP_FILES, APP_EDIT, APP_PUT…, APP_DELETE…, APP_COMMIT). Returns true / false
276
+ * like deploy, or undefined when a full install must be done instead (older firmware, not installed, APP_EDIT
277
+ * refused, an incomplete file list).
278
+ */
279
+ async updateChanged(r, hash, t0, progress) {
280
+ const ui = this.ui
281
+ const there = await this.session.installedFiles(r.appId)
282
+ if (there.status === 'unsupported') {
283
+ this.noUpdate = true
284
+ this.note('no-update', NOTE_NO_UPDATE)
285
+ return undefined
286
+ }
287
+ if (there.status !== 'ok') return undefined
288
+ const { changed, deleted } = diffFiles(r.files, there.files)
289
+ if (!changed.length && !deleted.length) {
290
+ this.lastHash = hash
291
+ ui.info(`Nothing changed: ${r.appId} on Kamoji already has these files.`)
292
+ await this.open()
293
+ return true
294
+ }
295
+ const res = await this.session.update(r.appId, changed, deleted, progress)
296
+ if (res.fallback) {
297
+ if (res.fallback === 'unsupported') {
298
+ this.noUpdate = true
299
+ this.note('no-update', NOTE_NO_UPDATE)
300
+ } else ui.info(`Kamoji could not update only the changed files (${res.fallback}): sending every file.`)
301
+ return undefined
302
+ }
303
+ this.lastHash = hash
304
+ ui.ok(`Updated ${r.appId}: ${describeUpdate(changed, deleted)} in ${secs(Date.now() - t0)}.`)
305
+ await this.afterInstall(r, t0)
306
+ return true
307
+ }
308
+
309
+ async afterInstall(r, t0) {
310
+ const ui = this.ui
311
+ this.lastList = await this.session.listApps()
312
+ const app = this.lastList.apps.find((a) => a.id === r.appId)
313
+ if (app && !app.ok) {
314
+ ui.error(`Kamoji installed ${r.appId} but can't run it: ${app.reason || 'see the USB log'}.`)
315
+ return
316
+ }
317
+ if (r.manifest.ble !== undefined) {
318
+ const status = await this.session.status(r.appId)
319
+ if (status === 'pending_restart') {
320
+ if (this.reboot) {
321
+ ui.info('Its Bluetooth services are new or changed: restarting Kamoji (--reboot)…')
322
+ await this.restart()
323
+ return
324
+ }
325
+ ui.warn(`Its Bluetooth services are new or changed: they go live after a restart of Kamoji. ${this.restartHint}`)
326
+ } else if (status === 'profile_error') ui.error('Its Bluetooth services could not start: details in the USB log.')
327
+ }
328
+ await this.open(t0)
329
+ }
330
+
331
+ async open(t0) {
332
+ const r = await this.session.open(this.appId, this.lastList ?? undefined)
333
+ const total = t0 ? `, ${secs(Date.now() - t0)} after the first byte` : ''
334
+ this.ui.ok(`${this.appId} is on screen (mode ${r.mode}${r.confirmed ? '' : ', not confirmed'}${total}).`)
335
+ return r
336
+ }
337
+
338
+ async restart() {
339
+ await this.session.reboot()
340
+ this.connected = false
341
+ this.session.close()
342
+ await this.conn?.link.disconnect?.()
343
+ await sleep(8000)
344
+ for (let i = 0; i < 10 && !this.connected; i++) {
345
+ try {
346
+ await this.connect()
347
+ } catch {
348
+ await sleep(3000)
349
+ }
350
+ }
351
+ if (!this.connected) throw new KamojiError('timeout', 'Kamoji did not come back after the restart.')
352
+ if (this.appId) await this.open()
353
+ }
354
+
355
+ _explain(e) {
356
+ if (e instanceof KamojiError) this.ui.error(e.message, e.hint)
357
+ else this.ui.error(e?.message ?? String(e))
358
+ }
359
+
360
+ // ------------------------------------------------------------------ screenshots, USB log
361
+
362
+ async screenshot(dir) {
363
+ const name = `${this.appId ?? 'kamoji'}-${new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)}.jpg`
364
+ let jpeg
365
+ let via
366
+ if (this.serial) {
367
+ jpeg = await this.serial.screenshot(90)
368
+ via = 'USB'
369
+ } else {
370
+ await this.connect()
371
+ jpeg = await this.session.screenshot()
372
+ via = 'Bluetooth'
373
+ }
374
+ const file = await this.saveShot(dir, name, jpeg)
375
+ this.ui.ok(`Screenshot (${via}, ${kb(jpeg.length)}): ${file}`)
376
+ return file
377
+ }
378
+
379
+ /** The USB log line printer (filtered to the app unless verbose). */
380
+ logLine(line) {
381
+ if (this.ui.verbose) {
382
+ this.ui.raw(line)
383
+ return
384
+ }
385
+ const c = classify(line, this.appId)
386
+ if (!c) return
387
+ // The app's lines come over Bluetooth too (--ble-logs): USB adds only crashes, resets and boots.
388
+ if (this.logsOn !== null && this.connected && !['crash', 'boot', 'usb'].includes(c.kind)) return
389
+ this.ui.log(c.kind, c.text)
390
+ }
391
+
392
+ /** An app log line over Bluetooth (APP:LOG:…), printed like the USB one. */
393
+ bleLogLine(log) {
394
+ if (!this.bleLogs) return
395
+ const c = classifyBle(log, this.appId)
396
+ if (c) this.ui.log(c.kind, c.text)
397
+ }
398
+ }