dechatter 0.1.1 → 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.
package/web/widget.js CHANGED
@@ -3,7 +3,9 @@
3
3
  // and analysis are dechatter's Python running in a worker (engine.js).
4
4
 
5
5
  import { Mic } from './mic.js';
6
- import { STEPS, draw, read } from './wizard.js';
6
+ import { PHASE, Stepper } from './stepper.js';
7
+ import { chipLoad, feed, length, rate } from './units.js';
8
+ import { STEPS, draw, placehold, read, reveal } from './wizard.js';
7
9
 
8
10
  const params = new URLSearchParams(location.search);
9
11
  const token = params.get('token') ?? '';
@@ -20,34 +22,45 @@ const UNITS_TEXT = {
20
22
  mm: 'Lengths in mm: the machine is in G21.',
21
23
  in: 'Lengths in inches: the machine is in G20.',
22
24
  unknown: 'Lengths in mm. With the machine connected they follow its G20/G21 mode.',
23
- kept: 'Lengths in inches, as before the stopped job. The machine is now in G21: send G20 to put it back in inches.',
24
25
  };
25
- const KEEP_UNITS_KEY = 'dechatter.keep-units';
26
- const OWN_PROGRAM = /^dechatter-.*\.nc$/; // the names the engine gives its programs
27
26
  const cnc = {
28
27
  socket: null,
29
28
  link: 'connecting', // connecting | no-port | ready | offline
30
29
  port: '',
31
- workflow: null, // idle | running | paused; null until cncjs reports it
32
- program: '', // name of the G-code file cncjs has loaded
33
- pause: null, // { text, settled } while the program waits at an M0, else null
34
- units: null, // mm | in: how the wizard shows lengths; null until the machine's mode is known
35
- reported: null, // mm | in: the machine's G21/G20 mode as cncjs last reported it
36
- settled: null, // mm | in: the last report taken while no job ran; null until there is one
37
- // in from the start of one of this widget's jobs on an inch machine until the machine is
38
- // back in G20. Stored per machine, so a reload after a stopped job does not forget it.
39
- keep: null,
40
- lines: { received: 0, total: 0 }, // how far cncjs got through the loaded program
30
+ workflow: null, // idle | running | paused: cncjs's own sender; null until cncjs reports it
31
+ activeState: '', // the controller's state as cncjs last reported it: Idle, Run, Hold, Alarm…
32
+ subState: null, // with Hold, Grbl's Hold:N: 0 once the hold is complete
33
+ wpos: null, // its work position then, as cncjs reports it
34
+ reportInches: false, // the controller reports positions in inches (Grbl's $13=1)
35
+ // mm | in: the machine's G21/G20 mode as cncjs last reported it; null until it has. The
36
+ // wizard shows lengths in it and programs are written in it, so a job never changes it.
37
+ units: null,
41
38
  };
39
+ // The round the widget is running, one block at a time: { stepper, round, name }, else null.
40
+ // It is set the moment Start is pressed, so a second Start finds it and what cncjs reports
41
+ // while the round is being prepared reaches the stepper. The session stays pinned to it.
42
+ let run = null;
42
43
  const mic = new Mic();
43
44
  let boot = 'Starting'; // what the engine is loading; null once it is ready
44
45
  let fatal = ''; // why the engine could not start; nothing works without it
45
46
  let names = []; // sessions stored in this browser
46
47
  let current = localStorage.getItem(SESSION_KEY) ?? '';
47
48
  let state = null; // the current session, as the engine last reported it
48
- let editing = null; // { values, materials, step } while the setup wizard is open, else null
49
- let timeline = []; // what cncjs reported since the job last started; saved with the recording
50
- let busy = false; // an engine request is in flight
49
+ let editing = null; // { values, defaults, materials, computed, step } while the setup wizard is open, else null
50
+ let timeline = []; // the run's windows and events, saved with its recording
51
+ // Engine requests in flight; the controls wait while there are any.
52
+ let requests = 0;
53
+ const busy = () => requests > 0;
54
+
55
+ function requestDone() {
56
+ requests -= 1;
57
+ }
58
+ // The delete or reset confirmation: closed, being prepared, or open. While it is not
59
+ // closed, the session it names cannot change.
60
+ let dialog = 'closed';
61
+ // Whether the open session's setup loads ('loads' | 'refused'), as the engine checks it;
62
+ // null with no session open. Reset and Export need it to load; the rounds need not.
63
+ let setupStatus = null;
51
64
  let stockChoice = 'same'; // survives redraws: planning on the wrong face position cuts air or too deep
52
65
 
53
66
  // ---- engine (Python in a worker) -------------------------------------------------------
@@ -90,33 +103,62 @@ function showError(message) {
90
103
  $('error').hidden = !message;
91
104
  }
92
105
 
93
- // Run one request that answers with the session's new state.
94
- async function act(method, ...args) {
95
- busy = true;
106
+ // Run one request on a session that answers with its new state. The page takes that state
107
+ // only while the session is still the one open. Resolves whether the request succeeded.
108
+ async function actOn(name, method, ...args) {
109
+ requests += 1;
96
110
  render();
97
111
  try {
98
- state = await engine(method, current, ...args);
112
+ const next = await engine(method, name, ...args);
113
+ if (name === current) {
114
+ state = next;
115
+ }
99
116
  showError('');
117
+ return true;
100
118
  } catch (err) {
101
119
  showError(err.message);
120
+ return false;
102
121
  } finally {
103
- busy = false;
104
- syncRecording();
122
+ requestDone();
105
123
  render();
106
124
  }
107
125
  }
108
126
 
127
+ const act = (method, ...args) => actOn(current, method, ...args);
128
+
109
129
  async function openSession(name) {
110
130
  current = name;
111
131
  editing = null;
112
132
  state = null;
133
+ setupStatus = null;
113
134
  localStorage.setItem(SESSION_KEY, name);
114
135
  if (name) {
136
+ await checkSetup(name);
115
137
  await act('state');
116
138
  }
117
139
  render();
118
140
  }
119
141
 
142
+ // Whether a session's setup loads, apart from its rounds: a session whose rounds do not
143
+ // load can still be reset and exported.
144
+ async function checkSetup(name) {
145
+ requests += 1;
146
+ render();
147
+ try {
148
+ const { status } = await engine('setup_status', name);
149
+ if (name === current) {
150
+ setupStatus = status;
151
+ }
152
+ } catch (err) {
153
+ if (name === current) {
154
+ setupStatus = null;
155
+ showError(err.message);
156
+ }
157
+ } finally {
158
+ requestDone();
159
+ }
160
+ }
161
+
120
162
  async function newSession() {
121
163
  const name = window.prompt('Name this tool assembly, for example al-10mm-3fl');
122
164
  if (!name) {
@@ -128,6 +170,7 @@ async function newSession() {
128
170
  current = name.trim();
129
171
  localStorage.setItem(SESSION_KEY, current);
130
172
  state = null;
173
+ await checkSetup(current);
131
174
  await openWizard();
132
175
  showError('');
133
176
  } catch (err) {
@@ -139,10 +182,36 @@ async function newSession() {
139
182
  // Start the wizard on the session's stored setup. The form is redrawn even when it last
140
183
  // showed this same step, so nothing typed into an earlier wizard is left on screen.
141
184
  async function openWizard() {
142
- editing = { ...(await engine('setup_form', current)), step: 0 };
185
+ editing = { ...(await engine('setup_form', current)), computed: null, step: 0 };
143
186
  $('setup-form').dataset.key = '';
144
187
  }
145
188
 
189
+ // What the planner makes of the entries left empty, from what the wizard holds so far.
190
+ // Only shown as placeholders, filled in when the answer comes: the step is already drawn
191
+ // and may hold typing. Values the wizard cannot make sense of yet show none, and an answer
192
+ // overtaken by a later request is dropped.
193
+ async function preview(wizard) {
194
+ wizard.asked = (wizard.asked ?? 0) + 1;
195
+ const asked = wizard.asked;
196
+ let computed = null;
197
+ try {
198
+ computed = await engine('setup_preview', JSON.stringify(wizard.values));
199
+ } catch {
200
+ computed = null;
201
+ }
202
+ if (editing !== wizard || wizard.asked !== asked) {
203
+ return;
204
+ }
205
+ wizard.computed = computed;
206
+ placehold($('setup-form'), STEPS[wizard.step], units(), wizard);
207
+ }
208
+
209
+ function goToStep(step) {
210
+ editing.step = Math.min(Math.max(step, 0), STEPS.length - 1);
211
+ render();
212
+ preview(editing);
213
+ }
214
+
146
215
  async function editSetup() {
147
216
  try {
148
217
  await openWizard();
@@ -162,12 +231,21 @@ function keepStep() {
162
231
  }
163
232
 
164
233
  async function nextStep() {
234
+ reveal($('setup-form'));
165
235
  if (!$('setup-form').reportValidity()) {
166
236
  return;
167
237
  }
168
238
  keepStep();
169
239
  if (editing.step < STEPS.length - 1) {
170
- editing.step += 1;
240
+ goToStep(editing.step + 1);
241
+ return;
242
+ }
243
+ if (busy()) {
244
+ return; // already saving
245
+ }
246
+ // A job may be running one of this session's programs; a new setup could discard it.
247
+ if (cnc.workflow === 'running' || cnc.workflow === 'paused') {
248
+ showError('A job is running in cncjs. Save the setup once it has ended.');
171
249
  render();
172
250
  return;
173
251
  }
@@ -183,27 +261,145 @@ async function nextStep() {
183
261
 
184
262
  function previousStep() {
185
263
  keepStep();
186
- editing.step -= 1;
264
+ goToStep(editing.step - 1);
265
+ }
266
+
267
+ function download(blob, filename) {
268
+ const url = URL.createObjectURL(blob);
269
+ // cncjs sandboxes widget frames without allow-downloads, so the cncjs page itself
270
+ // (same origin) starts the download.
271
+ const host = window.parent.document;
272
+ const link = host.createElement('a');
273
+ link.href = url;
274
+ link.download = filename;
275
+ host.body.append(link);
276
+ link.click();
277
+ link.remove();
278
+ setTimeout(() => URL.revokeObjectURL(url), 60000);
279
+ }
280
+
281
+ // Both carry the report, whose lengths follow the machine's units (mm until known).
282
+ async function exportSession(name = current) {
283
+ try {
284
+ const bytes = await engine('export_zip', name, units());
285
+ download(new Blob([bytes], { type: 'application/zip' }), `${name}.zip`);
286
+ if (run?.name === name) {
287
+ showError(`Exported ${name} without round ${run.round}: it is still running, and is stored once it ends.`);
288
+ }
289
+ } catch (err) {
290
+ showError(err.message);
291
+ }
292
+ }
293
+
294
+ async function downloadReport() {
295
+ try {
296
+ const page = await engine('report_html', current, units());
297
+ download(new Blob([page], { type: 'text/html' }), `${current}-report.html`);
298
+ } catch (err) {
299
+ showError(err.message);
300
+ }
301
+ }
302
+
303
+ // The widget is running a round of this session.
304
+ function jobOf(name) {
305
+ return run !== null && run.name === name;
306
+ }
307
+
308
+ // Why a session cannot be deleted or reset now; '' when it can.
309
+ function busyRefusal(name, verb) {
310
+ if (mic.recording) {
311
+ return `A round is being recorded. ${verb} the session after the job.`;
312
+ }
313
+ if (jobOf(name)) {
314
+ return `A round of ${name} is running. ${verb} the session after it.`;
315
+ }
316
+ return '';
317
+ }
318
+
319
+ const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
320
+
321
+ // Deleting removes the session; resetting discards its rounds and keeps its setup. Both ask
322
+ // first, naming what goes, and offer Export. They read nothing but the folder, so a session
323
+ // that does not load (from dechatter 0.1.x, or damaged) can go too.
324
+ const ACTIONS = {
325
+ delete: {
326
+ verb: 'Delete',
327
+ question: (name, held) => `Delete session ${name}? It holds ${plural(held.rounds, 'round')} and ${plural(held.recordings, 'recording')}.`,
328
+ note: 'Deleting cannot be undone. Export keeps a copy as a zip.',
329
+ async run(name) {
330
+ names = await engine('delete', name);
331
+ await openSession('');
332
+ },
333
+ },
334
+ reset: {
335
+ verb: 'Reset',
336
+ question: (name, held) => `Reset session ${name}? Its ${plural(held.rounds, 'round')} and ${plural(held.recordings, 'recording')} are discarded; its setup stays, and planning starts again from round 1.`,
337
+ note: 'Resetting cannot be undone. Export keeps a copy as a zip.',
338
+ // On a refusal or failure the session shows as the engine has it now.
339
+ async run(name) {
340
+ try {
341
+ const after = await engine('reset', name);
342
+ if (name === current) {
343
+ state = after;
344
+ editing = null;
345
+ }
346
+ } catch (err) {
347
+ if (name === current) {
348
+ state = await engine('state', name).catch(() => state);
349
+ }
350
+ throw err;
351
+ }
352
+ },
353
+ },
354
+ };
355
+
356
+ async function ask(action) {
357
+ const name = current;
358
+ const { verb, question, note } = ACTIONS[action];
359
+ const refusal = busyRefusal(name, verb);
360
+ if (refusal) {
361
+ showError(refusal);
362
+ return;
363
+ }
364
+ dialog = 'preparing';
187
365
  render();
366
+ try {
367
+ // A session whose setup does not load (from dechatter 0.1.x, or damaged) cannot be
368
+ // exported; one whose rounds alone do not load can.
369
+ const loads = setupStatus === 'loads';
370
+ $('confirm-question').textContent = question(name, await engine('contents', name));
371
+ $('confirm-note').textContent = loads ? note : `${note.split('.')[0]}. This session cannot be exported: its setup does not load (it is from dechatter 0.1.x, or damaged).`;
372
+ $('confirm-export').hidden = !loads;
373
+ $('confirm-go').textContent = verb;
374
+ Object.assign($('confirm-dialog').dataset, { session: name, action });
375
+ $('confirm-dialog').showModal();
376
+ dialog = 'open';
377
+ } catch (err) {
378
+ dialog = 'closed';
379
+ showError(err.message);
380
+ render();
381
+ }
188
382
  }
189
383
 
190
- async function exportSession() {
384
+ async function confirmed() {
385
+ const { session: name, action } = $('confirm-dialog').dataset;
386
+ $('confirm-dialog').close();
387
+ const refusal = busyRefusal(name, ACTIONS[action].verb);
388
+ if (refusal) {
389
+ showError(refusal);
390
+ return;
391
+ }
392
+ requests += 1;
393
+ render();
191
394
  try {
192
- const bytes = await engine('export_zip', current);
193
- const url = URL.createObjectURL(new Blob([bytes], { type: 'application/zip' }));
194
- // cncjs sandboxes widget frames without allow-downloads, so the cncjs page itself
195
- // (same origin) starts the download.
196
- const host = window.parent.document;
197
- const link = host.createElement('a');
198
- link.href = url;
199
- link.download = `${current}.zip`;
200
- host.body.append(link);
201
- link.click();
202
- link.remove();
203
- setTimeout(() => URL.revokeObjectURL(url), 60000);
395
+ showError('');
396
+ await ACTIONS[action].run(name);
204
397
  } catch (err) {
205
398
  showError(err.message);
399
+ } finally {
400
+ requestDone();
206
401
  }
402
+ render();
207
403
  }
208
404
 
209
405
  async function importSession(file) {
@@ -267,30 +463,17 @@ function note(event, detail) {
267
463
  }
268
464
 
269
465
  function setPort(port) {
270
- cnc.port = port;
271
- cnc.link = port ? 'ready' : 'no-port';
272
- cnc.keep = port ? localStorage.getItem(keepKey()) : null;
273
- if (!port) {
274
- cnc.reported = null;
275
- cnc.settled = null;
466
+ // Another port may be another machine: its units are unknown until cncjs reports them.
467
+ if (port !== cnc.port) {
276
468
  showIn(null);
469
+ cnc.activeState = '';
470
+ run?.stepper.disconnected();
277
471
  }
472
+ cnc.port = port;
473
+ cnc.link = port ? 'ready' : 'no-port';
278
474
  render();
279
475
  }
280
476
 
281
- function keepKey() {
282
- return `${KEEP_UNITS_KEY}|${cncjsOrigin}|${cnc.port}`;
283
- }
284
-
285
- function hold(units) {
286
- cnc.keep = units;
287
- if (units) {
288
- localStorage.setItem(keepKey(), units);
289
- return;
290
- }
291
- localStorage.removeItem(keepKey());
292
- }
293
-
294
477
  function showIn(next) {
295
478
  if (next === cnc.units) {
296
479
  return;
@@ -301,36 +484,6 @@ function showIn(next) {
301
484
  cnc.units = next;
302
485
  }
303
486
 
304
- // The stopped job left G21 behind and the machine has not gone back to G20 since.
305
- function keptFromStoppedJob() {
306
- return cnc.keep !== null && cnc.workflow === 'idle' && cnc.reported !== null && cnc.reported !== cnc.keep;
307
- }
308
-
309
- // The machine's G20/G21 mode decides how the wizard shows lengths. Programs run in G21 and
310
- // put an inch machine back in G20 as their last step, so a job that ran to its end changes
311
- // nothing. A job stopped part-way leaves G21 behind, which is not the operator's choice: an
312
- // inch machine then stays in inches here until it goes back to G20 or the operator says
313
- // to follow the machine.
314
- function followMachine() {
315
- if (!cnc.reported || cnc.workflow === null) {
316
- return;
317
- }
318
- if (cnc.workflow !== 'idle') {
319
- // cncjs does not refresh the mode during a job; what it repeats right after one is
320
- // still this value, and must not pass for the machine going back to G20.
321
- cnc.settled = cnc.reported;
322
- return;
323
- }
324
- // Only one of this widget's programs ends by restoring G20.
325
- const finished = OWN_PROGRAM.test(cnc.program) && cnc.lines.total > 0 && cnc.lines.received >= cnc.lines.total;
326
- const wentBack = cnc.reported === cnc.keep && cnc.settled !== cnc.reported;
327
- if (cnc.keep && (finished || wentBack)) {
328
- hold(null);
329
- }
330
- cnc.settled = cnc.reported;
331
- showIn(cnc.keep ?? cnc.reported);
332
- }
333
-
334
487
  async function connectCncjs() {
335
488
  try {
336
489
  await loadScript(`${cncjsOrigin}/socket.io/socket.io.js`);
@@ -351,6 +504,7 @@ async function connectCncjs() {
351
504
  });
352
505
  socket.on('disconnect', () => {
353
506
  cnc.link = 'offline';
507
+ run?.stepper.disconnected(); // the machine finishes the one move it has, then stands
354
508
  render();
355
509
  });
356
510
  socket.on('error', (err) => {
@@ -360,49 +514,44 @@ async function connectCncjs() {
360
514
  });
361
515
  socket.on('serialport:open', ({ port }) => setPort(port));
362
516
  socket.on('serialport:close', () => setPort(''));
363
- socket.on('gcode:load', (name) => {
364
- cnc.program = name;
365
- render();
366
- });
367
- socket.on('gcode:unload', () => {
368
- cnc.program = '';
369
- render();
370
- });
371
- socket.on('sender:status', (status) => {
372
- cnc.program = status.name ?? cnc.program;
373
- cnc.lines = { received: status.received, total: status.total };
374
- followMachine();
375
- note('sender', { sent: status.sent, received: status.received, total: status.total });
376
- // A manual-spindle program stops at "M0 (set the spindle to N rpm, then resume)". cncjs
377
- // reports the pause as soon as it sends the line; the machine has only stopped once
378
- // everything sent was acknowledged.
379
- const reason = status.hold ? status.holdReason : null;
380
- const pause = reason?.data === 'M0'
381
- ? { text: /\(([^)]*)\)/.exec(reason.msg ?? '')?.[1] ?? 'program pause', settled: status.received >= status.sent }
382
- : null;
383
- if (JSON.stringify(pause) !== JSON.stringify(cnc.pause)) {
384
- cnc.pause = pause;
385
- render();
517
+ socket.on('serialport:read', (line) => {
518
+ // A refused block ends the run: the stepper holds and resets. An alarm ends it too, but
519
+ // the controller has stopped the machine itself: nothing is sent.
520
+ const text = String(line);
521
+ if (!run || !/^(error|ALARM):/.test(text)) {
522
+ return;
386
523
  }
524
+ note('controller', { line: text });
525
+ if (text.startsWith('ALARM:')) {
526
+ run.stepper.alarm(text);
527
+ return;
528
+ }
529
+ run.stepper.error(text);
530
+ });
531
+ socket.on('controller:settings', (_type, settings) => {
532
+ cnc.reportInches = String(settings?.settings?.$13 ?? '0') === '1';
387
533
  });
388
534
  socket.on('workflow:state', (workflow) => {
389
- if (workflow === 'running' && cnc.workflow !== 'paused') {
390
- timeline = [];
391
- }
392
- // Only this widget's programs switch the machine to G21. Another job starting changes
393
- // nothing: the machine is still in the G21 a stopped job left.
394
- if (workflow === 'running' && cnc.workflow === 'idle' && cnc.units === 'in' && OWN_PROGRAM.test(cnc.program)) {
395
- hold('in');
396
- }
397
535
  cnc.workflow = workflow;
398
- followMachine();
399
- note('workflow', { state: workflow });
400
- syncRecording();
536
+ // cncjs's own sender started a job while the widget runs a round: two senders on one
537
+ // machine. The widget's round stops.
538
+ if (workflow === 'running') {
539
+ run?.stepper.fail('cncjs started a job of its own while the round ran');
540
+ }
401
541
  render();
402
542
  });
403
543
  socket.on('controller:state', (_type, controller) => {
404
- cnc.reported = MACHINE_UNITS[controller?.parserstate?.modal?.units] ?? cnc.reported;
405
- followMachine();
544
+ showIn(MACHINE_UNITS[controller?.parserstate?.modal?.units] ?? cnc.units);
545
+ const status = controller?.status ?? {};
546
+ cnc.wpos = status.wpos ?? cnc.wpos;
547
+ if (status.activeState !== cnc.activeState) {
548
+ cnc.activeState = status.activeState ?? '';
549
+ if (run) {
550
+ note('controller', { state: cnc.activeState });
551
+ }
552
+ }
553
+ cnc.subState = status.subState ?? null;
554
+ run?.stepper.controller({ activeState: status.activeState, subState: cnc.subState, wpos: status.wpos });
406
555
  render();
407
556
  });
408
557
  }
@@ -420,54 +569,139 @@ window.addEventListener('message', (event) => {
420
569
  setPort(port);
421
570
  });
422
571
 
423
- // ---- recording follows the job ---------------------------------------------------------
572
+ // ---- the widget runs the round --------------------------------------------------------
424
573
 
425
574
  function plannedRound() {
426
575
  const last = state?.rounds.at(-1);
427
576
  return last && !last.analysed ? last : null;
428
577
  }
429
578
 
430
- // Record exactly while cncjs runs the planned round's program.
431
- function syncRecording() {
432
- if (!state || busy) {
433
- return;
579
+ // Why a round cannot start now; '' when it can.
580
+ function startRefusal() {
581
+ if (run) {
582
+ return 'A round is already running.';
434
583
  }
435
- const round = plannedRound();
436
- if (!mic.recording && round && cnc.workflow === 'running' && cnc.program === round.program) {
437
- if (!mic.open) {
438
- showError('The job is running but the microphone is not open, so this run cannot be analysed. Enable the microphone and run the round again.');
439
- return;
440
- }
441
- mic.record();
442
- act('record_start', round.round);
443
- return;
584
+ if (!mic.open) {
585
+ return 'Enable the microphone first.';
586
+ }
587
+ return machineRefusal();
588
+ }
589
+
590
+ // Why the machine cannot take a round now; '' when it can.
591
+ function machineRefusal() {
592
+ if (cnc.link !== 'ready') {
593
+ return 'Open the machine\'s port in cncjs first.';
444
594
  }
445
- if (mic.recording && cnc.workflow === 'idle' && cnc.link === 'ready') {
446
- const samples = mic.finish();
447
- act('record_stop', samples, mic.rate, JSON.stringify(timeline));
595
+ if (cnc.units === null) {
596
+ return 'cncjs has not reported G20 or G21 yet: say which the machine is in.';
448
597
  }
598
+ if (cnc.workflow === 'running' || cnc.workflow === 'paused') {
599
+ return 'cncjs is running a job of its own. Let it end, or stop it, first.';
600
+ }
601
+ if (cnc.activeState === 'Alarm') {
602
+ return 'The machine is in alarm. Clear it in cncjs (home, or unlock) first.';
603
+ }
604
+ if (cnc.activeState === 'Hold' || cnc.activeState === 'Door') {
605
+ return `The machine is in ${cnc.activeState}. Resume or reset it in cncjs first.`;
606
+ }
607
+ return '';
449
608
  }
450
609
 
451
- async function loadProgram(round) {
452
- busy = true;
610
+ const command = (...args) => cnc.socket.emit('command', cnc.port, ...args);
611
+
612
+ // Record while the widget runs the round one block at a time; then analyse what ran.
613
+ async function startRound(round) {
614
+ const refusal = startRefusal();
615
+ if (refusal) {
616
+ showError(refusal);
617
+ return;
618
+ }
619
+ const name = current;
620
+ // Before any wait: Start is now refused, and a lost link, an error or alarm line or a
621
+ // job of cncjs's own while the round is prepared ends the stepper before it sends a thing.
622
+ const stepper = new Stepper({
623
+ io: {
624
+ send: (lines) => command('gcode', lines),
625
+ feedhold: () => command('feedhold'),
626
+ cyclestart: () => command('cyclestart'),
627
+ reset: () => command('reset'),
628
+ },
629
+ reportInches: cnc.reportInches,
630
+ onChange: () => render(),
631
+ onWindow: ({ kind, ...window }) => note(kind, window),
632
+ });
633
+ // cncjs reports the controller only when it changes: start from what it said last.
634
+ stepper.controller({ activeState: cnc.activeState, subState: cnc.subState, wpos: cnc.wpos });
635
+ run = { stepper, round: round.round, name };
453
636
  render();
637
+ let blocks;
454
638
  try {
455
- // Capture has to be running before the job can start; the listener below does not wait.
456
- await mic.resume();
457
- const gcode = await engine('program', current, round.round, units());
458
- await new Promise((resolve, reject) => {
459
- cnc.socket.emit('command', cnc.port, 'gcode:load', round.program, gcode, {}, (err) =>
460
- err ? reject(new Error(`cncjs could not load the program: ${err.message ?? err}`)) : resolve(),
461
- );
462
- });
463
- cnc.program = round.program;
464
- showError('');
639
+ await mic.resume(); // capture has to be running before the first cut
640
+ blocks = await engine('steps', name, round.round, cnc.units);
465
641
  } catch (err) {
642
+ run = null;
466
643
  showError(err.message);
467
- } finally {
468
- busy = false;
469
644
  render();
645
+ return;
470
646
  }
647
+ // The machine may have changed during those waits: check again before recording.
648
+ if (notStarted(stepper)) {
649
+ return;
650
+ }
651
+ timeline = [];
652
+ mic.record();
653
+ note('record', { round: round.round, units: cnc.units });
654
+ if (!(await actOn(name, 'record_start', round.round))) {
655
+ mic.finish();
656
+ run = null;
657
+ render();
658
+ return;
659
+ }
660
+ // Once more: nothing has been sent, so a refusal now drops the recording unsaved.
661
+ const late = notStartedReason(stepper);
662
+ if (late) {
663
+ mic.finish();
664
+ await actOn(name, 'record_cancel');
665
+ run = null;
666
+ showError(late);
667
+ render();
668
+ return;
669
+ }
670
+ const outcome = await stepper.run(blocks);
671
+ note('run', { outcome, reason: stepper.reason });
672
+ const samples = mic.finish();
673
+ run = null;
674
+ await actOn(name, 'record_stop', samples, mic.rate, JSON.stringify(timeline));
675
+ if (outcome === PHASE.FAILED) {
676
+ // Both, when the analysis refused too: why the round ended, then why it was not analysed.
677
+ const analysis = $('error').hidden ? '' : ` ${$('error').textContent}`;
678
+ showError(`The round ended early: ${stepper.reason.replace(/\.$/, '')}. The cuts made before it count.${analysis}`);
679
+ }
680
+ }
681
+
682
+ // Why a round about to start cannot: the machine now refuses, the microphone closed, or
683
+ // the stepper was ended (a lost link, an error or alarm line, a cncjs job) before it sent
684
+ // a block; '' if it can.
685
+ function notStartedReason(stepper) {
686
+ if (stepper.finished) {
687
+ return `The round did not start: ${stepper.reason.replace(/\.$/, '')}. Nothing was sent.`;
688
+ }
689
+ if (!mic.open) {
690
+ return 'The round did not start: the microphone closed. Enable it, then press Start again.';
691
+ }
692
+ return machineRefusal();
693
+ }
694
+
695
+ // Whether the round cannot start after all; if so, says why and lets Start go again.
696
+ function notStarted(stepper) {
697
+ const reason = notStartedReason(stepper);
698
+ if (!reason) {
699
+ return false;
700
+ }
701
+ run = null;
702
+ showError(reason);
703
+ render();
704
+ return true;
471
705
  }
472
706
 
473
707
  // ---- rendering -------------------------------------------------------------------------
@@ -505,11 +739,27 @@ function renderSessions() {
505
739
  ...names.map((name) => el('option', { value: name }, name)),
506
740
  );
507
741
  select.value = names.includes(current) ? current : '';
508
- select.disabled = busy || mic.recording;
509
- $('summary').textContent = state?.summary ?? '';
510
- for (const id of ['edit-setup', 'export']) {
511
- $(id).disabled = !state || busy || mic.recording;
742
+ // A run records into its own session: another one cannot be opened, made or imported.
743
+ const pinned = busy() || dialog !== 'closed' || mic.recording || run !== null;
744
+ select.disabled = pinned;
745
+ $('new-session').disabled = pinned;
746
+ $('import').disabled = pinned;
747
+ $('summary').textContent = state ? summary(state) : '';
748
+ $('edit-setup').disabled = !state || pinned;
749
+ // Export reads only what is stored: it works while a round runs, without that round.
750
+ $('export').disabled = setupStatus !== 'loads' || busy();
751
+ // Also for a session that failed to load: deleting it is the way to be rid of it.
752
+ for (const [id, verb] of [['delete-session', 'Delete'], ['reset-session', 'Reset']]) {
753
+ $(id).disabled = !names.includes(current) || busy() || Boolean(busyRefusal(current, verb)) || dialog !== 'closed';
512
754
  }
755
+ // Reset keeps the setup, so the setup has to load; Delete is the way out otherwise.
756
+ $('reset-session').disabled ||= setupStatus !== 'loads';
757
+ }
758
+
759
+ // The session's tool and cut in one line, lengths in the machine's units.
760
+ function summary({ summary: s, spindle }) {
761
+ const depths = s.depths_mm.map((depth) => length(depth, units())).join(', ');
762
+ return `Ø ${length(s.diameter_mm, units())}, ${s.flutes} flutes, ${s.material}, depth ${depths}, ${chipLoad(s.chip_load_mm, units())} per tooth${spindle === 'manual' ? ', manual spindle' : ''}`;
513
763
  }
514
764
 
515
765
  function minutes(seconds) {
@@ -527,62 +777,174 @@ function renderSetup() {
527
777
  $('setup-hint').textContent = step.hint;
528
778
  $('setup-back').hidden = editing.step === 0;
529
779
  $('setup-next').textContent = editing.step === STEPS.length - 1 ? 'Save' : 'Next';
530
- $('setup-next').disabled = busy;
531
- const kept = keptFromStoppedJob();
532
- $('units').textContent = UNITS_TEXT[kept ? 'kept' : (cnc.units ?? 'unknown')];
533
- $('follow-machine').hidden = !kept;
780
+ $('setup-next').disabled = busy();
781
+ $('units').textContent = UNITS_TEXT[cnc.units ?? 'unknown'];
534
782
  // Redraw the fields only when the step or the machine's units change, so typing is not
535
783
  // interrupted otherwise. A change of units drops an entry that is only half typed.
536
784
  const key = `${current}|${editing.step}|${units()}`;
537
785
  if ($('setup-form').dataset.key !== key) {
538
- draw($('setup-form'), step, editing.values, units(), editing.materials);
786
+ draw($('setup-form'), step, editing.values, units(), editing);
539
787
  $('setup-form').dataset.key = key;
540
788
  }
541
789
  }
542
790
 
791
+ // Planning on the wrong face position cuts air or too deep: the choice survives redraws.
792
+ function stockSelect() {
793
+ const stock = el('select', {}, el('option', { value: 'same' }, 'same block'), el('option', { value: 'fresh' }, 'fresh block, face at Y0'));
794
+ stock.value = stockChoice;
795
+ stock.onchange = () => {
796
+ stockChoice = stock.value;
797
+ };
798
+ return stock;
799
+ }
800
+
801
+ const STEP_TEXT = {
802
+ setup: 'Setting up',
803
+ rapid: 'Moving to the next pass',
804
+ spindle: 'Setting the spindle speed',
805
+ plunge: 'Plunging beside the stock',
806
+ dwell: 'Spindle at speed in the air',
807
+ cut: 'Cutting',
808
+ retract: 'Backing off',
809
+ end: 'Finishing',
810
+ };
811
+
812
+ const HELD_LONG_S = 60;
813
+ const IDLE_AWAY_S = 5;
814
+
815
+ // Why the run seems stuck, pointing to Stop; '' while it is not.
816
+ function stall(stepper) {
817
+ const now = Date.now() / 1000;
818
+ if (stepper.phase === PHASE.HELD && now - stepper.holds.at(-1)[0] >= HELD_LONG_S) {
819
+ return `Held for ${Math.round(now - stepper.holds.at(-1)[0])} s. Resume, or Stop the round: the cuts made so far are analysed.`;
820
+ }
821
+ if (stepper.idleAway !== null && now - stepper.idleAway >= IDLE_AWAY_S) {
822
+ return 'The machine reports Idle, but not where this move ends. Check it in cncjs; if it will not move on, Stop the round: the cuts made so far are analysed.';
823
+ }
824
+ if (cnc.link !== 'ready') {
825
+ return 'The connection to cncjs or the machine is lost.';
826
+ }
827
+ return '';
828
+ }
829
+
830
+ // While the widget runs a round: where it is, and Hold, Resume, Continue and Stop. The panel
831
+ // is built once per run and updated in place: cncjs reports the controller several times a
832
+ // second, and controls rebuilt that often would lose a click.
833
+ let runView = null;
834
+
835
+ function buildRunView(current) {
836
+ const view = { run: current };
837
+ view.title = el('p', { className: 'recording' }, '', el('span', { id: 'recording-clock' }, '0 s'));
838
+ view.doing = el('p', {});
839
+ view.ask = el('p', { className: 'instruction', hidden: true });
840
+ view.askText = el('span', {});
841
+ view.continue = button('Continue', () => current.stepper.continueSpindle(), { className: 'primary' });
842
+ view.ask.append(view.askText, view.continue);
843
+ view.hold = button('Hold', () => current.stepper.hold());
844
+ view.resume = button('Resume', () => current.stepper.resume(), { className: 'primary' });
845
+ view.stop = button('Stop', () => current.stepper.stop(), { className: 'danger' });
846
+ view.stuck = el('p', { className: 'instruction', hidden: true });
847
+ view.root = el('div', {},
848
+ view.title,
849
+ view.doing,
850
+ view.ask,
851
+ el('p', {}, view.hold, ' ', view.resume, ' ', view.stop),
852
+ view.stuck,
853
+ el('p', { className: 'muted' }, 'Stop if a cut gets violent: the cuts made so far still count. Feed hold in cncjs works too.'),
854
+ );
855
+ return view;
856
+ }
857
+
858
+ function updateRunView(view) {
859
+ const { stepper, round } = view.run;
860
+ view.title.firstChild.textContent = `Recording round ${round}: `;
861
+ const block = stepper.block;
862
+ const where = block?.pass_id === null || block?.pass_id === undefined ? '' : `, pass ${block.pass_id}`;
863
+ const doing = stepper.phase === PHASE.HELD ? 'Held' : (STEP_TEXT[block?.step] ?? 'Starting');
864
+ view.doing.textContent = `${doing}${where} (block ${Math.max((stepper.index ?? 0) + 1, 1)} of ${stepper.total || '…'}).`;
865
+ const asking = stepper.phase === PHASE.SET_SPINDLE;
866
+ view.ask.hidden = !asking;
867
+ view.askText.textContent = asking ? `Set the spindle to ${block.rpm} rpm, then ` : '';
868
+ view.hold.hidden = stepper.phase !== PHASE.MOVING;
869
+ view.resume.hidden = stepper.phase !== PHASE.HELD;
870
+ // Nothing moves before the first block: a double-clicked Start must not land on Stop.
871
+ view.stop.disabled = stepper.phase === PHASE.READY || stepper.finished || stepper.phase === PHASE.STOPPING;
872
+ const stuck = stall(stepper);
873
+ view.stuck.hidden = !stuck;
874
+ view.stuck.textContent = stuck;
875
+ }
876
+
543
877
  function renderStep() {
544
878
  const step = $('step');
545
- step.replaceChildren();
546
879
  step.hidden = !state || editing !== null;
880
+ if (run && !step.hidden) {
881
+ if (runView?.run !== run) {
882
+ runView = buildRunView(run);
883
+ }
884
+ if (step.firstChild !== runView.root || step.childNodes.length !== 1) {
885
+ step.replaceChildren(runView.root);
886
+ }
887
+ updateRunView(runView);
888
+ return;
889
+ }
890
+ runView = null;
891
+ step.replaceChildren();
547
892
  if (step.hidden) {
548
893
  return;
549
894
  }
550
895
  const round = plannedRound();
551
896
 
552
- if (mic.recording) {
897
+ if (busy()) {
898
+ step.append(el('p', {}, 'Working…'));
899
+ return;
900
+ }
901
+
902
+ if (state.discarded_round !== null) {
903
+ step.append(el('p', {}, `Round ${state.discarded_round} had not been run and was planned from the old setup, so it was discarded.`));
904
+ }
905
+
906
+ if (state.next === 'converged') {
553
907
  step.append(
554
- el('p', { className: 'recording' }, `Recording round ${state.recording_round ?? ''}: `, el('span', { id: 'recording-clock' }, '0 s')),
555
- el('p', {}, 'Feed-hold and stop the job in cncjs if a cut gets violent. The passes that ran still count.'),
556
- ...(cnc.pause ? [el('p', { className: 'instruction' }, cnc.pause.settled ? `Now ${cnc.pause.text} in cncjs.` : 'Wait for the machine to stop.')] : []),
908
+ el('p', {}, 'Converged: no further cut is expected to add removal rate. The best stable cuts are below.'),
909
+ el('p', {}, button('Download the report', downloadReport, { className: 'primary' }), ' to print and keep with the tool.'),
557
910
  );
558
911
  return;
559
912
  }
560
913
 
561
- if (busy) {
562
- step.append(el('p', {}, 'Working…'));
914
+ if (state.next === 'sweep') {
915
+ const best = state.best[0];
916
+ const stock = stockSelect();
917
+ step.append(
918
+ el('p', {}, 'Converged: no further cut is expected to add removal rate. The best stable cuts are below.'),
919
+ el('p', {}, `One more round can find how hard the best cut (${best.rpm} rpm, ${length(best.width_mm, units())} wide, ${length(best.depth_mm, units())} deep) can be pushed: the same cut at rising chip loads, lightest first. Its cuts do not change the map.`),
920
+ el('p', {}, button('Plan the chip-load sweep', async () => {
921
+ await act('plan_sweep', stockChoice);
922
+ stockChoice = 'same';
923
+ }, { className: 'primary' }), ' on the ', stock),
924
+ el('p', {}, button('Download the report', downloadReport), ' as it stands.'),
925
+ );
563
926
  return;
564
927
  }
565
928
 
566
- if (state.next === 'converged') {
567
- step.append(el('p', {}, 'Converged: no further cut is expected to add removal rate. The best stable cuts are below.'));
929
+ if (state.next === 'setup') {
930
+ step.append(
931
+ el('p', {}, 'This session still holds the example setup, not your machine. Fill it in before planning.'),
932
+ el('p', {}, button('Open the setup wizard', editSetup, { className: 'primary' })),
933
+ );
568
934
  return;
569
935
  }
570
936
 
571
937
  if (state.next === 'plan') {
572
938
  const first = state.rounds.length === 0;
573
- const stock = el('select', {}, el('option', { value: 'same' }, 'same block'), el('option', { value: 'fresh' }, 'fresh block, face at Y0'));
574
- stock.value = stockChoice;
575
- stock.onchange = () => {
576
- stockChoice = stock.value;
577
- };
939
+ const stock = stockSelect();
578
940
  const shallower = !first && state.next_depth_mm !== state.depth_mm;
579
- const label = `Plan round ${state.rounds.length + 1}${shallower ? ` at ${state.next_depth_mm} mm depth` : ''}`;
941
+ const label = `Plan round ${state.rounds.length + 1}${shallower ? ` at ${length(state.next_depth_mm, units())} depth` : ''}`;
580
942
  const plan = button(label, async () => {
581
943
  await act('plan', first ? 'same' : stockChoice);
582
944
  stockChoice = 'same';
583
945
  }, { className: 'primary' });
584
946
  const next = shallower
585
- ? `${state.depth_mm} mm depth is settled. Next come cuts ${state.next_depth_mm} mm deep, starting from the widths that were stable.`
947
+ ? `${length(state.depth_mm, units(), { mmToo: true })} depth is settled. Next come cuts ${length(state.next_depth_mm, units(), { mmToo: true })} deep, starting from the widths that were stable.`
586
948
  : 'Plan the next cuts from what was measured.';
587
949
  step.append(el('p', {}, first ? 'Plan a coarse grid of test cuts.' : next));
588
950
  step.append(el('p', {}, plan, ...(first ? [] : [' on the ', stock])));
@@ -591,18 +953,28 @@ function renderStep() {
591
953
 
592
954
  const tests = round.passes.filter((p) => p.kind === 'test').length;
593
955
  const speedChanges = (r) => r.passes.filter((p, i) => i === 0 || p.rpm !== r.passes[i - 1].rpm).length;
594
- const loaded = cnc.program === round.program;
595
- const ready = cnc.link === 'ready' && cnc.workflow === 'idle' && mic.open;
596
- const load = button(loaded ? 'Reload program' : 'Load into cncjs', () => loadProgram(round), { className: loaded ? '' : 'primary', disabled: !ready });
956
+ const refusal = startRefusal();
957
+ const start = button('Start', () => startRound(round), { className: 'primary', disabled: Boolean(refusal) || busy() });
958
+ // cncjs reports the mode from the controller's parser state. Until it does, the operator
959
+ // can say which it is: the program sets that mode itself, so a wrong choice cannot
960
+ // misplace a cut, only leave the machine in the other mode afterwards.
961
+ const declare = el('select', {}, el('option', { value: '' }, 'machine units?'), el('option', { value: 'mm' }, 'mm (G21)'), el('option', { value: 'in' }, 'inches (G20)'));
962
+ declare.onchange = () => {
963
+ showIn(declare.value || null);
964
+ render();
965
+ };
966
+ const unknownUnits = cnc.link === 'ready' && cnc.units === null;
597
967
  step.append(
598
- el('p', {}, `Round ${round.round}: ${tests} test cuts ${round.depth_mm} mm deep, about ${minutes(round.run_time_s)} plus rapids. The front face ends at Y${round.face_y_end_mm}.`),
968
+ el('p', {}, `Round ${round.round}: ${tests} test cuts ${length(round.depth_mm, units(), { mmToo: true })} deep, about ${minutes(round.run_time_s)} plus rapids. The front face ends at Y ${length(round.face_y_end_mm, units(), { mmToo: true })}.`),
599
969
  el('ol', {},
600
970
  el('li', {}, 'Zero X at the left end of the stock, Y on its front face, Z on top.'),
601
- el('li', {}, load, mic.open ? '' : ' (enable the microphone first)'),
602
- el('li', {}, loaded ? 'Press play in cncjs. Recording starts and stops with the job. Keep this tab open.' : 'Press play in cncjs.'),
603
- ...(state.spindle === 'manual' ? [el('li', {}, `The program pauses before each of its ${speedChanges(round)} spindle speeds. Set the speed shown here, then resume in cncjs.`)] : []),
971
+ el('li', {}, start, ' runs the round from here, one move at a time, and records it. Keep this tab open.', ...(unknownUnits ? [' cncjs has not reported G20 or G21 yet; the machine is in ', declare] : [])),
972
+ ...(state.spindle === 'manual' ? [el('li', {}, `Before each of its ${speedChanges(round)} spindle speeds the round stops; set the speed shown here and press Continue.`)] : []),
604
973
  ),
605
974
  );
975
+ if (refusal && !unknownUnits) {
976
+ step.append(el('p', { className: 'muted' }, refusal));
977
+ }
606
978
  if (round.has_recording) {
607
979
  step.append(el('p', {}, 'The last run could not be analysed. Run the round again, or ', button('Analyse the last recording again', () => act('analyze', round.round))));
608
980
  }
@@ -615,15 +987,23 @@ function verdictCell(round, pass) {
615
987
  if (!round.analysed) {
616
988
  return el('td', {}, '');
617
989
  }
618
- const select = el('select', { disabled: busy },
619
- ...(pass.verdict ? [] : [el('option', { value: '' }, 'not heard')]),
990
+ if (pass.status === 'not run' && !pass.verdict) {
991
+ return el('td', { className: 'muted' }, 'not run');
992
+ }
993
+ const select = el('select', { disabled: busy() },
994
+ ...(pass.verdict ? [] : [el('option', { value: '' }, pass.status === 'likely not run' ? 'likely not run' : 'not heard')]),
620
995
  el('option', { value: 'stable' }, pass.status === 'aborted' ? 'stable (aborted)' : 'stable'),
621
996
  el('option', { value: 'unstable' }, pass.status === 'aborted' ? 'chatter (aborted)' : 'chatter'),
622
997
  );
623
998
  select.value = pass.verdict ?? '';
624
999
  select.title = pass.chatter_hz ? `peak ${Math.round(pass.chatter_hz)} Hz, ${pass.prominence_db} dB over the floor` : '';
625
1000
  select.onchange = () => act('set_verdict', round.round, pass.id, select.value);
626
- return el('td', { className: pass.verdict ?? '' }, select);
1001
+ // The spindle speed heard sits at the edge of the search around this pass's: the sound
1002
+ // may be another pass's. Worth a listen before trusting the verdict.
1003
+ const edge = pass.spindle_fit === 'edge'
1004
+ ? [el('span', { className: 'muted', title: 'The spindle speed heard is at the edge of what this pass could be: check it.' }, ' speed?')]
1005
+ : [];
1006
+ return el('td', { className: pass.verdict ?? '' }, select, ...edge);
627
1007
  }
628
1008
 
629
1009
  function renderRound() {
@@ -632,14 +1012,15 @@ function renderRound() {
632
1012
  if (!round) {
633
1013
  return;
634
1014
  }
635
- $('round-title').textContent = `Round ${round.round}${round.analysed ? ' results' : ''}, ${round.depth_mm} mm deep`;
1015
+ const kind = round.planner === 'sweep' ? ' (chip-load sweep)' : '';
1016
+ $('round-title').textContent = `Round ${round.round}${kind}${round.analysed ? ' results' : ''}, ${length(round.depth_mm, units(), { mmToo: true })} deep`;
636
1017
  $('passes').replaceChildren(
637
1018
  ...round.passes.map((p) =>
638
1019
  el('tr', { className: p.kind === 'test' ? '' : 'prep' },
639
1020
  el('td', {}, String(p.id)),
640
1021
  el('td', {}, String(p.rpm)),
641
- el('td', {}, p.width_mm.toFixed(2)),
642
- el('td', {}, String(Math.round(p.feed_mm_min))),
1022
+ el('td', {}, length(p.width_mm, units())),
1023
+ el('td', {}, feed(p.feed_mm_min, units())),
643
1024
  el('td', {}, p.p_stable === null ? '' : p.p_stable.toFixed(2)),
644
1025
  verdictCell(round, p),
645
1026
  ),
@@ -653,11 +1034,11 @@ function renderMap() {
653
1034
  if ($('map-section').hidden) {
654
1035
  return;
655
1036
  }
656
- $('map-title').textContent = `Stability map at ${state.depth_mm} mm depth`;
1037
+ $('map-title').textContent = `Stability map at ${length(state.depth_mm, units(), { mmToo: true })} depth`;
657
1038
  const { speeds, widths, p } = state.map;
658
1039
  const canvas = $('map');
659
1040
  const ctx = canvas.getContext('2d');
660
- const pad = { left: 40, bottom: 16, top: 4, right: 4 };
1041
+ const pad = { left: units() === 'in' ? 56 : 40, bottom: 16, top: 4, right: 4 };
661
1042
  const w = canvas.width - pad.left - pad.right;
662
1043
  const h = canvas.height - pad.top - pad.bottom;
663
1044
  ctx.clearRect(0, 0, canvas.width, canvas.height);
@@ -698,9 +1079,9 @@ function renderMap() {
698
1079
  ctx.fillText(`${speeds[0]} rpm`, pad.left, pad.top + h + 3);
699
1080
  ctx.textAlign = 'right';
700
1081
  ctx.fillText(String(speeds.at(-1)), pad.left + w, pad.top + h + 3);
701
- ctx.fillText(`${widths.at(-1)}`, pad.left - 3, pad.top);
1082
+ ctx.fillText(length(widths.at(-1), units()).split(' ')[0], pad.left - 3, pad.top);
702
1083
  ctx.textBaseline = 'bottom';
703
- ctx.fillText(`${widths[0]} mm`, pad.left - 3, pad.top + h);
1084
+ ctx.fillText(length(widths[0], units()), pad.left - 3, pad.top + h);
704
1085
  }
705
1086
 
706
1087
  function renderBest() {
@@ -710,13 +1091,23 @@ function renderBest() {
710
1091
  ...best.map((b) =>
711
1092
  el('tr', {},
712
1093
  el('td', {}, String(b.rpm)),
713
- el('td', {}, `${b.width_mm.toFixed(2)} mm`),
714
- el('td', {}, `${b.depth_mm} mm`),
715
- el('td', {}, String(b.feed_mm_min)),
716
- el('td', {}, b.mrr_cm3_min.toFixed(2)),
1094
+ el('td', {}, length(b.width_mm, units())),
1095
+ el('td', {}, length(b.depth_mm, units())),
1096
+ el('td', {}, feed(b.feed_mm_min, units())),
1097
+ el('td', {}, rate(b.mrr_cm3_min, units())),
717
1098
  ),
718
1099
  ),
719
1100
  );
1101
+ const sweep = state?.sweep;
1102
+ $('sweep-result').hidden = !sweep || best.length === 0;
1103
+ if (!sweep) {
1104
+ return;
1105
+ }
1106
+ const u = units();
1107
+ const where = `at ${sweep.rpm} rpm, ${length(sweep.width_mm, u)} wide and ${length(sweep.depth_mm, u)} deep`;
1108
+ $('sweep-result').textContent = sweep.chip_load_mm === null
1109
+ ? `Chip-load sweep: ${where}, even its lightest pass chattered. Keep the session's ${chipLoad(sweep.session_chip_load_mm, u, { mmToo: true })} per tooth.`
1110
+ : `Chip-load sweep: ${where}, the cut stayed stable up to ${chipLoad(sweep.chip_load_mm, u, { mmToo: true })} per tooth (the session used ${chipLoad(sweep.session_chip_load_mm, u)}): feed ${feed(sweep.feed_mm_min, u, { mmToo: true })}, ${rate(sweep.mrr_cm3_min, u, { mmToo: true })}.`;
720
1111
  }
721
1112
 
722
1113
  function render() {
@@ -746,17 +1137,28 @@ $('setup-form').onsubmit = (event) => {
746
1137
  event.preventDefault();
747
1138
  nextStep();
748
1139
  };
749
- $('follow-machine').onclick = () => {
750
- hold(null);
751
- followMachine();
752
- render();
753
- };
754
1140
  $('cancel-setup').onclick = () => {
755
1141
  editing = null;
756
1142
  showError('');
757
1143
  render();
758
1144
  };
759
- $('export').onclick = exportSession;
1145
+ $('export').onclick = () => exportSession();
1146
+ $('delete-session').onclick = () => ask('delete');
1147
+ $('reset-session').onclick = () => ask('reset');
1148
+ // The page's error line is behind the dialog: say there how the export went.
1149
+ $('confirm-dialog').addEventListener('close', () => {
1150
+ dialog = 'closed';
1151
+ render();
1152
+ });
1153
+ $('confirm-export').onclick = async () => {
1154
+ showError('');
1155
+ await exportSession($('confirm-dialog').dataset.session);
1156
+ const { verb } = ACTIONS[$('confirm-dialog').dataset.action];
1157
+ $('confirm-note').textContent = $('error').hidden ? `Exported. ${verb} it now, or cancel.` : `Not exported: ${$('error').textContent}`;
1158
+ };
1159
+ $('confirm-go').onclick = confirmed;
1160
+ $('confirm-cancel').onclick = () => $('confirm-dialog').close();
1161
+ $('download-report').onclick = downloadReport;
760
1162
  $('import').onclick = () => $('import-file').click();
761
1163
  $('import-file').onchange = () => {
762
1164
  const [file] = $('import-file').files;
@@ -784,8 +1186,9 @@ for (const type of ['pointerdown', 'pointerup', 'keydown']) {
784
1186
  }
785
1187
 
786
1188
  // Leaving mid-recording loses the run: the samples are only in this page.
1189
+ // Leaving mid-round loses the recording; the machine finishes its one move and stands.
787
1190
  window.addEventListener('beforeunload', (event) => {
788
- if (mic.recording) {
1191
+ if (run || mic.recording) {
789
1192
  event.preventDefault();
790
1193
  }
791
1194
  });
@@ -794,6 +1197,8 @@ render();
794
1197
  connectCncjs();
795
1198
  openMic(localStorage.getItem(DEVICE_KEY) || undefined);
796
1199
  setInterval(renderLevel, LEVEL_MS);
1200
+ // cncjs reports only changes: a run that stalls gets no news, so its panel is redrawn anyway.
1201
+ setInterval(() => run && renderStep(), 1000);
797
1202
 
798
1203
  try {
799
1204
  names = await engine('names');