clavarium 0.2.388-next.1 → 0.2.389-next.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.
@@ -61,6 +61,20 @@ set -euo pipefail
61
61
  export LC_ALL=C
62
62
 
63
63
  MULTIPASS="multipass"
64
+ # THE WAY DOWN (vm halt, vm hardstop): how long each step is given before the next, in seconds --
65
+ # a polite stop, a stop by force asked of the VM manager, SIGTERM to the machine's own qemu, SIGKILL
66
+ # to it; then how long multipass may take to answer a list, and to see the machine stopped after.
67
+ HALT_POLITE="60"
68
+ HALT_FORCE="30"
69
+ HALT_TERM="5"
70
+ HALT_KILL="5"
71
+ HALT_LIST="20"
72
+ HALT_SETTLE="10"
73
+ # The bounds of the plain verbs (a VM manager that hangs must not hold a call for ever).
74
+ START_SECONDS="180"
75
+ STOP_SECONDS="120"
76
+ KILL_SECONDS="60"
77
+ SUSPEND_SECONDS="120"
64
78
  IMAGE="24.04"
65
79
  DISK="8G"
66
80
  LAUNCH_SECONDS="900"
@@ -178,7 +192,8 @@ while [ $# -gt 0 ]; do
178
192
  TEST="${2:-}"; case "$TEST" in /*) : ;; *) refuse "--test takes an absolute path" ;; esac
179
193
  DATA="$TEST"; MNT="$TEST"; WIFI_STATE="$TEST/wifi"; NM_KEYFILES="$TEST/system-connections"; WIFI_WAIT="3"; WIFI_UP_WAIT="3"; WIFI_STEP="0.2"
180
194
  HAND_STATE="$TEST/network"; NETPLAN_DIR="$TEST/netplan"; HAND_WAIT="3"; SYS_NET="$TEST/sys-net"
181
- MESH_DATA="$TEST/mesh"; MESH_STATE="$TEST/meshcentral"; CADDYFILE="$TEST/Caddyfile"; MESH_CADDY="$TEST/clavarium-meshcentral.caddy"; shift 2 ;;
195
+ MESH_DATA="$TEST/mesh"; MESH_STATE="$TEST/meshcentral"; CADDYFILE="$TEST/Caddyfile"; MESH_CADDY="$TEST/clavarium-meshcentral.caddy"
196
+ HALT_POLITE="2"; HALT_FORCE="2"; HALT_TERM="1"; HALT_KILL="2"; HALT_LIST="2"; HALT_SETTLE="2"; shift 2 ;;
182
197
  *) break ;;
183
198
  esac
184
199
  done
@@ -219,12 +234,113 @@ vm_of() { is_name "${1#clv-}" && [ "$1" != "${1#clv-}" ] || refuse "not one of o
219
234
  vm_qemu_pids() {
220
235
  local want="$1" pid vm
221
236
  for pid in $(pgrep qemu-system 2>/dev/null || true); do
237
+ # A process that has ended but not yet been reaped (a zombie) holds no memory: it is gone.
238
+ [ "$(sed -n 's/^State:[[:space:]]*\([A-Z]\).*/\1/p' "/proc/$pid/status" 2>/dev/null)" = "Z" ] && continue
222
239
  vm="$(tr '\0' '\n' < "/proc/$pid/cmdline" 2>/dev/null | grep -oE '/instances/clv(shelf)?-[a-z0-9-]+/' | head -1 | cut -d/ -f3)" || vm=""
223
240
  [ "$vm" = "$want" ] && printf '%s\n' "$pid"
224
241
  done
225
242
  }
226
243
  # No qemu left for this machine after a short grace: its RAM has been freed.
227
244
  vm_freed() { local v="$1" i; for i in $(seq 1 24); do [ -z "$(vm_qemu_pids "$v")" ] && return 0; sleep 0.5; done; return 1; }
245
+ # THIS machine's qemu, PROVEN just before a signal: a process named qemu-system* whose command line
246
+ # holds a disk in this instance's own directory. Read again right before each signal, so that a
247
+ # process id reused meanwhile, or another machine's qemu, is never hit.
248
+ vm_qemu_is() {
249
+ local pid="$1" want="$2" comm vm
250
+ [[ "$pid" =~ ^[0-9]+$ ]] || return 1
251
+ comm="$(cat "/proc/$pid/comm" 2>/dev/null)" || return 1
252
+ [[ "$comm" == qemu-system* ]] || return 1
253
+ vm="$(tr '\0' '\n' < "/proc/$pid/cmdline" 2>/dev/null | grep -oE '/instances/clv(shelf)?-[a-z0-9-]+/' | head -1 | cut -d/ -f3)" || return 1
254
+ [ "$vm" = "$want" ]
255
+ }
256
+ # The memory its qemu holds (kB, its resident set), counted before the way down: what is freed.
257
+ vm_rss_kb() { local pid kb total=0; for pid in "$@"; do kb="$(sed -n 's/^VmRSS:[[:space:]]*\([0-9]*\) kB$/\1/p' "/proc/$pid/status" 2>/dev/null)" || kb=""; total=$((total + ${kb:-0})); done; echo "$total"; }
258
+ gb_of_kb() { awk -v k="$1" 'BEGIN { printf "%.1fG", k / 1048576 }'; }
259
+ # What multipass says of it, bounded: its state, "absent" (listed, not there), or "unknown" (mute).
260
+ vm_state_of() {
261
+ local out
262
+ out="$(timeout "$HALT_LIST" "$MULTIPASS" list --format csv 2>/dev/null)" || { echo "unknown"; return 0; }
263
+ out="$(printf '%s\n' "$out" | awk -F, -v n="$1" '$1 == n { print $2; exit }')"
264
+ echo "${out:-absent}"
265
+ }
266
+ # Nothing left to stop: no qemu of it (after a grace of $2 seconds), and not asleep (an asleep
267
+ # machine has no qemu but is not stopped: only a stop by force ends its saved state).
268
+ halt_gone() {
269
+ local v="$1" i
270
+ for i in $(seq 0 "$2"); do [ -z "$(vm_qemu_pids "$v")" ] && break; [ "$i" -lt "$2" ] && sleep 1; done
271
+ [ -z "$(vm_qemu_pids "$v")" ] || return 1
272
+ [ "$(vm_state_of "$v")" != "Suspended" ]
273
+ }
274
+ # One step that asks the VM manager, in the background, so that a TERM of this program (the server
275
+ # moving on: "Force now") ends it at once instead of leaving it to run its whole bound.
276
+ HALT_CHILD=""
277
+ halt_run() { local rc=0; "$@" >/dev/null 2>&1 & HALT_CHILD=$!; wait "$HALT_CHILD" || rc=$?; HALT_CHILD=""; return "$rc"; }
278
+ # A signal to its qemu, each process proven first; then waited for, up to $3 seconds.
279
+ halt_signal() {
280
+ local v="$1" sig="$2" wait="$3" pid i
281
+ for pid in $(vm_qemu_pids "$v"); do vm_qemu_is "$pid" "$v" && kill "-$sig" "$pid" 2>/dev/null || true; done
282
+ for i in $(seq 1 $((wait * 4))); do [ -z "$(vm_qemu_pids "$v")" ] && return 0; sleep 0.25; done
283
+ [ -z "$(vm_qemu_pids "$v")" ]
284
+ }
285
+ # THE WAY DOWN, from step $2 to step $3 (polite, force, term, kill), then the check. One line per
286
+ # step on the output, for the server and its page:
287
+ # step <id> start
288
+ # step <id> <ok|fail|timeout|skip> <seconds>s [why]
289
+ # step check <ok|fail> <seconds>s [qemu-left|mute|state <S>] freed <G>
290
+ # Before each step: its qemu already gone (and the machine not asleep), the rest is skipped.
291
+ # Exit 0 only when no qemu is left for it and multipass says Stopped.
292
+ halt_steps() {
293
+ local v="$1" from="$2" until="$3" kb s on="no" t rc res grace=0 state
294
+ trap '[ -n "$HALT_CHILD" ] && kill "$HALT_CHILD" 2>/dev/null; exit 143' TERM INT
295
+ # shellcheck disable=SC2046
296
+ kb="$(vm_rss_kb $(vm_qemu_pids "$v"))"
297
+ for s in polite force term kill; do
298
+ [ "$s" = "$from" ] && on="yes"
299
+ [ "$on" = "yes" ] || continue
300
+ if halt_gone "$v" "$grace"; then echo "step $s skip 0s gone"; break; fi
301
+ grace=0
302
+ echo "step $s start"; t=$SECONDS; rc=0
303
+ case "$s" in
304
+ polite) if [ -z "$(vm_qemu_pids "$v")" ]; then echo "step polite skip 0s asleep"; [ "$s" = "$until" ] && break; continue; fi
305
+ halt_run timeout "$HALT_POLITE" "$MULTIPASS" stop "$v" || rc=$? ;;
306
+ force) halt_run timeout "$HALT_FORCE" "$MULTIPASS" stop --force "$v" || rc=$? ;;
307
+ term) [ -n "$(vm_qemu_pids "$v")" ] || { echo "step term skip 0s none"; [ "$s" = "$until" ] && break; continue; }
308
+ halt_signal "$v" TERM "$HALT_TERM" || rc=124 ;;
309
+ kill) halt_signal "$v" KILL "$HALT_KILL" || rc=124 ;;
310
+ esac
311
+ case "$rc" in 0) res="ok"; grace=3 ;; 124) res="timeout" ;; *) res="fail" ;; esac
312
+ echo "step $s $res $((SECONDS - t))s"
313
+ [ "$s" = "$until" ] && break
314
+ done
315
+ echo "step check start"; t=$SECONDS
316
+ for _ in $(seq 0 "$HALT_SETTLE"); do
317
+ state="$(vm_state_of "$v")"
318
+ [ -z "$(vm_qemu_pids "$v")" ] && [ "$state" = "Stopped" ] && { echo "step check ok $((SECONDS - t))s freed $(gb_of_kb "$kb")"; exit 0; }
319
+ # A VM manager that does not answer is not asked again and again.
320
+ [ "$state" = "unknown" ] && break
321
+ sleep 1
322
+ done
323
+ if [ -n "$(vm_qemu_pids "$v")" ]; then echo "step check fail $((SECONDS - t))s qemu-left freed 0.0G"
324
+ elif [ "$state" = "unknown" ]; then echo "step check fail $((SECONDS - t))s mute freed $(gb_of_kb "$kb")"
325
+ else echo "step check fail $((SECONDS - t))s state $state freed $(gb_of_kb "$kb")"; fi
326
+ exit 1
327
+ }
328
+ halt_plan() {
329
+ local v="$1" from="$2" until="$3" s on="no"
330
+ echo "before each step: if no qemu is left for $v (and it is not asleep), straight to the check"
331
+ for s in polite force term kill; do
332
+ [ "$s" = "$from" ] && on="yes"
333
+ [ "$on" = "yes" ] || continue
334
+ case "$s" in
335
+ polite) echo "step polite: timeout $HALT_POLITE $MULTIPASS stop $v" ;;
336
+ force) echo "step force: timeout $HALT_FORCE $MULTIPASS stop --force $v" ;;
337
+ term) echo "step term: kill -TERM <the qemu of $v, proven by its disk>, waited ${HALT_TERM}s" ;;
338
+ kill) echo "step kill: kill -KILL <the qemu of $v, proven by its disk>, waited ${HALT_KILL}s" ;;
339
+ esac
340
+ [ "$s" = "$until" ] && break
341
+ done
342
+ echo "step check: no qemu left for $v, and $MULTIPASS says Stopped (within ${HALT_SETTLE}s)"
343
+ }
228
344
  number() { [[ "$1" =~ ^[0-9]{1,6}$ ]] || refuse "not a number: ${1:-<empty>}"; }
229
345
  # A disk or partition named by its device: /dev/sdX, /dev/vdX, /dev/nvmeNnN(pN),
230
346
  # /dev/xvdX, /dev/mmcblkN(pN), with a digit or two at the end; a loop device only
@@ -794,9 +910,31 @@ case "$AREA $VERB" in
794
910
  "vm info")
795
911
  [ $# -eq 1 ] || usage; vm_of "$1"
796
912
  run "$MULTIPASS" info "$1" --format json ;;
797
- "vm start"|"vm stop")
913
+ "vm start")
914
+ [ $# -eq 1 ] || usage; vm_of "$1"
915
+ run timeout "$START_SECONDS" "$MULTIPASS" start "$1" ;;
916
+ "vm stop")
798
917
  [ $# -eq 1 ] || usage; vm_of "$1"
799
- run "$MULTIPASS" "$VERB" "$1" ;;
918
+ run timeout "$STOP_SECONDS" "$MULTIPASS" stop "$1" ;;
919
+ "vm halt")
920
+ # <vm> [<from> [<until>]]: STOPPED FOR SURE, step by step (halt_steps): a polite stop, a stop
921
+ # by force, then its own qemu ended -- SIGTERM, SIGKILL -- without the VM manager, which may be
922
+ # the thing that hangs. <from>: where to begin (the server moves on with it, "Force now");
923
+ # <until>: the last step tried before the check (force: the VM manager's own ways only).
924
+ [ $# -ge 1 ] && [ $# -le 3 ] || usage; vm_of "$1"
925
+ from="${2:-polite}"; until="${3:-kill}"
926
+ [[ "$from" =~ ^(polite|force|term|kill)$ ]] || refuse "not a step: $from"
927
+ [[ "$until" =~ ^(force|kill)$ ]] || refuse "not a last step: $until"
928
+ [ "$from" = "kill" ] && [ "$until" = "force" ] && refuse "kill comes after force"
929
+ [ "$from" = "term" ] && [ "$until" = "force" ] && refuse "term comes after force"
930
+ if [ "$SAY" = "yes" ]; then halt_plan "$1" "$from" "$until"; exit 0; fi
931
+ halt_steps "$1" "$from" "$until" ;;
932
+ "vm hardstop")
933
+ # <vm>: "Force stop", as a power cut: nothing is asked of the VM manager. Its own qemu,
934
+ # proven by its disk, is sent SIGTERM, then SIGKILL; then the check, as for vm halt.
935
+ [ $# -eq 1 ] || usage; vm_of "$1"
936
+ if [ "$SAY" = "yes" ]; then halt_plan "$1" term kill; exit 0; fi
937
+ halt_steps "$1" term kill ;;
800
938
  "vm suspend")
801
939
  # Veille: suspend must save the machine's state AND free its RAM by ending
802
940
  # its qemu process. Multipass saves the state reliably but at times leaves
@@ -808,17 +946,22 @@ case "$AREA $VERB" in
808
946
  # gone after the first suspend and none of this runs.
809
947
  [ $# -eq 1 ] || usage; vm_of "$1"
810
948
  if [ "$SAY" = "yes" ]; then
811
- printf '%s\n' "$MULTIPASS suspend $1" \
949
+ printf '%s\n' "timeout $SUSPEND_SECONDS $MULTIPASS suspend $1" \
812
950
  "if its qemu still holds the RAM: $MULTIPASS start $1 && $MULTIPASS suspend $1 (wake+resleep)" \
813
951
  "if it still does: $MULTIPASS stop $1 (free it; it wakes by a boot)"
814
952
  exit 0
815
953
  fi
816
- "$MULTIPASS" suspend "$1" || refuse "suspend of $1 failed"
817
- vm_freed "$1" && exit 0
818
- "$MULTIPASS" start "$1" >/dev/null 2>&1 && "$MULTIPASS" suspend "$1" >/dev/null 2>&1
819
- vm_freed "$1" && exit 0
820
- "$MULTIPASS" stop "$1" >/dev/null 2>&1 || true
821
- vm_freed "$1" && exit 0
954
+ # One line per step, as vm halt says them (the server shows them to the page).
955
+ echo "step suspend start"; t=$SECONDS
956
+ timeout "$SUSPEND_SECONDS" "$MULTIPASS" suspend "$1" || { echo "step suspend fail $((SECONDS - t))s"; refuse "suspend of $1 failed"; }
957
+ vm_freed "$1" && { echo "step suspend ok $((SECONDS - t))s"; exit 0; }
958
+ echo "step suspend ok $((SECONDS - t))s qemu-left"; echo "step resleep start"; t=$SECONDS
959
+ timeout "$START_SECONDS" "$MULTIPASS" start "$1" >/dev/null 2>&1 && timeout "$SUSPEND_SECONDS" "$MULTIPASS" suspend "$1" >/dev/null 2>&1
960
+ vm_freed "$1" && { echo "step resleep ok $((SECONDS - t))s"; exit 0; }
961
+ echo "step resleep fail $((SECONDS - t))s"; echo "step stop start"; t=$SECONDS
962
+ timeout "$STOP_SECONDS" "$MULTIPASS" stop "$1" >/dev/null 2>&1 || true
963
+ vm_freed "$1" && { echo "step stop ok $((SECONDS - t))s"; exit 0; }
964
+ echo "step stop fail $((SECONDS - t))s"
822
965
  refuse "suspended $1 but its memory was not freed (its qemu stayed); the VM manager likely needs a restart" ;;
823
966
  "vm reclaim")
824
967
  # Free a machine that is ASLEEP but whose qemu still holds the RAM -- a
@@ -843,7 +986,7 @@ case "$AREA $VERB" in
843
986
  # A stop that does not wait for the system inside: asked only after a
844
987
  # clean stop hung or failed (a restart the owner asked for).
845
988
  [ $# -eq 1 ] || usage; vm_of "$1"
846
- run "$MULTIPASS" stop --force "$1" ;;
989
+ run timeout "$KILL_SECONDS" "$MULTIPASS" stop --force "$1" ;;
847
990
  "vm set")
848
991
  # <vm> memory <megabytes> | <vm> disk <gigabytes> | <vm> cpus <n>. The VM manager
849
992
  # takes it only from a stopped machine, and a disk only ever grows:
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.388-next.1",
3
+ "version": "0.2.389-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.388-next.1",
9
+ "version": "0.2.389-next.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.388-next.1",
3
+ "version": "0.2.389-next.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "A conversation is a VM with a terminal in it. Everything else is a folder.",
package/server/api.mjs CHANGED
@@ -8,6 +8,11 @@
8
8
  * POST /api/conversations/<name>/restart a clean stop (by force if it hangs), then a start
9
9
  * POST /api/conversations/<name>/machine {memoryMb?, diskGb?, cpus?}: stopped, set, started again (202);
10
10
  * asleep: checked and kept for its wake, as `sizeAtWake` (200)
11
+ * POST /api/conversations/<name>/machine {action: start|stop|restart|sleep|force|force-now}: done on its machine,
12
+ * one at a time (force takes the place of any other; force-now: the next
13
+ * step of the one running) -> its state (202), as below
14
+ * POST /api/conversations/<name>/machine {escalate: true|false}: a stop that hangs goes on to its qemu by itself (default) or asks
15
+ * GET /api/conversations/<name>/machine {action: {kind, since, until, steps: [{id, state, since, s}]} | null, report, limits, escalate}
11
16
  * POST /api/conversations/<name>/machine/cancel the size kept for its wake, given up
12
17
  * GET /api/conversations/<name>/health what was last seen of its machine
13
18
  * POST /api/conversations/<name>/health look now (never wakes a machine)
@@ -472,6 +477,9 @@ export async function handleApi(request, response, conversations, headers, resou
472
477
  const items = settings.configured ? await signin.recent(conversation).catch((e) => ({ failure: e.message })) : [];
473
478
  return send(200, { ...settings, items: Array.isArray(items) ? items : [], failure: items.failure ?? null }), true;
474
479
  }
480
+ /* Its machine: the action running, step by step, and the last report (conversations.mjs, machineState). */
481
+ const machineOf = /^\/api\/conversations\/([^/]+)\/machine$/.exec(pathname);
482
+ if (machineOf) return send(200, conversations.machineState(decodeURIComponent(machineOf[1]))), true;
475
483
  const paired = /^\/api\/conversations\/([^/]+)\/devices$/.exec(pathname);
476
484
  if (paired && sharing) return send(200, sharing.devices.of(decodeURIComponent(paired[1]))), true;
477
485
  const sending = /^\/api\/conversations\/([^/]+)\/git\/([a-z0-9-]{1,32})\/auto$/.exec(pathname);
@@ -910,6 +918,9 @@ export async function handleApi(request, response, conversations, headers, resou
910
918
  await health.check(conversation, { asked: true }); return send(200, health.of(conversation)), true;
911
919
  }
912
920
  if (machine[2] === 'restart') return send(202, await conversations.restart(conversation)), true;
921
+ /* One action on its machine, or the owner's choice for its way down (conversations.mjs, machineAction). */
922
+ if (typeof body?.action === 'string') return send(202, await conversations.machineAction(conversation, body.action)), true;
923
+ if (typeof body?.escalate === 'boolean') return send(200, conversations.setStopEscalate(conversation, body.escalate)), true;
913
924
  const resized = await conversations.resize(conversation, { memoryMb: body.memoryMb, diskGb: body.diskGb, cpus: body.cpus });
914
925
  /* Asleep, nothing was started: the choice is only kept, for its wake. */
915
926
  return send(resized.phase === 'restarting' ? 202 : 200, resized), true;
@@ -9,7 +9,7 @@
9
9
  import { isConversationName, identifierFrom, titleProblem, groupProblem } from './names.mjs';
10
10
  import { JsonFile } from './store.mjs';
11
11
  import { attachCommand, SOCKET } from './tmux.mjs';
12
- import { WORK, VM_USER, SHARING_STEP } from './vm.mjs';
12
+ import { WORK, VM_USER, SHARING_STEP, stepLine } from './vm.mjs';
13
13
  import { resumeOrFresh } from './tools.mjs';
14
14
  import { TOOLS_PATH, LAUNCH } from './toolbox.mjs';
15
15
  import { availableParallelism } from 'node:os';
@@ -54,6 +54,20 @@ export const ANSWER_PROBE = Object.freeze(['test', '-d', '/']);
54
54
  that is starting): the page tries again without being asked. */
55
55
  /* The name a chat gives its tool, at most. */
56
56
  export const CHAT_NAME_MAX = 40;
57
+ /* WHAT AN OWNER DOES TO A MACHINE (machineAction, 09-11): start it, stop it, restart it, put it to
58
+ sleep, or force it off as a power cut would. One at a time per machine; Force stop takes the place
59
+ of any other. */
60
+ export const MACHINE_KINDS = Object.freeze(['start', 'stop', 'restart', 'sleep', 'force']);
61
+ /* How long each step is given (seconds), as the host program bounds it: past it, the page offers
62
+ "Force now", which moves on to the next step. */
63
+ export const STEP_LIMITS = Object.freeze({ polite: 60, force: 30, term: 5, kill: 5, check: 10, start: 180, suspend: 120, resleep: 300, stop: 120 });
64
+ /* The way down, in order (the host program's `vm halt`), and the step "Force now" moves on to. */
65
+ const DOWN = ['polite', 'force', 'term', 'kill', 'check'];
66
+ const NEXT = Object.freeze({ polite: 'force', force: 'term', term: 'kill' });
67
+ /* Each step in words, for the journal and the chat (the page has its own, web/app.js). */
68
+ const STEP_WORDS = Object.freeze({ polite: 'polite stop', force: 'forced stop', term: 'SIGTERM', kill: 'SIGKILL', check: 'check', start: 'start', suspend: 'sleep', resleep: 'wake and sleep again', stop: 'clean stop' });
69
+ const KIND_WORDS = Object.freeze({ start: ['Started', 'Not started'], stop: ['Stopped', 'Not stopped'], restart: ['Restarted', 'Not restarted'], sleep: ['Asleep', 'Not asleep'], force: ['Stopped by force', 'Not stopped by force'], resize: ['Resized', 'Not resized'] });
70
+
57
71
  export class Refusal extends Error {
58
72
  constructor(status, message, { retry = false } = {}) { super(message); this.status = status; if (retry) this.retry = true; }
59
73
  }
@@ -72,6 +86,13 @@ const firstLine = (text) => String(text ?? '').trim().split('\n').filter(Boolean
72
86
 
73
87
  export class Conversations {
74
88
  #layout; #store; #vms; #tools; #stopDelayMs; #timers = new Map(); #watching = new Map(); #fresh = new Set(); #mountAgain = new Set(); #uid; #gid;
89
+ /* THE ONE ACTION RUNNING ON EACH MACHINE (machineAction), by name: a start, a stop, a restart, a
90
+ sleep, a resize, a force stop. A second one is refused while it runs; Force stop ends it and
91
+ takes its place. */
92
+ #acts = new Map();
93
+ /* Set by the server: an action's outcome, in words -- written in the journal (events.mjs), and
94
+ said in its chat when `chat` (a restart says it already, through `renewed`). */
95
+ machineSaid = () => {};
75
96
  /* Set by the server: prepares the VM before the tool is attached, and
76
97
  names the program the tool is started through. See secrets.mjs. */
77
98
  prepare = async () => {};
@@ -124,6 +145,8 @@ export class Conversations {
124
145
  if (c.phase === 'moving') store.patch(c.name, { phase: 'ready', step: undefined, moved: 'The server restarted while the work folder was being moved. The files are safe, in the machine: look at /work, /work.before-move and /work.moving.' });
125
146
  if (c.phase === 'building') store.patch(c.name, { phase: 'failed', error: 'The server restarted while this conversation was being built. Build it again, or archive it.' });
126
147
  if (c.phase === 'restarting') store.patch(c.name, { phase: 'ready', step: undefined, restartingSince: undefined, restarted: 'The server restarted while this machine was being restarted: look at its state, and restart it again if needed.' });
148
+ /* An action cut short: said as such, never left running on the page. */
149
+ if (store.get(c.name)?.machine) store.patch(c.name, { machine: undefined, machineReport: { kind: c.machine.kind, ok: false, cut: true, at: new Date().toISOString(), steps: (c.machine.steps ?? []).filter((x) => x.state !== 'todo').map(({ id, state, s }) => ({ id, result: state === 'run' ? 'cut' : state, ...(s !== undefined ? { s } : {}) })), advice: 'look', said: 'The server restarted during this action: look at its state.' } });
127
150
  /* Nothing of a start is going on any more: a page must not wait for it. */
128
151
  if (store.get(c.name)?.progress) store.patch(c.name, { progress: undefined });
129
152
  }
@@ -414,9 +437,13 @@ export class Conversations {
414
437
  const c = this.#store.get(name);
415
438
  if (!c) throw new Refusal(404, 'No such conversation.');
416
439
  if (c.phase !== 'ready') throw new Refusal(409, c.phase === 'building' ? 'This conversation is still being built.' : c.phase === 'moving' ? 'This conversation is moving its work folder.' : 'This conversation could not be built.');
440
+ /* Being stopped, put to sleep or forced off: not woken under it; the page tries again after. */
441
+ const acting = this.#acts.get(name);
442
+ if (acting && ['stop', 'force', 'sleep', 'start'].includes(acting.kind)) throw new Refusal(409, 'Its machine is being changed: wait for the end of it.', { retry: true });
417
443
  this.#cancelStop(name);
418
- /* Opening is the explicit gesture that ends a sleep. */
444
+ /* Opening is the explicit gesture that ends a sleep, or a stop its owner asked for. */
419
445
  if (c.asleep) this.#store.patch(name, { asleep: false });
446
+ if (c.stopped) this.#store.patch(name, { stopped: undefined });
420
447
  this.#watching.set(name, (this.#watching.get(name) ?? 0) + 1);
421
448
  /* Another screen is applying the size kept for its wake: this one opens once it is over. */
422
449
  await this.#resizing.get(name)?.catch(() => {});
@@ -810,7 +837,9 @@ export class Conversations {
810
837
  const c = this.#busyCheck(name);
811
838
  const want = c.sizeAtWake;
812
839
  const had = { memoryMb: c.memoryMb, cpus: c.cpus ?? 1, diskGb: c.diskGb ?? DISK_GB };
813
- const release = this.#claim(name, 'restarting', 'Looking at the machine');
840
+ const act = this.#take(name, 'restart');
841
+ const claimed = this.#claim(name, 'restarting', 'Looking at the machine');
842
+ const release = () => { claimed(); this.#give(name, act); };
814
843
  let state;
815
844
  try {
816
845
  state = await this.#vms.state(name);
@@ -824,12 +853,14 @@ export class Conversations {
824
853
  this.#store.patch(name, { phase: 'restarting', restartingSince: since, step: 'Stopping the machine', restarted: undefined, sizeAtWake: undefined });
825
854
  const tool = this.#tools.find((t) => t.id === c.tool);
826
855
  this.#begin(name, 'restart', [...(state === 'Stopped' ? [] : ['stopping']), ...(want ? ['setting'] : []), 'starting', 'answering', 'folders', 'tool', ...this.#resumeStep(c, tool)], since);
827
- this.restarted = this.#cycle(name, c, want ? this.#setter(name, c, want) : async () => undefined, true).then(async (failure) => {
856
+ this.#plan(name, act, [...this.#downSteps(name), 'start']);
857
+ this.restarted = this.#cycle(name, c, want ? this.#setter(name, c, want) : async () => undefined, true, act).then(async (failure) => {
858
+ this.#report(name, act, { ok: !failure, why: failure, chat: false });
828
859
  if (!want) return this.#settle(name, failure ? `Not restarted: ${failure}` : 'Restarted.', failure ? `Its machine was not restarted: ${failure}` : 'Its machine was restarted: the tool started again.', Boolean(failure));
829
860
  await this.reconcile(name);
830
861
  const said = sizeSaid(this.#store.get(name), had);
831
862
  return this.#settle(name, failure ? `Not changed: ${failure} It has ${said}.` : `Restarted: it now has ${said}.`, failure ? `Its machine was not changed: ${failure} It has ${said}.` : `Its machine was restarted with ${said}: the tool started again.`, Boolean(failure));
832
- });
863
+ }).finally(() => this.#give(name, act));
833
864
  return this.#store.get(name);
834
865
  }
835
866
 
@@ -844,7 +875,9 @@ export class Conversations {
844
875
  const tool = this.#tools.find((t) => t.id === c.tool);
845
876
  const { memory, disk, cpus } = this.#sizeAsked(c, tool, asked);
846
877
  if (c.asleep === true) return this.#later(name, c, { memoryMb: memory, cpus, diskGb: disk });
847
- const release = this.#claim(name, 'restarting', 'Looking at the machine');
878
+ const act = this.#take(name, 'resize');
879
+ const claimed = this.#claim(name, 'restarting', 'Looking at the machine');
880
+ const release = () => { claimed(); this.#give(name, act); };
848
881
  let state;
849
882
  try {
850
883
  state = await this.#vms.state(name);
@@ -858,11 +891,14 @@ export class Conversations {
858
891
  /* Started again only when it ran: then the page is told each step to its tool. */
859
892
  if (state === 'Running') this.#begin(name, 'resize', ['stopping', 'setting', 'starting', 'answering', 'folders', 'tool', ...this.#resumeStep(c, tool)], since);
860
893
  const set = this.#setter(name, c, { memoryMb: memory, cpus, diskGb: disk });
861
- this.resized = this.#cycle(name, c, set, state === 'Running').then(async (failure) => {
894
+ if (state === 'Running') this.#plan(name, act, [...this.#downSteps(name), 'start']);
895
+ this.resized = this.#cycle(name, c, set, state === 'Running', act).then(async (failure) => {
896
+ if (state === 'Running') this.#report(name, act, { ok: !failure, why: failure, chat: false });
897
+ else this.#store.patch(name, { machine: undefined });
862
898
  await this.reconcile(name);
863
899
  const said = sizeSaid(this.#store.get(name), { memoryMb: memory, cpus, diskGb: disk });
864
900
  await this.#settle(name, failure ? `Not changed: ${failure} It has ${said}.` : `It now has ${said}.`, failure ? `Its machine was not changed: ${failure} It has ${said}.` : `Its machine was restarted with ${said}: the tool started again.`, Boolean(failure));
865
- });
901
+ }).finally(() => this.#give(name, act));
866
902
  return this.#store.get(name);
867
903
  }
868
904
 
@@ -970,13 +1006,19 @@ export class Conversations {
970
1006
  if (!c) throw new Refusal(404, 'No such conversation.');
971
1007
  if (c.phase !== 'ready') throw new Refusal(409, c.phase === 'restarting' ? 'Its machine is being restarted already.' : c.phase === 'moving' ? 'It is moving its work folder.' : 'This conversation is not ready.');
972
1008
  if (this.#resizing.has(name)) throw new Refusal(409, 'Its machine is being given its new size as it wakes.', { retry: true });
1009
+ if (this.#acts.has(name)) throw new Refusal(409, 'Its machine is busy with another action: wait, or force it off.', { retry: true });
973
1010
  return c;
974
1011
  }
975
1012
 
976
1013
  /* Stops the machine (cleanly, then by force), runs `between` on the
977
1014
  stopped machine, and starts it again when `restart`. Returns what
978
1015
  went wrong, in words, or undefined. */
979
- async #cycle(name, c, between, restart) {
1016
+ /* `act`: the action it runs for (restart, resize); one of its own when none is given (a size
1017
+ applied at a wake), taken and given back here. The stop is the way down (#down): its steps
1018
+ told to the page, "Force now" taken, Force stop taking its place. */
1019
+ async #cycle(name, c, between, restart, given = null) {
1020
+ const act = given ?? this.#take(name, 'resize');
1021
+ if (!given) this.#plan(name, act, [...this.#downSteps(name), ...(restart ? ['start'] : [])]);
980
1022
  const step = (text) => { if (this.#store.get(name)) this.#store.patch(name, { step: text }); };
981
1023
  try {
982
1024
  await this.#calm(name, step);
@@ -984,21 +1026,21 @@ export class Conversations {
984
1026
  let state = await this.#vms.state(name);
985
1027
  if (state !== 'Stopped') {
986
1028
  step('Stopping the machine');
987
- /* A machine asleep cannot be stopped cleanly: it is not running. */
988
- const clean = state === 'Suspended' ? { code: 1 } : await this.#watched(name, 'stop', this.#vms.stop(name, STOP_MS));
989
- state = await this.#vms.state(name);
990
- if (clean.code !== 0 || state !== 'Stopped') {
991
- step('Stopping the machine by force');
992
- await this.#watched(name, 'stop', this.#vms.kill(name));
993
- state = await this.#vms.state(name);
994
- }
1029
+ const down = await this.#down(name, act);
1030
+ if (down.preempted) return 'it was stopped by force instead.';
1031
+ state = await this.#vms.state(name).catch(() => undefined);
995
1032
  if (state !== 'Stopped') return `the machine did not stop (${state ? `it is ${state}` : 'its state could not be read'}).`;
996
- }
1033
+ } else this.#skipDown(name, act);
997
1034
  const failed = await between();
998
1035
  if (!restart) return failed;
999
1036
  step('Starting the machine');
1000
1037
  this.#reach(name, 'starting');
1001
- const started = await this.#watched(name, 'start', this.#vms.start(name));
1038
+ if (act.preempted) return 'it was stopped by force instead.';
1039
+ this.#stepAt(name, act, 'start', 'start');
1040
+ act.ctl = new AbortController();
1041
+ const started = await this.#watched(name, 'start', this.#vms.start(name, { signal: act.ctl.signal }));
1042
+ if (started.aborted) return 'it was stopped by force instead.';
1043
+ this.#stepAt(name, act, 'start', started.code === 0 ? 'ok' : 'fail');
1002
1044
  /* The VM manager may fail its start for its own mounts while the machine runs: those are mounted again here. */
1003
1045
  if (started.code !== 0 && (await this.#vms.state(name).catch(() => undefined)) !== 'Running') return `${failed ? `${failed} And ` : ''}the machine did not start (${firstLine(started.stderr) || firstLine(started.stdout) || `exit ${started.code}`}).`;
1004
1046
  /* Whatever was put in its memory is gone: the next opening prepares it again, its folders first. */
@@ -1007,6 +1049,7 @@ export class Conversations {
1007
1049
  this.#reach(name, 'answering');
1008
1050
  return failed;
1009
1051
  } catch { return 'it stopped on an unexpected error.'; }
1052
+ finally { if (!given) { this.#store.patch(name, { machine: undefined }); this.#give(name, act); } }
1010
1053
  }
1011
1054
 
1012
1055
  /* Before its machine is stopped: its folders being mounted again are
@@ -1025,7 +1068,7 @@ export class Conversations {
1025
1068
  async #settle(name, said, chat, failed = false) {
1026
1069
  if (!this.#store.get(name)) return;
1027
1070
  const running = (await this.#vms.state(name).catch(() => undefined)) === 'Running';
1028
- this.#store.patch(name, { phase: 'ready', step: undefined, restartingSince: undefined, asleep: false, restarted: said });
1071
+ this.#store.patch(name, { phase: 'ready', step: undefined, restartingSince: undefined, asleep: false, stopped: undefined, restarted: said });
1029
1072
  /* Its steps go on to the tool only when it runs; a failure ends them, said in `restarted`. */
1030
1073
  if (!running || failed) this.#end(name);
1031
1074
  /* The tool is started again in its terminal, as after any start. */
@@ -1062,7 +1105,8 @@ export class Conversations {
1062
1105
  this.#cancelStop(name);
1063
1106
  const timer = setTimeout(() => {
1064
1107
  this.#timers.delete(name);
1065
- if (!this.#watching.has(name)) { this.drop(name); void this.#vms.stop(name); }
1108
+ /* Not under an action of its owner's (a restart, a sleep): that one decides. */
1109
+ if (!this.#watching.has(name) && !this.#acts.has(name)) { this.drop(name); void this.#vms.stop(name); }
1066
1110
  }, this.#stopDelayMs);
1067
1111
  timer.unref?.();
1068
1112
  this.#timers.set(name, timer);
@@ -1240,7 +1284,8 @@ export class Conversations {
1240
1284
  resizing(name) { return this.#resizing.has(name); }
1241
1285
 
1242
1286
  /* The conversations whose machine should be running: built, not asleep. */
1243
- awake() { return this.#store.all().filter((c) => c.phase === 'ready' && c.asleep !== true).map((c) => c.name); }
1287
+ /* (Stopped by its owner: not running either, until somebody starts it.) */
1288
+ awake() { return this.#store.all().filter((c) => c.phase === 'ready' && c.asleep !== true && c.stopped !== true).map((c) => c.name); }
1244
1289
  /* Put to sleep, and nothing else: not one being built (02-11: a reset machine was taken for a sleeper and
1245
1290
  suspended mid-build), not a failed one. */
1246
1291
  asleep() { return this.#store.all().filter((c) => c.phase === 'ready' && c.asleep === true).map((c) => c.name); }
@@ -1248,15 +1293,228 @@ export class Conversations {
1248
1293
  /* Whether the machine of a conversation runs right now. */
1249
1294
  async running(name) { return (await this.#vms.state(name)) === 'Running'; }
1250
1295
 
1296
+ /* PUT TO SLEEP, through the one lock of its machine: refused while another action runs on it.
1297
+ Resolves once asleep; throws, in words, when it could not be. */
1251
1298
  async sleep(name) {
1252
1299
  if (!this.#store.get(name)) throw new Refusal(404, 'No such conversation.');
1253
- this.#cancelStop(name);
1254
- this.drop(name);
1255
- const r = await this.#vms.suspend(name);
1256
- if (r.code !== 0) throw new Refusal(502, `The machine did not go to sleep: ${firstLine(r.stderr)}`);
1257
- /* Remembered: a sleep that was asked for holds until somebody wakes
1258
- it on purpose. A page that merely reloads must not wake it. */
1259
- this.#store.patch(name, { asleep: true });
1300
+ if (this.#acts.has(name)) throw new Refusal(409, 'Its machine is busy with another action: wait, or force it off.', { retry: true });
1301
+ const act = this.#take(name, 'sleep');
1302
+ const report = await this.#perform(name, act);
1303
+ if (!report.ok) throw new Refusal(502, `The machine did not go to sleep: ${report.why ?? 'it did not answer.'}`);
1304
+ }
1305
+
1306
+ /* ---------- ONE ACTION AT A TIME ON A MACHINE (09-11) ---------- */
1307
+ /* Taken at once, before anything is awaited, so that a second action asked meanwhile sees it. */
1308
+ #take(name, kind) {
1309
+ let finish;
1310
+ const act = { kind, since: new Date().toISOString(), steps: [], ctl: null, next: null, current: null, preempted: false, until: kind !== 'force' && this.#store.get(name)?.stopEscalate === false ? 'force' : 'kill' };
1311
+ act.done = new Promise((r) => { finish = r; });
1312
+ act.finish = finish;
1313
+ this.#acts.set(name, act);
1314
+ return act;
1315
+ }
1316
+ #give(name, act) { if (this.#acts.get(name) === act) this.#acts.delete(name); act.finish(); }
1317
+ /* The steps the page shows, in order: done, running, to come (`todo`). */
1318
+ #plan(name, act, ids) {
1319
+ act.steps = ids.map((id) => ({ id, state: 'todo' }));
1320
+ this.#show(name, act);
1321
+ }
1322
+ #show(name, act) {
1323
+ if (!this.#store.get(name)) return;
1324
+ this.#store.patch(name, { machine: { kind: act.kind, since: act.since, until: act.until, steps: act.steps.map((x) => ({ ...x })) } });
1325
+ }
1326
+ /* The way down's steps, as this machine's owner chose: to its own qemu, or the VM manager's ways only. */
1327
+ #downSteps(name) { return this.#store.get(name)?.stopEscalate === false ? ['polite', 'force', 'check'] : [...DOWN]; }
1328
+ /* A step reached (`start`) or ended (ok|fail|timeout|skip|cut), with its seconds. */
1329
+ #stepAt(name, act, id, result, { s, more, freedGb } = {}) {
1330
+ let at = act.steps.find((x) => x.id === id);
1331
+ if (!at) { at = { id, state: 'todo' }; const check = act.steps.findIndex((x) => x.id === 'check' || x.id === 'start'); act.steps.splice(check < 0 || id === 'start' ? act.steps.length : check, 0, at); }
1332
+ if (result === 'start') { at.state = 'run'; at.since = new Date().toISOString(); act.current = id; }
1333
+ else {
1334
+ at.state = result;
1335
+ at.s = s ?? (at.since ? Math.round((Date.now() - Date.parse(at.since)) / 1000) : 0);
1336
+ if (more) at.more = more;
1337
+ if (freedGb !== undefined) at.freedGb = freedGb;
1338
+ if (act.current === id) act.current = null;
1339
+ /* Nothing left to stop: the steps before the check are not needed. */
1340
+ if (result === 'skip' && more === 'gone') for (const x of act.steps) if (x.state === 'todo' && x.id !== 'check' && x.id !== 'start') x.state = 'skip';
1341
+ }
1342
+ this.#show(name, act);
1343
+ }
1344
+ /* Nothing to stop: the way down is skipped whole. */
1345
+ #skipDown(name, act) { for (const x of act.steps) if (DOWN.includes(x.id)) x.state = 'skip'; this.#show(name, act); }
1346
+ /* A line of the host program's output. */
1347
+ #seen(name, act, line) {
1348
+ const step = stepLine(line);
1349
+ if (!step) return;
1350
+ if (step.result === 'start') this.#reach(name, 'stopping');
1351
+ this.#stepAt(name, act, step.id, step.result, step);
1352
+ }
1353
+
1354
+ /* THE WAY DOWN (the host program's `vm halt`, or `vm hardstop` for Force stop): a polite stop, a
1355
+ stop by force, SIGTERM then SIGKILL to its own qemu, then the check -- each step said as it
1356
+ goes. "Force now" ends the step running and starts the next (#forceNow); Force stop ends it
1357
+ all (`preempted`). Resolves with { ok, freedGb, more } or { preempted }. */
1358
+ async #down(name, act, { hard = false } = {}) {
1359
+ let from = hard ? 'term' : 'polite';
1360
+ let first = true;
1361
+ for (;;) {
1362
+ /* Force stop asked before this step began: it does not begin. */
1363
+ if (act.preempted) return { ok: false, preempted: true };
1364
+ act.ctl = new AbortController(); act.next = null;
1365
+ const options = { signal: act.ctl.signal, onLine: (line) => this.#seen(name, act, line) };
1366
+ const r = hard && first ? await this.#vms.hardstop(name, options) : await this.#vms.halt(name, { from, until: act.until, ...options });
1367
+ first = false;
1368
+ if (r.aborted && act.next && !act.preempted) {
1369
+ if (act.current) this.#stepAt(name, act, act.current, 'skip', { more: 'moved on' });
1370
+ from = act.next;
1371
+ continue;
1372
+ }
1373
+ if (r.aborted) return { ok: false, preempted: true };
1374
+ /* A step still said running when the program ended (it was cut): ended so. */
1375
+ if (act.current) this.#stepAt(name, act, act.current, 'fail', { more: 'cut' });
1376
+ const check = act.steps.find((x) => x.id === 'check');
1377
+ return { ok: r.code === 0, freedGb: check?.freedGb, more: check?.more ?? (r.code === 0 ? '' : firstLine(r.stderr)) };
1378
+ }
1379
+ }
1380
+
1381
+ /* WHAT AN OWNER ASKS OF A MACHINE (`kind`, MACHINE_KINDS; 'force-now' moves the running action
1382
+ to its next step). Answers at once with what the page reads (machineState); the action goes
1383
+ on, its steps on the record (`machine`), its report kept after it (`machineReport`), said in
1384
+ the journal and in its chat. `this.acted`: its end, for whoever waits for it. */
1385
+ async machineAction(name, kind) {
1386
+ const c = this.#store.get(name);
1387
+ if (!c) throw new Refusal(404, 'No such conversation.');
1388
+ if (kind === 'force-now') return this.#forceNow(name);
1389
+ if (!MACHINE_KINDS.includes(kind)) throw new Refusal(400, 'Not an action of a machine.');
1390
+ if (kind === 'restart') { await this.restart(name); this.acted = this.restarted; return this.machineState(name); }
1391
+ const running = this.#acts.get(name);
1392
+ if (kind !== 'force') this.#busyCheck(name);
1393
+ else {
1394
+ if (c.phase === 'building' || c.phase === 'moving') throw new Refusal(409, c.phase === 'building' ? 'This conversation is still being built.' : 'It is moving its work folder.');
1395
+ if (running) { running.preempted = true; running.ctl?.abort(); await running.done; }
1396
+ }
1397
+ if (kind === 'start' && (c.asleep !== true && (await this.#vms.state(name).catch(() => undefined)) === 'Running')) throw new Refusal(409, 'Its machine runs already.');
1398
+ if (kind === 'start') await this.room({ kind: 'start', name, memoryMb: c.memoryMb });
1399
+ if (this.#acts.has(name)) throw new Refusal(409, 'Its machine is busy with another action: wait, or force it off.', { retry: true });
1400
+ const act = this.#take(name, kind);
1401
+ this.acted = this.#perform(name, act);
1402
+ return this.machineState(name);
1403
+ }
1404
+
1405
+ /* "FORCE NOW": the step running is ended and the next one started (polite -> forced -> SIGTERM ->
1406
+ SIGKILL). Past the VM manager's own ways, for an owner who chose them alone, it is the owner's
1407
+ choice now: the way goes on to its qemu. */
1408
+ #forceNow(name) {
1409
+ const act = this.#acts.get(name);
1410
+ const now = act?.steps.find((x) => x.state === 'run');
1411
+ if (!act || !now || !NEXT[now.id] || !act.ctl) throw new Refusal(409, 'Nothing to move on from just now.');
1412
+ if (now.id === 'force' && act.until === 'force') {
1413
+ act.until = 'kill';
1414
+ const check = act.steps.findIndex((x) => x.id === 'check');
1415
+ act.steps.splice(check, 0, { id: 'term', state: 'todo' }, { id: 'kill', state: 'todo' });
1416
+ }
1417
+ act.next = NEXT[now.id]; act.current = now.id;
1418
+ this.#show(name, act);
1419
+ act.ctl.abort();
1420
+ return this.machineState(name);
1421
+ }
1422
+
1423
+ /* What the page reads: the action running (its steps, each with its state and since when), the
1424
+ last report, each step's bound, and the owner's choice for the way down. */
1425
+ machineState(name) {
1426
+ const c = this.#store.get(name);
1427
+ if (!c) throw new Refusal(404, 'No such conversation.');
1428
+ return { action: c.machine ?? null, report: c.machineReport ?? null, limits: STEP_LIMITS, escalate: c.stopEscalate !== false };
1429
+ }
1430
+
1431
+ /* THE WAY DOWN, AS ITS OWNER CHOSE (a default, changed per conversation): on (the default), a stop
1432
+ that hangs goes on to its own qemu by itself; off, it stops after the VM manager's own ways, and
1433
+ the page offers to go further. */
1434
+ setStopEscalate(name, on) {
1435
+ if (!this.#store.get(name)) throw new Refusal(404, 'No such conversation.');
1436
+ this.#store.patch(name, { stopEscalate: on === false ? false : undefined });
1437
+ return this.machineState(name);
1438
+ }
1439
+
1440
+ /* AN ACTION, RUN TO ITS END: start, stop, sleep, force (a restart and a resize run #cycle). Gives
1441
+ its machine back, writes its report, resolves with it. */
1442
+ async #perform(name, act) {
1443
+ const c = this.#store.get(name);
1444
+ const kind = act.kind;
1445
+ let result = { ok: false };
1446
+ try {
1447
+ this.#cancelStop(name);
1448
+ if (kind === 'start') {
1449
+ const before = await this.#vms.state(name).catch(() => undefined);
1450
+ this.#plan(name, act, ['start']);
1451
+ this.#stepAt(name, act, 'start', 'start');
1452
+ act.ctl = new AbortController();
1453
+ if (act.preempted) act.ctl.abort();
1454
+ const r = act.preempted ? { code: 143, aborted: true } : await this.#vms.start(name, { signal: act.ctl.signal });
1455
+ if (r.aborted) result = { ok: false, preempted: true };
1456
+ else {
1457
+ const now = await this.#vms.state(name).catch(() => undefined);
1458
+ this.#stepAt(name, act, 'start', now === 'Running' ? 'ok' : 'fail');
1459
+ result = now === 'Running' ? { ok: true } : { ok: false, more: firstLine(r.stderr) || firstLine(r.stdout) || `it is ${now ?? 'in a state that could not be read'}` };
1460
+ if (now === 'Running') {
1461
+ /* From a stop, whatever was in its memory is gone: the next opening prepares it again, its folders
1462
+ first. From sleep, it is as it was. */
1463
+ if (before !== 'Suspended') { this.#fresh.add(name); this.#mountAgain.add(name); }
1464
+ this.#store.patch(name, { asleep: false, stopped: undefined });
1465
+ }
1466
+ }
1467
+ } else if (kind === 'sleep') {
1468
+ this.#plan(name, act, ['suspend']);
1469
+ this.drop(name);
1470
+ act.ctl = new AbortController();
1471
+ const r = await this.#vms.suspend(name, { signal: act.ctl.signal, onLine: (line) => this.#seen(name, act, line) });
1472
+ if (r.aborted) result = { ok: false, preempted: true };
1473
+ else {
1474
+ if (act.current) this.#stepAt(name, act, act.current, r.code === 0 ? 'ok' : 'fail');
1475
+ if (!act.steps.some((x) => x.state !== 'todo')) this.#stepAt(name, act, 'suspend', r.code === 0 ? 'ok' : 'fail');
1476
+ result = r.code === 0 ? { ok: true } : { ok: false, more: firstLine(r.stderr) || `exit ${r.code}` };
1477
+ /* Remembered: a sleep that was asked for holds until somebody wakes
1478
+ it on purpose. A page that merely reloads must not wake it. */
1479
+ if (r.code === 0) this.#store.patch(name, { asleep: true, stopped: undefined });
1480
+ }
1481
+ } else {
1482
+ /* stop, force: the way down, all of it or from its own qemu. */
1483
+ this.#plan(name, act, kind === 'force' ? ['term', 'kill', 'check'] : this.#downSteps(name));
1484
+ await this.#calm(name, () => {});
1485
+ this.drop(name);
1486
+ result = await this.#down(name, act, { hard: kind === 'force' });
1487
+ /* Stopped: no longer asleep (its saved state is gone); it stays stopped until somebody starts it. */
1488
+ if (result.ok) this.#store.patch(name, { asleep: false, stopped: true });
1489
+ }
1490
+ } catch (error) { result = { ok: false, more: error instanceof Refusal ? error.message : 'an unexpected error' }; }
1491
+ let report;
1492
+ try { report = this.#report(name, act, { ...result, why: result.preempted ? 'Force stop took its place.' : undefined, chat: true }); }
1493
+ finally { this.#give(name, act); }
1494
+ /* Started: its tool starts in its terminal, as after any start (once the machine is given back). */
1495
+ if (kind === 'start' && result.ok) try { this.ready(name); } catch { /* the next opening starts it */ }
1496
+ return report;
1497
+ }
1498
+
1499
+ /* THE REPORT OF AN ACTION, kept on the conversation (`machineReport`), the steps it took with
1500
+ their seconds, the memory freed, and what to do when it failed (`advice`: force | manager |
1501
+ again | look); said in the journal, and in its chat when `chat`. */
1502
+ #report(name, act, { ok, freedGb, more, why, chat = true, preempted = false }) {
1503
+ const steps = act.steps.filter((x) => x.state !== 'todo').map(({ id, state, s }) => ({ id, result: state, ...(s !== undefined ? { s } : {}) }));
1504
+ const check = act.steps.find((x) => x.id === 'check');
1505
+ const freed = freedGb ?? check?.freedGb;
1506
+ const left = /qemu-left/.test(more ?? check?.more ?? '');
1507
+ const mute = /mute/.test(more ?? check?.more ?? '');
1508
+ const advice = ok || preempted ? undefined : left ? (act.until === 'force' ? 'force' : 'manager') : mute ? 'manager' : act.kind === 'sleep' ? 'force' : act.kind === 'force' || act.kind === 'stop' ? 'manager' : 'again';
1509
+ const seconds = Math.max(0, Math.round((Date.now() - Date.parse(act.since)) / 1000));
1510
+ const [yes, no] = KIND_WORDS[act.kind] ?? ['Done', 'Not done'];
1511
+ const listed = steps.filter((x) => x.result !== 'skip').map((x) => `${STEP_WORDS[x.id] ?? x.id} ${x.result === 'ok' ? '' : `${x.result} `}${x.s ?? 0} s`).join(', ');
1512
+ const advised = { force: ' Use Force stop.', manager: ' The VM manager may need a restart: that is your call.', again: ' Try again in a moment.', look: ' Look at its state.' }[advice] ?? '';
1513
+ const said = `${ok ? yes : no} in ${seconds} s${listed ? ` (${listed})` : ''}${ok && freed ? `, ${freed.toFixed(1)} GB freed` : ''}.${!ok && why ? ` ${why}` : ''}${!ok && !why && more ? ` ${more}.` : ''}${advised}`;
1514
+ const report = { kind: act.kind, ok: Boolean(ok), at: new Date().toISOString(), s: seconds, steps, ...(freed !== undefined ? { freedGb: freed } : {}), ...(advice ? { advice } : {}), ...(preempted ? { preempted: true } : {}), said };
1515
+ if (this.#store.get(name)) this.#store.patch(name, { machine: undefined, machineReport: report });
1516
+ try { this.machineSaid(name, said, Boolean(ok), chat); } catch { /* told, nothing more */ }
1517
+ return { ...report, ...(why ? { why } : more ? { why: more } : {}) };
1260
1518
  }
1261
1519
 
1262
1520
  /* Online or offline: remembered here, enforced by network.mjs. */
package/server/main.mjs CHANGED
@@ -550,6 +550,11 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
550
550
  alert: (payload) => { void alerts.tell(payload); } });
551
551
  /* Its machine restarted or built again: said in its chat, and the tool told to read it again. */
552
552
  all.renewed = (name, text, running) => talk.renewed(name, text, running);
553
+ /* What an owner did to a machine (start, stop, sleep, force, restart): in the journal, and a line in its chat. */
554
+ all.machineSaid = (name, text, ok, chat) => {
555
+ events.add({ kind: 'machine', text: `Machine of ${name}: ${text}`, conversation: name });
556
+ if (chat) try { talk.event(name, ok ? { kind: 'machine-ok', text, topic: 'Machine' } : { kind: 'machine-problem', text, tone: 'warn', topic: 'Machine', brief: 'Machine action failed' }); } catch { /* its chat is off */ }
557
+ };
553
558
  /* A Tether call waiting for the owner is said in its conversation's thread, with Accept / Refuse. */
554
559
  tethers.announce = (name, event) => { try { return talk.event(name, event); } catch { return null; } };
555
560
  /* A device given a conversation that talks through the app talks there too. */
@@ -232,5 +232,26 @@ export const SETTINGS_WORDS_FR = {
232
232
  'set-dev-revoke': 'Révoquer l’appareil', 'set-dev-revoke-q': '{name} perd tout, maintenant', 'set-dev-revoke-yes': 'Révoquer',
233
233
  'set-dev-more': '+ Donner plus', 'set-dev-add': '+ Ajouter', 'set-dev-added': 'Ajouté', 'set-dev-remove': 'Retirer',
234
234
  'set-dev-not-shared': 'Non partagé ({n})', 'set-dev-share': 'Partager…', 'set-dev-chat-off': 'Chat coupé : l’appareil attend',
235
+ /* Its machine (09-11): the five buttons, why one is greyed, the confirmation, the steps, the report. */
236
+ 'set-m-start': 'Démarrer', 'set-m-stop': 'Arrêter', 'set-m-restart': 'Redémarrer', 'set-m-force': 'Forcer l’arrêt',
237
+ 'set-m-force-now': 'Forcer maintenant', 'set-m-force-now-why': 'Termine cette étape, passe à la suivante',
238
+ 'set-mwhy-busy': 'Une autre action est en cours', 'set-mwhy-notready': 'Pas encore prête', 'set-mwhy-runs': 'Elle tourne déjà',
239
+ 'set-mwhy-stopped': 'Déjà arrêtée', 'set-mwhy-asleep': 'Déjà endormie', 'set-mwhy-nothing': 'Endormie : rien ne tourne',
240
+ 'set-mwhat-start': 'Démarre sa machine et son outil', 'set-mwhat-stop': 'L’arrête proprement, de force si ça bloque',
241
+ 'set-mwhat-restart': 'L’arrête, puis la redémarre', 'set-mwhat-force': 'Coupe tout, comme une coupure de courant',
242
+ 'set-mconf-stop': 'L’arrêter ? Le travail en cours s’interrompt.', 'set-mconf-restart': 'Redémarrer ? L’outil repart, fichiers gardés.',
243
+ 'set-mconf-force': 'Comme une coupure de courant : rien n’est sauvé.', 'set-mconf-no': 'Annuler',
244
+ 'set-mesc': 'Si un arrêt bloque', 'set-mesc-auto': 'Forcer seul', 'set-mesc-ask': 'Me demander',
245
+ 'set-mstep-polite': 'Poli', 'set-mstep-force': 'Forcé', 'set-mstep-term': 'Tuer doucement', 'set-mstep-kill': 'Tuer net',
246
+ 'set-mstep-check': 'Vérifié', 'set-mstep-start': 'Démarrage', 'set-mstep-suspend': 'Mise en veille', 'set-mstep-resleep': 'Réveil puis veille',
247
+ 'set-mstep-stop': 'Arrêt propre', 'set-mstep-done': 'Fait : {steps}', 'set-mpast': 'Délai dépassé : Forcer maintenant',
248
+ 'set-mk-start': 'Démarrée', 'set-mk-start-no': 'Pas démarrée', 'set-mk-stop': 'Arrêtée', 'set-mk-stop-no': 'Pas arrêtée',
249
+ 'set-mk-restart': 'Redémarrée', 'set-mk-restart-no': 'Pas redémarrée', 'set-mk-resize': 'Redimensionnée', 'set-mk-resize-no': 'Pas redimensionnée',
250
+ 'set-mk-sleep': 'Endormie', 'set-mk-sleep-no': 'Pas endormie', 'set-mk-force': 'Arrêtée de force', 'set-mk-force-no': 'Pas arrêtée de force',
251
+ 'set-madv-force': 'Essayez Forcer l’arrêt', 'set-madv-manager': 'Le gestionnaire doit peut-être redémarrer',
252
+ 'set-madv-again': 'Réessayez dans un instant', 'set-madv-look': 'Regardez son état',
253
+ 'set-mrep-freed': '{gb} Go rendus', 'set-mrep-replaced': 'Remplacée par Forcer l’arrêt',
254
+ 'set-mt-stop': 'Arrêt de sa machine', 'set-mt-force': 'Arrêt forcé de sa machine', 'set-mt-sleep': 'Mise en veille', 'set-mt-start': 'Démarrage de sa machine',
255
+ 'set-stopped-page': 'Arrêtée. Elle démarre quand vous la démarrez.',
235
256
  };
236
257
  export const settingsWords = (lang) => (String(lang ?? '').toLowerCase().split('-')[0] === 'fr' ? { ...SETTINGS_WORDS_FR } : {});
package/server/vm.mjs CHANGED
@@ -23,6 +23,18 @@ const LAUNCH_SECONDS = 900;
23
23
  const PREFIX = 'clv-';
24
24
  /* Copying a ready-made disk of a few gigabytes: slow disks are given time. */
25
25
  const CLONE_MS = 15 * 60_000;
26
+ /* The bounds of the host program's ways down (its own steps are bounded: these only catch a host
27
+ program that hangs). */
28
+ const HALT_MS = 360_000;
29
+ const HARDSTOP_MS = 120_000;
30
+ /* A line of a way down: `step <id> <start|ok|fail|timeout|skip> [<n>s] [what more]`. */
31
+ export function stepLine(line) {
32
+ const m = /^step ([a-z]+) (start|ok|fail|timeout|skip)(?: (\d+)s)?(?: (.*))?$/.exec(String(line ?? '').trim());
33
+ if (!m) return null;
34
+ const more = m[4] ?? '';
35
+ const freed = /(?:^| )freed (\d+(?:\.\d)?)G\b/.exec(more);
36
+ return { id: m[1], result: m[2], ...(m[3] !== undefined ? { s: Number(m[3]) } : {}), ...(more ? { more } : {}), ...(freed ? { freedGb: Number(freed[1]) } : {}) };
37
+ }
26
38
 
27
39
  export function vmName(conversation) {
28
40
  if (!isConversationName(conversation)) throw new Error('not a conversation name');
@@ -41,18 +53,28 @@ export function megabytes(text) {
41
53
  /* Runs one command and resolves with what happened; it never throws for a
42
54
  non-zero exit, because "the VM does not exist" is an answer, not a crash. */
43
55
  export function runner(prefix) {
44
- /* `maxBytes`: what is taken in of its output, at most (8 MB unless said). */
45
- return (argv, { input, timeoutMs = 120_000, maxBytes = 8 * 1024 * 1024 } = {}) => new Promise((resolve) => {
56
+ /* `maxBytes`: what is taken in of its output, at most (8 MB unless said). `onLine`: told each
57
+ line of its output as it comes (the steps of a stop, for the page). `signal`: an AbortSignal
58
+ that ends it at once (a step the owner moves on from: "Force now"). */
59
+ return (argv, { input, timeoutMs = 120_000, maxBytes = 8 * 1024 * 1024, onLine, signal } = {}) => new Promise((resolve) => {
46
60
  const all = [...prefix, ...argv];
47
- const child = execFile(all[0], all.slice(1), { timeout: timeoutMs, maxBuffer: maxBytes, encoding: 'utf8' },
48
- (error, stdout, stderr) => resolve({ code: error ? (typeof error.code === 'number' ? error.code : 1) : 0, stdout, stderr }));
61
+ const child = execFile(all[0], all.slice(1), { timeout: timeoutMs, maxBuffer: maxBytes, encoding: 'utf8', ...(signal ? { signal } : {}) },
62
+ (error, stdout, stderr) => resolve({ code: error ? (typeof error.code === 'number' ? error.code : 1) : 0, stdout, stderr, ...(error?.name === 'AbortError' ? { aborted: true } : {}) }));
63
+ if (onLine) {
64
+ let rest = '';
65
+ child.stdout.on('data', (chunk) => {
66
+ rest += chunk;
67
+ const lines = rest.split('\n'); rest = lines.pop();
68
+ for (const line of lines) try { onLine(line); } catch { /* a listener's trouble is not the command's */ }
69
+ });
70
+ }
49
71
  child.stdin.on('error', () => {});
50
72
  child.stdin.end(input ?? '');
51
73
  });
52
74
  }
53
75
 
54
76
  /* The verbs that change a machine: its state is asked again after them. */
55
- const CHANGES = new Set(['launch', 'clone', 'start', 'stop', 'suspend', 'kill', 'delete', 'purge', 'set', 'rename', 'restore', 'snapshot', 'revive', 'reclaim']);
77
+ const CHANGES = new Set(['launch', 'clone', 'start', 'stop', 'suspend', 'kill', 'halt', 'hardstop', 'delete', 'purge', 'set', 'rename', 'restore', 'snapshot', 'revive', 'reclaim']);
56
78
  export const STATES_FRESH_MS = 3000;
57
79
  /* The VM manager did not say what a machine is in: not an answer about the machine. */
58
80
  export class VmUnknown extends Error {
@@ -164,10 +186,19 @@ export class Vms {
164
186
  return this.run(['vm', 'umount', vmName(conversation), name], { timeoutMs: 120_000 });
165
187
  }
166
188
 
167
- start(conversation) { return this.run(['vm', 'start', vmName(conversation)], { timeoutMs: 300_000 }); }
189
+ /* `signal`: a start given up (Force stop asked meanwhile). */
190
+ start(conversation, { signal } = {}) { return this.run(['vm', 'start', vmName(conversation)], { timeoutMs: 300_000, ...(signal ? { signal } : {}) }); }
168
191
  stop(conversation, timeoutMs = 300_000) { return this.run(['vm', 'stop', vmName(conversation)], { timeoutMs }); }
169
192
  /* Stopped without waiting for the system inside: after a clean stop hung. */
170
193
  kill(conversation) { return this.run(['vm', 'kill', vmName(conversation)], { timeoutMs: 300_000 }); }
194
+ /* STOPPED FOR SURE, step by step (the host program's `vm halt`): a polite stop, a stop by force,
195
+ then its own qemu ended (SIGTERM, SIGKILL), then checked. `from`/`until`: the first and last
196
+ step (polite|force|term|kill; until force|kill). Each `step ...` line is told to `onLine`. */
197
+ halt(conversation, { from = 'polite', until = 'kill', onLine, signal } = {}) {
198
+ return this.run(['vm', 'halt', vmName(conversation), from, until], { timeoutMs: HALT_MS, onLine, signal });
199
+ }
200
+ /* "Force stop", as a power cut: its qemu ended, nothing asked of the VM manager (`vm hardstop`). */
201
+ hardstop(conversation, { onLine, signal } = {}) { return this.run(['vm', 'hardstop', vmName(conversation)], { timeoutMs: HARDSTOP_MS, onLine, signal }); }
171
202
  /* Memory in megabytes, disk in gigabytes: only on a stopped machine. */
172
203
  setMemory(conversation, mb) { return this.run(['vm', 'set', vmName(conversation), 'memory', String(mb)], { timeoutMs: 120_000 }); }
173
204
  setCpus(conversation, n) { return this.run(['vm', 'set', vmName(conversation), 'cpus', String(n)], { timeoutMs: 120_000 }); }
@@ -182,7 +213,8 @@ export class Vms {
182
213
  const cpus = /^\d{1,3}$/.test(line('cpus') ?? '') ? Number(line('cpus')) : undefined;
183
214
  return { memoryMb: mb === undefined ? undefined : Math.round(mb), diskGb: disk === undefined ? undefined : Math.round(disk / 1024), cpus };
184
215
  }
185
- suspend(conversation) { return this.run(['vm', 'suspend', vmName(conversation)], { timeoutMs: 300_000 }); }
216
+ /* Its steps (`step suspend ...`, then a wake and sleep again, then a clean stop) told to `onLine`. */
217
+ suspend(conversation, { signal, onLine } = {}) { return this.run(['vm', 'suspend', vmName(conversation)], { timeoutMs: 600_000, ...(signal ? { signal } : {}), ...(onLine ? { onLine } : {}) }); }
186
218
  /* Free the RAM of a machine that is asleep but whose qemu still holds it (a
187
219
  suspend that did not end the process): wake+resleep, then a clean stop. */
188
220
  reclaim(conversation) { return this.run(['vm', 'reclaim', vmName(conversation)], { timeoutMs: 300_000 }); }
package/web/app.js CHANGED
@@ -181,7 +181,7 @@
181
181
  $('notice-cancel').onclick = cancel ?? null;
182
182
  $('notice-health').hidden = true; $('notice-restart').hidden = true;
183
183
  notice.hidden = false;
184
- $('notice-spin').hidden = true; $('notice-steps').hidden = true;
184
+ $('notice-spin').hidden = true; $('notice-steps').hidden = true; $('notice-mlive').hidden = true;
185
185
  $('notice-head').hidden = true; delete notice.dataset.progress; delete notice.dataset.loading;
186
186
  mascot(null);
187
187
  };
@@ -234,7 +234,91 @@
234
234
  const usualFor = (kind, s) => {
235
235
  if (kind === 'build') return 'A new machine takes a few minutes. Nothing to do meanwhile: its terminal comes by itself.';
236
236
  if (kind === 'wake') return `${s < 180 ? 'A start usually takes a minute or two.' : 'This takes much longer than a start usually does.'} Its work, its files and its chat are kept.`;
237
- return `${s < 180 ? 'A restart usually takes one to two minutes.' : 'This is taking longer than usual: the machine may be slow to stop or to start. It goes on by itself.'} Its files and its chat are kept.`;
237
+ return `${s < 180 ? 'A restart usually takes one to two minutes.' : 'Longer than usual: its step is above, with what you can do.'} Its files and its chat are kept.`;
238
+ };
239
+ /* ---------- ITS MACHINE'S ACTION, STEP BY STEP (09-11) ----------
240
+ The escalation in one line (server/conversations.mjs, machineAction; the host program's vm halt):
241
+ polite stop, forced stop, soft kill (SIGTERM), hard kill (SIGKILL), checked. Done ticked, the
242
+ one under way pulsing with its time and its bound, those to come dimmed; right under it, "Force
243
+ now" once the step passes its bound (it moves on to the next), and "Force stop" (it takes the
244
+ place of the action). Drawn the same in its settings and over its terminal. */
245
+ const MSTEPS = {
246
+ polite: [() => uiSaid('set-mstep-polite', 'Polite'), 60], force: [() => uiSaid('set-mstep-force', 'Forced'), 30],
247
+ term: [() => uiSaid('set-mstep-term', 'Soft kill'), 5], kill: [() => uiSaid('set-mstep-kill', 'Hard kill'), 5],
248
+ check: [() => uiSaid('set-mstep-check', 'Checked'), 10], start: [() => uiSaid('set-mstep-start', 'Start'), 180],
249
+ suspend: [() => uiSaid('set-mstep-suspend', 'Sleep'), 120], resleep: [() => uiSaid('set-mstep-resleep', 'Wake and sleep'), 300],
250
+ stop: [() => uiSaid('set-mstep-stop', 'Clean stop'), 120],
251
+ };
252
+ const MNEXT = new Set(['polite', 'force', 'term']);
253
+ const mstepSaid = (id) => (MSTEPS[id] ? MSTEPS[id][0]() : id);
254
+ const MMARK = { ok: '\u2713', run: '\u25CF', todo: '\u25CB', skip: '\u2013', fail: '\u2715', timeout: '\u2715', cut: '\u2715' };
255
+ /* The step under way, its seconds so far and its bound; null when none runs. */
256
+ /* A step's bound, in seconds (a test may shorten them all: window.clavariumTimes.mstep). */
257
+ const mlimit = (id) => window.clavariumTimes?.mstep ?? MSTEPS[id]?.[1] ?? 60;
258
+ const mstepRunning = (a) => {
259
+ const x = a?.steps?.find((y) => y.state === 'run');
260
+ if (!x) return null;
261
+ const s = Math.max(0, Math.floor((Date.now() - (Date.parse(x.since ?? '') || Date.now())) / 1000));
262
+ return { id: x.id, s, limit: mlimit(x.id), past: s >= mlimit(x.id) };
263
+ };
264
+ /* In one line, for over its terminal: the step under way and its time, and what can be done past its bound. */
265
+ const mstepLine = (a) => {
266
+ const now = mstepRunning(a);
267
+ if (!now) return '';
268
+ const done = (a.steps ?? []).filter((x) => x.state === 'ok').map((x) => mstepSaid(x.id));
269
+ return `${mstepSaid(now.id)} \u00b7 ${clockOf(now.s)} / ${clockOf(now.limit)}${done.length ? ` \u2014 ${uiSaid('set-mstep-done', 'Done: {steps}', { steps: done.join(', ') })}` : ''}${now.past && MNEXT.has(now.id) && !DEVICE ? ` \u2014 ${uiSaid('set-mpast', 'Past its time: Force now moves on')}` : ''}`;
270
+ };
271
+ function paintMlive(el, c) {
272
+ const a = c?.machine;
273
+ el.hidden = !a;
274
+ if (!a) { el.replaceChildren(); el.dataset.key = ''; return; }
275
+ const key = `${c.name}|${a.kind}|${(a.steps ?? []).map((x) => `${x.id}:${x.state}`).join(',')}`;
276
+ if (el.dataset.key !== key) {
277
+ el.dataset.key = key;
278
+ const ol = document.createElement('ol'); ol.className = 'mstep'; ol.setAttribute('aria-live', 'polite');
279
+ (a.steps ?? []).forEach((x, i) => {
280
+ if (i) { const arr = document.createElement('li'); arr.className = 'arr'; arr.textContent = '\u2192'; arr.setAttribute('aria-hidden', 'true'); ol.append(arr); }
281
+ const li = document.createElement('li'); li.dataset.state = x.state; li.dataset.step = x.id;
282
+ const mark = document.createElement('span'); mark.className = 'mark'; mark.setAttribute('aria-hidden', 'true'); mark.textContent = MMARK[x.state] ?? '';
283
+ const label = document.createElement('span'); label.textContent = mstepSaid(x.id);
284
+ li.append(mark, label, document.createElement('small'));
285
+ ol.append(li);
286
+ });
287
+ const row = document.createElement('div'); row.className = 'row';
288
+ const now = document.createElement('button'); now.type = 'button'; now.className = 'primary m-force-now'; now.textContent = uiSaid('set-m-force-now', 'Force now');
289
+ now.title = uiSaid('set-m-force-now-why', 'Ends this step, starts the next');
290
+ now.addEventListener('click', () => void machineAct('force-now'));
291
+ const force = document.createElement('button'); force.type = 'button'; force.className = 'danger m-force-stop'; force.textContent = uiSaid('set-m-force', 'Force stop');
292
+ force.addEventListener('click', () => askMachine('force'));
293
+ row.append(now, force);
294
+ el.replaceChildren(ol, row);
295
+ }
296
+ /* Each second: the time of each step, and whether "Force now" applies yet. */
297
+ const running = mstepRunning(a);
298
+ for (const li of el.querySelectorAll('li[data-step]')) {
299
+ const x = (a.steps ?? []).find((y) => y.id === li.dataset.step);
300
+ li.querySelector('small').textContent = x?.state === 'run' && running ? `${clockOf(running.s)} / ${clockOf(running.limit)}` : x?.s !== undefined ? `${x.s} s` : x?.state === 'todo' ? `${mlimit(x.id)} s` : '';
301
+ }
302
+ el.querySelector('.m-force-now').hidden = DEVICE || !running || !running.past || !MNEXT.has(running.id);
303
+ el.querySelector('.m-force-stop').hidden = DEVICE || a.kind === 'force';
304
+ el.querySelector('.row').hidden = el.querySelector('.m-force-now').hidden && el.querySelector('.m-force-stop').hidden;
305
+ }
306
+ /* The report of its last action, in one line: how it ended, its steps and their seconds, the memory freed, what to do. */
307
+ const MREPORT = {
308
+ start: () => [uiSaid('set-mk-start', 'Started'), uiSaid('set-mk-start-no', 'Not started')],
309
+ stop: () => [uiSaid('set-mk-stop', 'Stopped'), uiSaid('set-mk-stop-no', 'Not stopped')],
310
+ restart: () => [uiSaid('set-mk-restart', 'Restarted'), uiSaid('set-mk-restart-no', 'Not restarted')],
311
+ resize: () => [uiSaid('set-mk-resize', 'Resized'), uiSaid('set-mk-resize-no', 'Not resized')],
312
+ sleep: () => [uiSaid('set-mk-sleep', 'Asleep'), uiSaid('set-mk-sleep-no', 'Did not go to sleep')],
313
+ force: () => [uiSaid('set-mk-force', 'Forced off'), uiSaid('set-mk-force-no', 'Not forced off')],
314
+ };
315
+ const MADVICE = { force: () => uiSaid('set-madv-force', 'Try Force stop'), manager: () => uiSaid('set-madv-manager', 'The VM manager may need a restart'), again: () => uiSaid('set-madv-again', 'Try again in a moment'), look: () => uiSaid('set-madv-look', 'Look at its state') };
316
+ const mreportWords = (r) => {
317
+ if (!r) return '';
318
+ const [yes, no] = (MREPORT[r.kind] ?? MREPORT.stop)();
319
+ const steps = (r.steps ?? []).filter((x) => x.result !== 'skip').map((x) => `${MMARK[x.result] ?? ''}\u00a0${mstepSaid(x.id)} ${x.s ?? 0} s`).join(' ');
320
+ const freed = r.ok && r.freedGb ? uiSaid('set-mrep-freed', '{gb} GB freed', { gb: Number(r.freedGb).toFixed(1) }) : '';
321
+ return [`${r.ok ? yes : no} \u00b7 ${r.s ?? 0} s`, steps, freed, r.preempted ? uiSaid('set-mrep-replaced', 'Replaced by Force stop') : r.advice ? MADVICE[r.advice]?.() : ''].filter(Boolean).join(' \u00b7 ');
238
322
  };
239
323
  /* `source()`: the latest word of the server (its list, or the terminal opening). */
240
324
  const panel = { source: () => undefined, of: '', key: '', timer: 0, open: false };
@@ -280,7 +364,11 @@
280
364
  mascot(at >= p.steps.length - 1 ? 'waking' : 'trying');
281
365
  $('notice-steps').hidden = !panel.open; $('notice-spin').hidden = true;
282
366
  $('notice-count').textContent = `${at + 1} / ${p.steps.length} \u00b7 ${clockOf(s)}`;
283
- $('notice-text').textContent = `${stepNow(p, tool)}${s >= 180 ? ` \u2014 ${usualFor(p.kind, s)}` : ''}`;
367
+ /* Its machine stopping under it (a restart, a resize): which step, what is done, what can be done now. */
368
+ const owner = conversations.find((x) => x.name === panel.of.split('/')[0]);
369
+ paintMlive($('notice-mlive'), owner);
370
+ const mline = mstepLine(owner?.machine);
371
+ $('notice-text').textContent = mline || `${stepNow(p, tool)}${s >= 180 ? ` \u2014 ${usualFor(p.kind, s)}` : ''}`;
284
372
  return true;
285
373
  };
286
374
  /* Shown, or brought up to date when it is shown already (its wheel keeps turning). */
@@ -1000,6 +1088,8 @@
1000
1088
  (seen on the live site: the "Start" button vanished before it could be
1001
1089
  pressed). */
1002
1090
  let welcoming = false;
1091
+ const MLIVE_SAY = { stop: 'stopping', force: 'forcing off', sleep: 'going to sleep', start: 'starting' };
1092
+ const MLIVE_TITLE = { stop: () => uiSaid('set-mt-stop', 'Stopping its machine'), force: () => uiSaid('set-mt-force', 'Forcing its machine off'), sleep: () => uiSaid('set-mt-sleep', 'Going to sleep'), start: () => uiSaid('set-mt-start', 'Starting its machine') };
1003
1093
  /* What can be done to the conversation shown, from what is known of it now. */
1004
1094
  function paintActions() {
1005
1095
  const c = conversations.find((x) => x.name === current);
@@ -1009,8 +1099,7 @@
1009
1099
  $('files-open').hidden = $('share').hidden = !usable;
1010
1100
  /* Given its chat alone: the files of the chat open from the chat; Files holds only what was given to the device itself. */
1011
1101
  if (noTerminal()) $('files-open').hidden = deviceShared.length === 0;
1012
- $('sleep').hidden = !usable || c.asleep === true;
1013
- $('restart').hidden = DEVICE || !usable;
1102
+ paintMachineActs(c);
1014
1103
  /* At hand, on top of its settings: wake when asleep, else restart, sleep, its terminal. */
1015
1104
  $('quick-wake').hidden = !c || c.asleep !== true;
1016
1105
  $('hand-terminal').hidden = !usable || noTerminal();
@@ -1018,6 +1107,53 @@
1018
1107
  /* Its own sheet is there as soon as it exists: archiving one that failed is done from it. */
1019
1108
  $('folders').hidden = DEVICE || !c;
1020
1109
  }
1110
+ /* ITS MACHINE'S FIVE BUTTONS, never hidden: greyed when they do not apply, with why in their title. */
1111
+ function paintMachineActs(c) {
1112
+ const busy = Boolean(c?.machine) || !c || c.phase !== 'ready' || holds(c);
1113
+ const asleep = c?.asleep === true;
1114
+ const stopped = c?.stopped === true || (!asleep && c?.health?.state === 'Stopped');
1115
+ const why = {
1116
+ busy: !c || c.phase === 'ready' || c.phase === 'restarting' ? uiSaid('set-mwhy-busy', 'Another action is running') : uiSaid('set-mwhy-notready', 'Not ready yet'),
1117
+ runs: uiSaid('set-mwhy-runs', 'It runs already'), stopped: uiSaid('set-mwhy-stopped', 'Already stopped'), asleep: uiSaid('set-mwhy-asleep', 'Asleep already'),
1118
+ };
1119
+ const set = (id, on, title, own = '') => { const b = $(id); b.hidden = false; b.disabled = !on; b.title = on ? own : title; };
1120
+ set('m-start', !busy && (asleep || stopped), busy ? why.busy : why.runs, uiSaid('set-mwhat-start', 'Starts its machine and its tool'));
1121
+ set('m-stop', !busy && !stopped, busy ? why.busy : why.stopped, uiSaid('set-mwhat-stop', 'Stops it cleanly, by force if it hangs'));
1122
+ set('restart', !busy, why.busy, uiSaid('set-mwhat-restart', 'Stops it, then starts it again'));
1123
+ set('sleep', !busy && !asleep && !stopped, busy ? why.busy : asleep ? why.asleep : why.stopped, 'Freezes the tool as it is; it wakes when you open the conversation');
1124
+ const forceable = c && ['ready', 'restarting'].includes(c.phase) && c.machine?.kind !== 'force' && (Boolean(c.machine) || (!stopped && !asleep));
1125
+ set('m-force', Boolean(forceable), c?.machine?.kind === 'force' ? why.busy : stopped ? why.stopped : asleep ? uiSaid('set-mwhy-nothing', 'Asleep: nothing runs') : why.busy, uiSaid('set-mwhat-force', 'Cuts it off, like a power cut'));
1126
+ paintMlive($('m-live'), c);
1127
+ const r = c?.machineReport;
1128
+ $('m-report').hidden = Boolean(c?.machine) || !r;
1129
+ $('m-report').textContent = mreportWords(r);
1130
+ $('m-report').dataset.ok = String(r?.ok === true);
1131
+ }
1132
+ /* ASKED IN THE PAGE, in one line: what is lost. Start and Sleep lose nothing: not asked. */
1133
+ const MCONFIRM = {
1134
+ stop: () => [uiSaid('set-mconf-stop', 'Stop it? What the tool does now is interrupted.'), uiSaid('set-m-stop', 'Stop')],
1135
+ restart: () => [uiSaid('set-mconf-restart', 'Restart it? The tool restarts; its files stay.'), uiSaid('set-m-restart', 'Restart')],
1136
+ force: () => [uiSaid('set-mconf-force', 'Like a power cut: nothing is saved.'), uiSaid('set-m-force', 'Force stop')],
1137
+ };
1138
+ function askMachine(kind) {
1139
+ const [line, yes] = MCONFIRM[kind]();
1140
+ $('m-confirm-text').textContent = line;
1141
+ $('m-confirm-yes').textContent = yes;
1142
+ $('m-confirm-yes').className = kind === 'force' ? 'danger' : 'primary';
1143
+ $('m-confirm-yes').onclick = () => { $('m-confirm').hidden = true; if (kind === 'restart') void restartMachine(true); else void machineAct(kind); };
1144
+ $('m-confirm').hidden = false;
1145
+ $('m-confirm-yes').focus();
1146
+ }
1147
+ /* One action on its machine; its steps come with the list (refreshed faster meanwhile). */
1148
+ async function machineAct(kind) {
1149
+ const name = current;
1150
+ if (!name) return;
1151
+ $('panel-error').hidden = true;
1152
+ if (kind === 'stop' || kind === 'force') disconnect();
1153
+ try { await post(`${API}/conversations/${encodeURIComponent(name)}/machine`, { action: kind }); }
1154
+ catch (error) { $('panel-error').textContent = error.message; $('panel-error').hidden = false; }
1155
+ await refresh();
1156
+ }
1021
1157
  /* `keepSheets`: the same conversation, looked at again (its state changed):
1022
1158
  a sheet the owner has open is not shut under their fingers. */
1023
1159
  function enter(keepSheets = false) {
@@ -1056,14 +1192,32 @@
1056
1192
  const s = Math.max(0, Math.floor((Date.now() - since) / 1000));
1057
1193
  const clock = `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
1058
1194
  const now = conversations.find((x) => x.name === c.name);
1059
- const usual = s < 180 ? 'A restart usually takes one to two minutes.' : 'This is taking longer than usual: the machine may be slow to stop or to start. It goes on by itself.';
1060
- $('notice-text').textContent = `${now?.step ?? c.step ?? 'Restarting its machine'}... ${clock} so far. ${usual} The tool starts again by itself; its files and its chat are kept.`;
1195
+ /* Its step, what is done and what can be done now (the steps and the buttons under it): never a vague wait. */
1196
+ const mline = mstepLine(now?.machine);
1197
+ paintMlive($('notice-mlive'), now);
1198
+ $('notice-text').textContent = mline ? `${mline}. ${clock} so far.` : `${now?.step ?? c.step ?? 'Restarting its machine'}... ${clock} so far. The tool starts again by itself; its files and its chat are kept.`;
1061
1199
  };
1062
1200
  show(''); tell(); $('notice-spin').hidden = false;
1063
1201
  clearInterval(restartTicking);
1064
1202
  restartTicking = setInterval(() => { const now = conversations.find((x) => x.name === c.name); if (current !== c.name || now?.phase !== 'restarting' || notice.hidden) { clearInterval(restartTicking); return; } tell(); }, 1000);
1065
1203
  return;
1066
1204
  }
1205
+ /* ITS MACHINE BEING STOPPED, FORCED OFF, PUT TO SLEEP OR STARTED by its owner: the steps over its terminal. */
1206
+ if (c && c.machine && c.phase === 'ready') {
1207
+ disconnect(); say(MLIVE_SAY[c.machine.kind] ?? 'busy', 'connecting');
1208
+ show(''); $('notice-spin').hidden = false;
1209
+ const tell = () => {
1210
+ const now = conversations.find((x) => x.name === c.name);
1211
+ if (current !== c.name || !now?.machine || notice.hidden) { clearInterval(restartTicking); return; }
1212
+ paintMlive($('notice-mlive'), now);
1213
+ $('notice-text').textContent = mstepLine(now.machine) || MLIVE_TITLE[now.machine.kind]?.() || '';
1214
+ };
1215
+ tell();
1216
+ clearInterval(restartTicking); restartTicking = setInterval(tell, 1000);
1217
+ return;
1218
+ }
1219
+ /* STOPPED BY ITS OWNER: it stays stopped until somebody starts it. */
1220
+ if (c && c.stopped === true && !socket && c.phase === 'ready') { say('stopped', 'waiting'); show(uiSaid('set-stopped-page', 'Stopped. It starts when you start it.'), uiSaid('set-m-start', 'Start'), connect); return; }
1067
1221
  if (c && c.phase === 'moving') { disconnect(); say('moving', 'connecting'); show(`Moving its work: ${c.step ?? 'working'}... The tool is stopped meanwhile and starts again by itself.`); $('notice-spin').hidden = false; return; }
1068
1222
  if (c && c.phase === 'failed') { disconnect(); say('failed', 'ended'); show(c.error ?? 'This conversation could not be built.', DEVICE ? undefined : 'Build it again', () => void rebuild()); return; }
1069
1223
  /* Given its chat and not its terminal: the chat is the whole page, and no terminal is ever opened. */
@@ -1773,7 +1927,7 @@
1773
1927
  async function refresh() {
1774
1928
  clearTimeout(pollTimer);
1775
1929
  try {
1776
- const mark = (x) => (x ? `${x.phase}/${x.asleep === true}/${holds(x)}` : '');
1930
+ const mark = (x) => (x ? `${x.phase}/${x.asleep === true}/${holds(x)}/${Boolean(x.machine)}/${x.stopped === true}` : '');
1777
1931
  const before = mark(conversations.find((x) => x.name === current));
1778
1932
  if (DEVICE) {
1779
1933
  const mePath = () => `${API}/me?c=${encodeURIComponent(current)}`;
@@ -1818,7 +1972,7 @@
1818
1972
  /* The panel is open: what the answerer did meanwhile is said there. */
1819
1973
  if (!DEVICE && panelShown) { void paintAnswerer(); paintWakeups(); paintMachine(conversations.find((x) => x.name === current)); }
1820
1974
  /* A start told step by step is asked about more often: its tool appears soon after its last step. */
1821
- if (home) pollTimer = setTimeout(refresh, conversations.some(holds) ? 1500 : conversations.some((c) => c.phase === 'building' || c.phase === 'moving' || c.phase === 'restarting') ? 2500 : 10000);
1975
+ if (home) pollTimer = setTimeout(refresh, conversations.some(holds) || conversations.some((c) => c.machine) ? 1500 : conversations.some((c) => c.phase === 'building' || c.phase === 'moving' || c.phase === 'restarting') ? 2500 : 10000);
1822
1976
  }
1823
1977
 
1824
1978
  /* ---------- A NEW CONVERSATION: a page of its own, as Settings ----------
@@ -2627,7 +2781,7 @@
2627
2781
  try { await post(`${API}/conversations/${encodeURIComponent(name)}/restart`, {}); healthDismissed = ''; await refresh(); enter(); }
2628
2782
  catch (error) { show(error.message, 'Back', enter); }
2629
2783
  }
2630
- $('restart').addEventListener('click', () => { void restartMachine(false); });
2784
+ $('restart').addEventListener('click', () => askMachine('restart'));
2631
2785
  $('health-restart').addEventListener('click', () => { void restartMachine(false); });
2632
2786
  $('health-check').addEventListener('click', async () => {
2633
2787
  $('health-check').disabled = true; $('health-check').textContent = 'Looking...';
@@ -2773,6 +2927,8 @@
2773
2927
  /* When its tool starts: its last session, or a new one -- for a tool that can take one up. */
2774
2928
  $('resume-box').hidden = DEVICE || !here?.resumes;
2775
2929
  for (const b of $('resume-on').children) b.setAttribute('aria-pressed', String((b.dataset.on === 'true') === (here?.resume !== false)));
2930
+ /* A stop that hangs: forced by itself (the default), or asked first. */
2931
+ for (const b of $('m-escalate').children) b.setAttribute('aria-pressed', String((b.dataset.on === 'true') === (here?.stopEscalate !== false)));
2776
2932
  /* Whether its tool asks before acting -- for a tool that can be given every right in its machine. */
2777
2933
  $('rights-box').hidden = DEVICE || !here?.rights;
2778
2934
  for (const b of $('ask-first').children) b.setAttribute('aria-pressed', String((b.dataset.on === 'true') === (here?.askFirst === true)));
@@ -11492,10 +11648,21 @@
11492
11648
  disconnect();
11493
11649
  say('going to sleep', 'connecting');
11494
11650
  show('Going to sleep...'); mascot('asleep');
11495
- try { await post(`${API}/conversations/${encodeURIComponent(name)}/sleep`); await refresh(); enter(); }
11651
+ try { await post(`${API}/conversations/${encodeURIComponent(name)}/machine`, { action: 'sleep' }); await refresh(); enter(); }
11496
11652
  catch (error) { say('awake', 'ended'); show(error.message, 'Back to the terminal', connect); }
11497
11653
  }
11498
11654
  $('sleep').addEventListener('click', () => void sleepMachine());
11655
+ $('m-start').addEventListener('click', () => void machineAct('start'));
11656
+ $('m-stop').addEventListener('click', () => askMachine('stop'));
11657
+ $('m-force').addEventListener('click', () => askMachine('force'));
11658
+ $('m-confirm-no').addEventListener('click', () => { $('m-confirm').hidden = true; });
11659
+ for (const b of $('m-escalate').children) {
11660
+ b.addEventListener('click', async () => {
11661
+ $('panel-error').hidden = true;
11662
+ try { await post(`${API}/conversations/${encodeURIComponent(current)}/machine`, { escalate: b.dataset.on === 'true' }); await refresh(); paintMachine(conversations.find((x) => x.name === current)); }
11663
+ catch (error) { $('panel-error').textContent = error.message; $('panel-error').hidden = false; }
11664
+ });
11665
+ }
11499
11666
  /* The quick actions at the top of the panel do the same as the Machine chapter's. */
11500
11667
  $('hand-terminal').addEventListener('click', () => { leavePanel(); seeTerminal(); });
11501
11668
  $('quick-wake').addEventListener('click', () => { leavePanel(); seeTerminal(); });
package/web/index.html CHANGED
@@ -131,10 +131,20 @@
131
131
  </div>
132
132
  <div class="hand-acts" id="panel-actions">
133
133
  <button type="button" id="quick-wake" class="primary" hidden>Wake it</button>
134
- <button type="button" id="restart" hidden data-said="set-restart-dots">Restart&hellip;</button>
135
- <button type="button" id="sleep" hidden title="Freezes the tool as it is; it wakes when you open the conversation" data-said="set-sleep">Sleep</button>
134
+ <!-- ITS MACHINE (09-11): always the same five, never hidden; what does not apply is greyed, with why
135
+ (app.js, paintMachineActs). One action at a time; Force stop takes the place of any other. -->
136
+ <button type="button" id="m-start" data-said="set-m-start">Start</button>
137
+ <button type="button" id="m-stop" data-said="set-m-stop">Stop</button>
138
+ <button type="button" id="restart" data-said="set-restart-dots">Restart&hellip;</button>
139
+ <button type="button" id="sleep" title="Freezes the tool as it is; it wakes when you open the conversation" data-said="set-sleep">Sleep</button>
140
+ <button type="button" id="m-force" class="danger" data-said="set-m-force">Force stop</button>
136
141
  <button type="button" id="hand-terminal" data-said="set-terminal">Terminal</button>
137
142
  </div>
143
+ <!-- Asked in the page, in one line: what is lost. -->
144
+ <div id="m-confirm" class="m-confirm" role="alertdialog" aria-labelledby="m-confirm-text" hidden><span id="m-confirm-text"></span><button type="button" id="m-confirm-yes" class="primary"></button><button type="button" id="m-confirm-no" data-said="set-mconf-no">Cancel</button></div>
145
+ <!-- The action under way, step by step (the escalation, in one line), then its report. -->
146
+ <div id="m-live" class="m-live" hidden></div>
147
+ <p id="m-report" class="hint m-report" role="status" hidden></p>
138
148
  </section>
139
149
  <nav id="panel-tabs" class="settings-tabs" role="tablist" aria-label="Categories of its settings">
140
150
  <button type="button" role="tab" data-group="general" data-said="set-tab-general">General</button>
@@ -193,6 +203,8 @@
193
203
  <div id="resume-box" hidden>
194
204
  <div class="set-row"><div class="set-what"><b>When its tool starts</b><small id="resume-hint">After a wake or restart</small></div><div class="set-control"><div class="levels" id="resume-on" role="group" aria-label="When its tool starts"><button type="button" data-on="true">Resume its last session</button><button type="button" data-on="false">Start fresh</button></div></div></div>
195
205
  </div>
206
+ <!-- A STOP THAT HANGS: forced by itself (the default), or asked first (conversations.mjs, stopEscalate). -->
207
+ <div class="set-row"><div class="set-what"><b data-said="set-mesc">If a stop hangs</b></div><div class="set-control"><div class="levels" id="m-escalate" role="group" aria-label="If a stop hangs"><button type="button" data-on="true" data-said="set-mesc-auto">Force it</button><button type="button" data-on="false" data-said="set-mesc-ask">Ask me</button></div></div></div>
196
208
  <div class="panel-top"><b>Memory, cores and disk</b></div>
197
209
  <form id="machine-size" autocomplete="off">
198
210
  <label for="machine-memory">Memory</label>
@@ -522,6 +534,8 @@
522
534
  <!-- A start told step by step: what it is, which step of how many, and the time so far. -->
523
535
  <div id="notice-head" hidden><p id="notice-title"></p><p id="notice-count"></p></div>
524
536
  <ol id="notice-steps" aria-live="polite" hidden></ol>
537
+ <!-- Its machine's action under way (a restart, a stop, a force stop): the same steps as in its settings. -->
538
+ <div id="notice-mlive" class="m-live" hidden></div>
525
539
  <p id="notice-text"></p>
526
540
  <ul id="notice-health" class="health-lines" hidden></ul>
527
541
  <div class="row"><button id="notice-action" type="button" class="primary"></button><button id="notice-restart" type="button" hidden>Restart the machine...</button><button id="notice-cancel" type="button" hidden>Cancel</button></div>
package/web/style.css CHANGED
@@ -2984,3 +2984,31 @@ button.kit-switch[aria-checked="true"]::after { left: 18px; background: var(--ok
2984
2984
  #share-here .kit-access .given-row { padding: 10px 12px; }
2985
2985
  .kit-asset.dev-thing > .kit-asset-ic { flex: none; }
2986
2986
  .device-panel .kit-aspanel-foot.as-foot { flex-direction: row; justify-content: flex-start; align-items: center; }
2987
+
2988
+ /* ITS MACHINE'S ACTION, STEP BY STEP (09-11): the escalation in one line -- polite, forced, soft kill,
2989
+ hard kill, checked. Done ticked, the one under way pulsing with its time, those to come dimmed; the
2990
+ two ways to hurry it right under. A list down the page on a phone. */
2991
+ .m-confirm { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 10px; padding: 8px 10px; border: 1px solid var(--line); border-radius: 8px; background: var(--panel); font-size: .875rem; }
2992
+ .m-confirm[hidden], .m-live[hidden], .m-report[hidden] { display: none; }
2993
+ .m-confirm span { flex: 1 1 14rem; }
2994
+ .m-live { display: grid; gap: 8px; margin-top: 10px; justify-items: start; }
2995
+ #notice .m-live { justify-items: center; margin: 0; }
2996
+ .mstep { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; align-items: center; gap: 4px; font-size: .8125rem; }
2997
+ .mstep li { display: inline-flex; align-items: baseline; gap: 5px; padding: 3px 9px; border: 1px solid var(--line); border-radius: 999px; color: var(--ink2); white-space: nowrap; }
2998
+ .mstep li.arr { border: 0; padding: 0; opacity: .55; }
2999
+ .mstep li .mark { font-weight: 700; }
3000
+ .mstep li small { font-variant-numeric: tabular-nums; font-size: .75rem; opacity: .85; }
3001
+ .mstep li[data-state="todo"] { opacity: .5; }
3002
+ .mstep li[data-state="ok"] { color: var(--ok); border-color: color-mix(in srgb, var(--ok) 50%, transparent); }
3003
+ .mstep li[data-state="skip"] { opacity: .45; text-decoration: line-through; }
3004
+ .mstep li[data-state="fail"], .mstep li[data-state="timeout"], .mstep li[data-state="cut"] { color: var(--warn); border-color: color-mix(in srgb, var(--warn) 50%, transparent); }
3005
+ .mstep li[data-state="run"] { color: var(--ink); font-weight: 600; border-color: var(--brass); }
3006
+ @media (prefers-reduced-motion: no-preference) { .mstep li[data-state="run"] { animation: mstep-pulse 1.4s ease-in-out infinite; } @keyframes mstep-pulse { 50% { box-shadow: 0 0 0 4px color-mix(in srgb, var(--brass) 28%, transparent); } } }
3007
+ .m-live .row { display: flex; flex-wrap: wrap; gap: 8px; }
3008
+ .m-report { margin: 8px 0 0; }
3009
+ .m-report[data-ok="false"] { color: var(--warn); }
3010
+ @media (max-width: 520px) {
3011
+ .mstep { flex-direction: column; align-items: stretch; }
3012
+ .mstep li.arr { display: none; }
3013
+ #notice .m-live { justify-items: stretch; }
3014
+ }