clavarium 0.2.5-next.1 → 0.2.6-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.
@@ -95,7 +95,7 @@ UPDATER="$CODE/current/app/deploy/updater.mjs"
95
95
  UPDATE_STATE="/var/lib/clavarium/update"
96
96
 
97
97
  refuse() { echo "REFUSED: $*" >&2; exit 78; }
98
- usage() { echo "usage: clavarium-host [--say-only [--data DIR] [--mnt DIR]] <vm|shelf|folder|work|view|tools|mounts|operator|machines|net|git|server|update> <verb> [arguments]" >&2; exit 64; }
98
+ usage() { echo "usage: clavarium-host [--say-only [--data DIR] [--mnt DIR]] <vm|shelf|folder|work|view|tools|mounts|operator|machines|disks|net|git|server|update> <verb> [arguments]" >&2; exit 64; }
99
99
 
100
100
  SAY="no"; DATA=""; MNT=""
101
101
  while [ $# -gt 0 ]; do
@@ -138,6 +138,15 @@ run() { if [ "$SAY" = "yes" ]; then printf '%s\n' "$*"; else exec "$@"; fi; }
138
138
  is_name() { [[ "$1" =~ ^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$ ]]; }
139
139
  vm_of() { is_name "${1#clv-}" && [ "$1" != "${1#clv-}" ] || refuse "not one of our VMs: ${1:-<empty>}"; }
140
140
  number() { [[ "$1" =~ ^[0-9]{1,6}$ ]] || refuse "not a number: ${1:-<empty>}"; }
141
+ # A disk or partition named by its device: /dev/sdX, /dev/vdX, /dev/nvmeNnN(pN),
142
+ # /dev/xvdX, /dev/mmcblkN(pN), with a digit or two at the end; a loop device only
143
+ # for the tests (CLAVARIUM_DISKS_LOOP=1, which sudo never passes). It must exist.
144
+ disk_dev() {
145
+ local re='^/dev/((sd|vd|xvd|hd)[a-z]{1,2}[0-9]{0,2}|nvme[0-9]{1,2}n[0-9]{1,2}(p[0-9]{1,2})?|mmcblk[0-9]{1,2}(p[0-9]{1,2})?)$'
146
+ [ "${CLAVARIUM_DISKS_LOOP:-}" = "1" ] && re='^/dev/((sd|vd|xvd|hd)[a-z]{1,2}[0-9]{0,2}|nvme[0-9]{1,2}n[0-9]{1,2}(p[0-9]{1,2})?|mmcblk[0-9]{1,2}(p[0-9]{1,2})?|loop[0-9]{1,3}(p[0-9]{1,2})?)$'
147
+ [[ "${1:-}" =~ $re ]] || refuse "not a disk: ${1:-<empty>}"
148
+ [ "$SAY" = "yes" ] || [ -b "$1" ] || refuse "no such disk: $1"
149
+ }
141
150
  # A ready-made machine: "clvshelf-" and the moment it was started, in UTC.
142
151
  # Never "clv-...": no conversation verb can reach it, and no shelf verb can
143
152
  # reach a conversation.
@@ -301,12 +310,19 @@ case "$AREA $VERB" in
301
310
  # Does the VM manager answer at all? Asked now and then by the server
302
311
  # (vmwatch.mjs); bounded, so that a VM manager that hangs is an answer.
303
312
  [ $# -eq 0 ] || usage
304
- run timeout 25 "$MULTIPASS" list --format csv ;;
313
+ run timeout 90 "$MULTIPASS" list --format csv ;;
305
314
  "vm revive")
306
315
  # The VM manager has not answered for minutes: its daemon restarted.
307
316
  # Asked by the server at most once in hours (vmwatch.mjs), never by a page.
308
317
  [ $# -eq 0 ] || usage
309
318
  run timeout 170 snap restart multipass.multipassd ;;
319
+ "vm states")
320
+ # EVERY MACHINE'S STATE AT ONCE: one question to the VM manager instead of one per
321
+ # machine. It answers one question at a time, and a machine frozen inside makes each
322
+ # question about it wait 10 seconds: asked machine by machine, they queued up and held
323
+ # back every other machine too (21-10). Bounded.
324
+ [ $# -eq 0 ] || usage
325
+ run timeout 120 "$MULTIPASS" list --format json ;;
310
326
  "vm info")
311
327
  [ $# -eq 1 ] || usage; vm_of "$1"
312
328
  run "$MULTIPASS" info "$1" --format json ;;
@@ -444,6 +460,33 @@ case "$AREA $VERB" in
444
460
  if [ "$SAY" = "yes" ]; then printf '%s\n' "$MULTIPASS list --format csv (ready-made machines only)"; exit 0; fi
445
461
  "$MULTIPASS" list --format csv | cut -d, -f1 | grep -E '^clvshelf-[0-9]{8}-[0-9]{6}$' || true
446
462
  exit 0 ;;
463
+ "server logs")
464
+ # WHAT THE SERVER'S PROGRAMS SAID, for Settings (This server, Logs): one
465
+ # source, over a span; read-only, bounded. The page masks what looks
466
+ # like a secret before showing it.
467
+ # server logs <clavarium|machines|updates|web|signin|tunnel|system> <1|6|24|168|boot>
468
+ [ $# -eq 2 ] || usage
469
+ case "$1" in
470
+ clavarium) units=(-u clavarium.service -u 'clavarium-view-*' -u clavarium-tools-view.service -u clavarium-move-machines.service) ;;
471
+ machines) units=(-u snap.multipass.multipassd.service) ;;
472
+ updates) units=(-u clavarium-update.service -u clavarium-certificate.service) ;;
473
+ web) units=(-u caddy.service -u oauth2-proxy.service) ;;
474
+ signin) units=(-u dex.service) ;;
475
+ tunnel) units=(-u clavarium-tunnel.service) ;;
476
+ system) units=(-k) ;;
477
+ *) refuse "not a source of logs: $1" ;;
478
+ esac
479
+ case "$2" in 1|6|24|168) since=(--since "-$2h") ;; boot) since=(-b) ;; *) refuse "not a span: $2 (1, 6, 24, 168 hours, or boot)" ;; esac
480
+ if [ "$SAY" = "yes" ]; then echo "journalctl ${units[*]} ${since[*]} -o short-iso --no-pager (the last 200000 lines)"; exit 0; fi
481
+ journalctl "${units[@]}" "${since[@]}" -o short-iso --no-pager -n 200000 2>/dev/null | cut -c1-2000 || true
482
+ exit 0 ;;
483
+ "server restart")
484
+ # THIS SERVER STARTED AGAIN, asked from the page: in two seconds, by
485
+ # systemd, so that the page is answered first. Its machines go on.
486
+ [ $# -eq 0 ] || usage
487
+ if [ "$SAY" = "yes" ]; then echo "systemd-run --on-active=2 systemctl restart clavarium.service"; exit 0; fi
488
+ systemd-run --quiet --collect --unit="clavarium-restart-$(date +%s)" --on-active=2 /usr/bin/systemctl restart clavarium.service
489
+ exit 0 ;;
447
490
  "server room")
448
491
  # WHAT THE SERVER HAS LEFT, for Settings (This server) and for the
449
492
  # reserve that creating, starting, waking or growing a machine must
@@ -642,6 +685,64 @@ case "$AREA $VERB" in
642
685
  elif [ "$VERB" = "failures" ]; then [ $# -eq 1 ] && number "$1" || usage
643
686
  else [ $# -eq 1 ] && [[ "$1" =~ ^[a-z0-9._+-]{1,64}@([a-z0-9-]{1,63}\.)+[a-z]{2,24}$ ]] || refuse "not an e-mail address: ${1:-<empty>}"; fi
644
687
  run "$UPDATER_NODE" "$CODE/current/app/deploy/operators.mjs" "$VERB" "$@" ;;
688
+ "disks list")
689
+ # THE DISKS OF THIS SERVER, whole, formatted or not, for Settings (This
690
+ # server, Move all the machines): lsblk, as JSON. Read-only. The page
691
+ # leaves out what is no disk to keep machines on (floppy, CD, read-only,
692
+ # tiny, loop devices).
693
+ [ $# -eq 0 ] || usage
694
+ if [ "$SAY" = "yes" ]; then echo "lsblk -J -b -o NAME,PATH,TYPE,SIZE,FSTYPE,LABEL,UUID,MOUNTPOINT,MODEL,RO,RM,PKNAME,TRAN"; exit 0; fi
695
+ lsblk -J -b -o NAME,PATH,TYPE,SIZE,FSTYPE,LABEL,UUID,MOUNTPOINT,MODEL,RO,RM,PKNAME,TRAN
696
+ exit 0 ;;
697
+ "disks mount")
698
+ # A DISK (or a partition) THAT HOLDS A FILE SYSTEM, mounted under /mnt
699
+ # for good (/etc/fstab, by its UUID, "nofail": the server starts without
700
+ # it). Nothing on it is changed.
701
+ [ $# -eq 1 ] || usage
702
+ disk_dev "$1"
703
+ fs="$(lsblk -dno FSTYPE -- "$1")"; uuid="$(lsblk -dno UUID -- "$1")"
704
+ case "$fs" in ext4|xfs|btrfs) : ;; *) refuse "no file system the machines can live on in $1 (${fs:-none}): prepare the disk instead" ;; esac
705
+ [ -z "$(lsblk -dno MOUNTPOINT -- "$1")" ] || refuse "$1 is mounted already"
706
+ [ -n "$uuid" ] || refuse "$1 has no UUID"
707
+ at="/mnt/$(basename -- "$1")"
708
+ [ ! -e "$at" ] || [ -z "$(ls -A "$at" 2>/dev/null)" ] || refuse "$at exists and is not empty"
709
+ if [ "$SAY" = "yes" ]; then echo "mkdir $at; fstab UUID=$uuid $at $fs defaults,nofail 0 2; mount $at"; exit 0; fi
710
+ mkdir -p -- "$at"
711
+ grep -q "^UUID=$uuid " /etc/fstab || printf 'UUID=%s %s %s defaults,nofail 0 2\n' "$uuid" "$at" "$fs" >> /etc/fstab
712
+ systemctl daemon-reload; mount -- "$at"
713
+ echo "mounted $at"
714
+ exit 0 ;;
715
+ "disks prepare")
716
+ # A WHOLE DISK ERASED AND MADE READY FOR MACHINES: one partition, ext4,
717
+ # mounted under /mnt/<its name> for good. Its name must be given twice
718
+ # (the second time typed by the owner on the page). Refused for the
719
+ # system's disk, and for a disk with anything mounted or in use.
720
+ [ $# -eq 2 ] || usage
721
+ disk_dev "$1"
722
+ [ "$(lsblk -dno TYPE -- "$1")" = "disk" ] || [ "${CLAVARIUM_DISKS_LOOP:-}" = "1" ] || refuse "$1 is not a whole disk"
723
+ [ "$2" = "$(basename -- "$1")" ] || refuse "the name typed is not the disk's: ${2:-<empty>} (it is $(basename -- "$1"))"
724
+ lsblk -nro MOUNTPOINT -- "$1" | grep -q . && refuse "something on $1 is mounted: not erased"
725
+ lsblk -nro FSTYPE -- "$1" | grep -qx swap && refuse "$1 holds swap: not erased"
726
+ # A disk under LVM, RAID, encryption or ZFS is part of something larger (maybe the system): never.
727
+ lsblk -nro FSTYPE,TYPE -- "$1" | grep -qE 'LVM2_member|crypto_LUKS|linux_raid_member|zfs_member|[[:space:]](lvm|crypt|raid[0-9]*|dm)$' && refuse "$1 is part of a volume, an array or an encrypted disk: not erased here"
728
+ root_disk="$(lsblk -nro PKNAME "$(findmnt -nvo SOURCE /)" 2>/dev/null || true)"
729
+ [ "$(basename -- "$1")" != "$root_disk" ] || refuse "$1 is the system's disk"
730
+ at="/mnt/$(basename -- "$1")"
731
+ [ ! -e "$at" ] || [ -z "$(ls -A "$at" 2>/dev/null)" ] || refuse "$at exists and is not empty"
732
+ if [ "$SAY" = "yes" ]; then echo "wipefs -a $1; sfdisk --label gpt $1 (one partition); mkfs.ext4 -L clavarium; fstab; mount $at"; exit 0; fi
733
+ wipefs -a -- "$1" >/dev/null
734
+ echo 'type=linux' | sfdisk --quiet --label gpt -- "$1" >/dev/null
735
+ partprobe -- "$1" 2>/dev/null || true; udevadm settle
736
+ part="$(lsblk -lnpo NAME,TYPE -- "$1" | awk '$2=="part"{print $1; exit}')"
737
+ [ -n "$part" ] || refuse "no partition appeared on $1"
738
+ mkfs.ext4 -q -F -L clavarium -- "$part"
739
+ udevadm settle
740
+ uuid="$(lsblk -dno UUID -- "$part")"
741
+ mkdir -p -- "$at"
742
+ printf 'UUID=%s %s ext4 defaults,nofail 0 2\n' "$uuid" "$at" >> /etc/fstab
743
+ systemctl daemon-reload; mount -- "$at"
744
+ echo "prepared $part, mounted $at"
745
+ exit 0 ;;
645
746
  "machines places")
646
747
  # WHERE ALL THE MACHINES COULD GO (deploy/move-machines.sh), for the
647
748
  # page: each disk mounted where the VM manager may keep them (/mnt,
@@ -675,6 +776,26 @@ case "$AREA $VERB" in
675
776
  printf 'state %s\n' "$(systemctl show -p ActiveState --value clavarium-move-machines.service 2>/dev/null || echo unknown)"
676
777
  journalctl -u clavarium-move-machines.service -n 12 -o cat --no-pager 2>/dev/null | sed 's/^/said /' || true
677
778
  exit 0 ;;
779
+ "machines old")
780
+ # THE COPY LEFT BEHIND by a move (deploy/move-machines.sh copies, never
781
+ # moves): its size, once the machines run from the new place. Read-only.
782
+ # old <MB> (nothing printed: no move, or nothing left)
783
+ [ $# -eq 0 ] || usage
784
+ if [ "$SAY" = "yes" ]; then echo "du of /var/snap/multipass/common/data/multipassd/vault and cache/multipassd"; exit 0; fi
785
+ old="/var/snap/multipass/common"
786
+ if [ -n "$MOVED_TO" ] && [ "$SHELF_STORE" = "$MOVED_TO" ] && { [ -d "$old/data/multipassd/vault" ] || [ -d "$old/cache/multipassd" ]; }; then
787
+ printf 'old %s\n' "$(du -smx "$old/data/multipassd/vault" "$old/cache/multipassd" 2>/dev/null | awk '{s+=$1} END{print s+0}')"
788
+ fi
789
+ exit 0 ;;
790
+ "machines forget-old")
791
+ # That copy removed -- only when no running machine uses any file of it.
792
+ [ $# -eq 0 ] || usage
793
+ old="/var/snap/multipass/common"
794
+ [ -n "$MOVED_TO" ] && [ "$SHELF_STORE" = "$MOVED_TO" ] || refuse "the machines were not moved: there is no old copy"
795
+ if [ "$SAY" = "yes" ]; then echo "rm -rf $old/data/multipassd/vault $old/cache/multipassd"; exit 0; fi
796
+ { pgrep -a qemu-system 2>/dev/null || true; } | grep -q -- "$old/data/multipassd/vault" && refuse "a machine still runs from the old copy: not removed"
797
+ rm -rf -- "$old/data/multipassd/vault" "$old/cache/multipassd"
798
+ exit 0 ;;
678
799
  "net taps")
679
800
  [ $# -eq 0 ] || usage
680
801
  run pgrep -a qemu-system ;;
@@ -19,7 +19,7 @@
19
19
  # back. If not, everything is put back as it was and said;
20
20
  # 5. Clavarium started again: its conversations start their machines as
21
21
  # they are opened.
22
- # Then: once all works, the old copy can go:
22
+ # Then: once all works, the old copy can go (Settings offers it), or by hand:
23
23
  # sudo rm -rf /var/snap/multipass/common/data/multipassd/vault /var/snap/multipass/common/cache/multipassd
24
24
  #
25
25
  # Exit codes: 0 done (or would be, --dry-run); 64 bad parameters; 78 refused,
@@ -105,5 +105,5 @@ say "Clavarium started again: its conversations start their machines as they are
105
105
  systemctl start clavarium.service clavarium-update.timer 2>/dev/null || true
106
106
  echo
107
107
  echo "Done: the machines are on $TO ($(df -h --output=avail "$TO" | tail -1 | tr -d ' ') free there)."
108
- echo "Once everything works, the old copy can go:"
108
+ echo "Once everything works, the old copy can go (Settings, Resources, The disks: Remove the old copy), or:"
109
109
  echo " sudo rm -rf $OLD/data/multipassd/vault $OLD/cache/multipassd"
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.5-next.1",
3
+ "version": "0.2.6-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.5-next.1",
9
+ "version": "0.2.6-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.5-next.1",
3
+ "version": "0.2.6-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
@@ -68,6 +68,9 @@
68
68
  * POST /api/secrets/<NAME>/rename {name}: its value and where it is handed go with it
69
69
  * GET /api/conversations/<name>/health-react POST the same {on?, message?, command?}: what it does when its machine is short
70
70
  * GET /api/machines/places GET /api/machines/moving POST /api/machines/move {to}: all the machines to another disk
71
+ * POST /api/machines/forget-old: the copy a move left behind, removed
72
+ * GET /api/machines/disks: every disk, whole POST /api/machines/mount {path} POST /api/machines/prepare {path, typed}: erased
73
+ * GET /api/server/logs?source=&span= what the server's programs said POST /api/server/restart
71
74
  * GET /api/operators who may sign in POST /api/operators {email} -> {email, password}: shown once
72
75
  * POST /api/operators/<email>/password -> {email, password} POST /api/operators/<email>/disable|enable|remove
73
76
  * POST /api/conversations/<name>/secrets {secret, attached}
@@ -97,6 +100,7 @@
97
100
  * another site cannot send. */
98
101
  import { sameOrigin } from './bridge.mjs';
99
102
  import { Refusal } from './conversations.mjs';
103
+ import { VmUnknown } from './vm.mjs';
100
104
  import { list, download, importFile, page, PAGE_HEADERS, changeRoute, IMAGE_HEADERS } from './files.mjs';
101
105
  import { WORK_TAB } from './resources.mjs';
102
106
  import { transcribe, AUDIO_MAX } from './voice.mjs';
@@ -120,7 +124,7 @@ function readBody(request, max = BODY_MAX) {
120
124
  }
121
125
 
122
126
  /* Returns true when the request was an API request (answered here). */
123
- export async function handleApi(request, response, conversations, headers, resources, originOk = sameOrigin, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove) {
127
+ export async function handleApi(request, response, conversations, headers, resources, originOk = sameOrigin, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs) {
124
128
  const { pathname } = new URL(request.url ?? '/', 'http://local');
125
129
  if (!pathname.startsWith('/api/')) return false;
126
130
  const send = (status, body) => {
@@ -223,6 +227,8 @@ export async function handleApi(request, response, conversations, headers, resou
223
227
  /* Who may sign in (operators.mjs): none in local mode. */
224
228
  const reactOf = /^\/api\/conversations\/([^/]+)\/health-react$/.exec(pathname);
225
229
  if (reactOf && reacting) return send(200, reacting.settings(decodeURIComponent(reactOf[1]))), true;
230
+ if (pathname === '/api/server/logs' && serverLogs) return send(200, await serverLogs.read(query.get('source') ?? 'clavarium', query.get('span') ?? '1')), true;
231
+ if (pathname === '/api/machines/disks' && machinesMove) return send(200, await machinesMove.disks()), true;
226
232
  if (pathname === '/api/machines/places' && machinesMove) return send(200, await machinesMove.places()), true;
227
233
  if (pathname === '/api/machines/moving' && machinesMove) return send(200, await machinesMove.moving()), true;
228
234
  if (pathname === '/api/operators') return send(200, team ? { operators: team.list(), me: identity } : { local: true }), true;
@@ -322,6 +328,10 @@ export async function handleApi(request, response, conversations, headers, resou
322
328
  const reactSet = /^\/api\/conversations\/([^/]+)\/health-react$/.exec(pathname);
323
329
  if (reactSet && reacting) { const n = decodeURIComponent(reactSet[1]); if (!conversations.list().some((c) => c.name === n)) throw new Refusal(404, 'No such conversation.'); return send(200, reacting.set(n, body)), true; }
324
330
  if (pathname === '/api/machines/move' && machinesMove) return send(202, await machinesMove.move(String(body.to ?? ''))), true;
331
+ if (pathname === '/api/server/restart' && serverLogs) return send(202, await serverLogs.restart()), true;
332
+ if (pathname === '/api/machines/mount' && machinesMove) return send(200, await machinesMove.mount(String(body.path ?? ''))), true;
333
+ if (pathname === '/api/machines/prepare' && machinesMove) return send(200, await machinesMove.prepare(String(body.path ?? ''), body.typed)), true;
334
+ if (pathname === '/api/machines/forget-old' && machinesMove) return send(200, await machinesMove.forgetOld()), true;
325
335
  if (pathname === '/api/operators' && team) return send(201, await team.add(body.email)), true;
326
336
  const op = /^\/api\/operators\/([^/]{3,200})\/(password|disable|enable|remove)$/.exec(pathname);
327
337
  if (op && team) {
@@ -462,7 +472,7 @@ export async function handleApi(request, response, conversations, headers, resou
462
472
  const conversation = decodeURIComponent(machine[1]);
463
473
  if (machine[2] === 'health') {
464
474
  if (!health || !conversations.list().some((c) => c.name === conversation)) throw new Refusal(404, 'No such conversation.');
465
- return send(200, await health.check(conversation)), true;
475
+ return send(200, await health.check(conversation, { asked: true })), true;
466
476
  }
467
477
  if (machine[2] === 'restart') return send(202, await conversations.restart(conversation)), true;
468
478
  return send(202, await conversations.resize(conversation, { memoryMb: body.memoryMb, diskGb: body.diskGb, cpus: body.cpus })), true;
@@ -512,7 +522,7 @@ export async function handleApi(request, response, conversations, headers, resou
512
522
  return send(200, { ok: true }), true;
513
523
  } catch (error) {
514
524
  /* A git failure also says which (`kind`), and an fsck id the owner may waive (`offer`). */
515
- if (error instanceof Refusal) return send(error.status, { error: error.message, ...(error.kind ? { kind: error.kind } : {}), ...(error.offer ? { offer: error.offer } : {}), ...(error.retry ? { retry: true } : {}) }), true;
525
+ if (error instanceof Refusal || error instanceof VmUnknown) return send(error.status, { error: error.message, ...(error.kind ? { kind: error.kind } : {}), ...(error.offer ? { offer: error.offer } : {}), ...(error.retry ? { retry: true } : {}) }), true;
516
526
  return send(500, { error: 'Something failed on the server.' }), true;
517
527
  }
518
528
  }
@@ -149,6 +149,12 @@ export class Conversations {
149
149
  /* Told by the server: the tool's screen is being drawn (or did not come
150
150
  in time). Its start is over. */
151
151
  attached(name) { this.#end(name); }
152
+ /* SOMEBODY USED IT (typed in its terminal): when, for the list (Recent), at most once a minute. */
153
+ touch(name) {
154
+ const c = this.#store.get(name);
155
+ if (!c || (c.lastActiveAt && Date.now() - new Date(c.lastActiveAt).getTime() < 60_000)) return;
156
+ this.#store.patch(name, { lastActiveAt: new Date().toISOString() });
157
+ }
152
158
 
153
159
  /* WHAT THE TOOL DOES AT ITS NEXT START, as the step after "The tool
154
160
  starts": takes up its last session ('resume'), starts a new one as its
@@ -279,7 +285,7 @@ export class Conversations {
279
285
  const cloned = await this.#vms.clone(name, from, memoryMb);
280
286
  const started = cloned.code === 0 ? await this.#vms.start(name) : cloned;
281
287
  readyMade = started.code === 0;
282
- if (!readyMade && await this.#vms.state(name) !== undefined) await this.#vms.remove(name);
288
+ if (!readyMade && await this.#vms.state(name, { fresh: true }) !== undefined) await this.#vms.remove(name);
283
289
  if (!this.#store.get(name)) return undefined; /* archived meanwhile */
284
290
  }
285
291
  if (!readyMade) {
@@ -358,7 +364,7 @@ export class Conversations {
358
364
  if (c.phase === 'building') throw new Refusal(409, 'This conversation is still being built.');
359
365
  const tool = this.#tools.find((t) => t.id === c.tool);
360
366
  if (!tool) throw new Refusal(400, 'The tool of this conversation is no longer offered.');
361
- const state = await this.#vms.state(name);
367
+ const state = await this.#vms.state(name, { fresh: true });
362
368
  if (state !== undefined && c.phase !== 'failed') throw new Refusal(409, 'This conversation has its machine: there is nothing to build again.');
363
369
  await this.room({ kind: 'create', name, memoryMb: c.memoryMb });
364
370
  this.#cancelStop(name);
@@ -393,7 +399,7 @@ export class Conversations {
393
399
  /* Each step reached is told to the screen that opens, with the steps
394
400
  (the record has them too, for any other page). */
395
401
  const tell = (text) => say(text, this.#store.get(name)?.progress);
396
- let state = await this.#vms.state(name);
402
+ let state = await this.#vms.state(name, { fresh: true });
397
403
  if (state === undefined) { this.left(name); throw new Refusal(410, 'The machine of this conversation no longer exists.'); }
398
404
  /* What a wake goes through, unless a build or a restart is already
399
405
  being told. From sleep, its tool is most likely there as it was
@@ -1060,7 +1066,7 @@ export class Conversations {
1060
1066
  this.drop(name);
1061
1067
  const kept = this.#store.get(name).work === 'kept';
1062
1068
  this.#store.remove(name);
1063
- if (await this.#vms.state(name) !== undefined) await this.#vms.remove(name);
1069
+ if (await this.#vms.state(name, { fresh: true }) !== undefined) await this.#vms.remove(name);
1064
1070
  /* Its work is moved aside on the server, not erased. */
1065
1071
  if (kept) await this.#vms.workAside(name);
1066
1072
  }
package/server/health.mjs CHANGED
@@ -72,6 +72,9 @@ export function readProbe(text, paths = []) {
72
72
  }
73
73
  /* What is kept and shown for one conversation, at most. */
74
74
  const PROBLEMS_MAX = 20;
75
+ /* A machine that did not answer is left alone this long, twice as long each time, up to QUIET_MAX_MS. */
76
+ export const QUIET_MS = 60_000;
77
+ export const QUIET_MAX_MS = 10 * 60_000;
75
78
  const TEXT_MAX = 300;
76
79
 
77
80
  /* The sentences the page shows, and how serious they are: 'ok', 'info',
@@ -87,6 +90,8 @@ export function judge(record) {
87
90
  else if (s === 'Starting' || s === 'Restarting') add('info', 'state', 'starting', 'Its machine is starting.');
88
91
  else if (s === 'Suspended') add('info', 'state', 'asleep', 'Its machine is asleep. It wakes when you open the conversation.');
89
92
  else if (s === 'Stopped') add('info', 'state', 'stopped', 'Its machine is stopped. It starts when you open the conversation.');
93
+ /* The VM manager did not answer: nothing is known of the machine, and nothing is said of it. */
94
+ else if (s === 'Unknown') add('info', 'state', 'unknown', 'The VM manager does not answer just now: its machine is looked at again in a moment.');
90
95
  else if (s !== 'Running') add('bad', 'state', `state:${s}`, `The VM manager says its machine is "${s}".`);
91
96
  if (s === 'Running') {
92
97
  if (record.answering === false) add('bad', 'answer', 'silent', 'Its machine does not answer. Restarting it usually helps.');
@@ -105,7 +110,7 @@ export function judge(record) {
105
110
  }
106
111
 
107
112
  export class Health {
108
- #vms; #conversations; #resources; #records = new Map(); #running = new Map(); #settleMs; #probeMs; #lookMs;
113
+ #vms; #conversations; #resources; #records = new Map(); #running = new Map(); #quiet = new Map(); #settleMs; #probeMs; #lookMs;
109
114
  /* Set by the server: told each judgment (the chat of a conversation says what is wrong: talk.mjs). */
110
115
  judged = () => {};
111
116
 
@@ -118,21 +123,22 @@ export class Health {
118
123
 
119
124
  /* The last thing known, or null. Cheap: nothing is asked. */
120
125
  of(name) { return this.#records.get(name) ?? null; }
121
- forget(name) { this.#records.delete(name); }
126
+ forget(name) { this.#records.delete(name); this.#quiet.delete(name); }
122
127
 
123
128
  /* The look under way (it may be mounting a folder again), or null. */
124
129
  busy(name) { return this.#running.get(name) ?? null; }
125
130
 
126
131
  /* Looks now. One look at a time per conversation: a second caller gets the same. */
127
- check(name, { repair = true } = {}) {
132
+ /* `asked`: by its owner, or after its machine was started: even one left alone is asked. */
133
+ check(name, { repair = true, asked = false } = {}) {
128
134
  const going = this.#running.get(name);
129
135
  if (going) return going;
130
- const look = this.#look(name, repair).finally(() => this.#running.delete(name));
136
+ const look = this.#look(name, repair, asked).finally(() => this.#running.delete(name));
131
137
  this.#running.set(name, look);
132
138
  return look;
133
139
  }
134
140
 
135
- async #look(name, repair) {
141
+ async #look(name, repair, asked = false) {
136
142
  const c = this.#conversations.get(name);
137
143
  if (!c) return null;
138
144
  const at = new Date().toISOString();
@@ -141,8 +147,17 @@ export class Health {
141
147
  const state = await this.#vms.state(name).catch(() => 'Unknown');
142
148
  if (state !== 'Running') return this.#keep(name, { at, state });
143
149
  const paths = this.#resources ? this.#resources.expected(name, c.work === 'kept') : (c.work === 'kept' ? ['/work'] : []);
150
+ /* A machine that did not answer is not asked again at once: each question about it holds
151
+ the VM manager for seconds, and every other machine waits behind it (21-10). */
152
+ const quiet = this.#quiet.get(name);
153
+ if (quiet && !asked && Date.now() < quiet.until) return this.#keep(name, { at, state, answering: false });
144
154
  let facts = await this.#probe(name, paths);
145
- if (!facts) return this.#keep(name, { at, state, answering: false });
155
+ if (!facts) {
156
+ const times = (quiet?.times ?? 0) + 1;
157
+ this.#quiet.set(name, { times, until: Date.now() + Math.min(QUIET_MAX_MS, QUIET_MS * 2 ** (times - 1)) });
158
+ return this.#keep(name, { at, state, answering: false });
159
+ }
160
+ this.#quiet.delete(name);
146
161
  const loose = () => paths.filter((p) => facts.mounts[p] !== 'ok');
147
162
  const remounted = []; const failed = [];
148
163
  if (loose().length > 0 && repair && this.#resources) {
@@ -6,11 +6,58 @@
6
6
  * why: '' when they may go there, or why not (the same disk, too small)
7
7
  * move(at) started; the page loses this server for a while, and finds it again
8
8
  * moving() { state, said: [lines] }: how it goes, or how it went
9
+ * forgetOld() the copy a move left on the first disk removed (oldMb in places():
10
+ * its size, null when there is none)
11
+ * disks() the disks of this server, WHOLE, formatted or not (lsblk): for each,
12
+ * what can be done -- move the machines to one of its file systems,
13
+ * mount one, or prepare (erase) the disk; and why not
14
+ * mount(path) / prepare(path, typed) a file system mounted under /mnt for good;
15
+ * a whole disk erased, one ext4 on it, mounted (its name typed again)
9
16
  */
10
17
  import { Refusal } from './conversations.mjs';
11
18
 
12
19
  const firstLine = (text) => String(text ?? '').trim().split('\n').filter(Boolean).pop()?.replace(/^REFUSED: /, '').slice(0, 200) ?? '';
13
20
  const whole = (x) => (/^\d+$/.test(x ?? '') ? Number(x) : undefined);
21
+ const MB = (bytes) => Math.round(Number(bytes ?? 0) / 1048576);
22
+ export const FILE_SYSTEMS = ['ext4', 'xfs', 'btrfs'];
23
+ const PLACES = /^\/(mnt|media)(\/|$)|^\/home$/;
24
+ const SYSTEM_MOUNTS = /^(\/|\/boot(\/efi)?|\/usr|\/var|\[SWAP\])$/;
25
+ const PART_OF_MORE = /^(LVM2_member|crypto_LUKS|linux_raid_member|zfs_member)$/;
26
+ /* A disk the machines could live on: not a floppy or a CD, not read-only, not tiny; a loop
27
+ device only when it is a disk mounted under /mnt or /media (a snap's is read-only squashfs). */
28
+ function aDisk(d) {
29
+ if (d.ro || /^(fd|sr|zram|ram)\d*/.test(d.name)) return false;
30
+ /* (A conversation's own work disk is a loop device too, mounted elsewhere: never listed.) */
31
+ if (d.type === 'loop') return FILE_SYSTEMS.includes(d.fstype) && /^\/(mnt|media)\//.test(d.mountpoint ?? '');
32
+ return d.type === 'disk' && MB(d.size) >= 4096;
33
+ }
34
+ /* lsblk -J (deploy/clavarium-host, "disks list") as the page needs it. */
35
+ export function readDisks(json) {
36
+ let all;
37
+ try { all = JSON.parse(json).blockdevices ?? []; } catch { return []; }
38
+ const flat = (d) => [d, ...(d.children ?? []).flatMap(flat)];
39
+ return all.filter(aDisk).map((d) => {
40
+ const inside = flat(d);
41
+ const parts = (d.children?.length ? d.children : [d]).map((p) => {
42
+ const deeper = flat(p);
43
+ const mount = deeper.map((x) => x.mountpoint).find(Boolean) ?? null;
44
+ const state = PART_OF_MORE.test(p.fstype ?? '') || deeper.some((x) => ['lvm', 'crypt', 'raid0', 'raid1', 'raid5', 'raid6', 'raid10'].includes(x.type)) ? 'part-of-more'
45
+ : mount && SYSTEM_MOUNTS.test(mount) ? 'system'
46
+ : mount && PLACES.test(mount) && FILE_SYSTEMS.includes(p.fstype) ? 'place'
47
+ : mount ? 'in-use'
48
+ : FILE_SYSTEMS.includes(p.fstype) ? 'mountable'
49
+ : p.fstype ? 'other' : 'empty';
50
+ return { name: p.name, path: p.path, sizeMb: MB(p.size), fstype: p.fstype ?? null, label: p.label ?? null, mount, state };
51
+ });
52
+ const system = parts.some((p) => p.state === 'system') || inside.some((x) => x.mountpoint && SYSTEM_MOUNTS.test(x.mountpoint));
53
+ const busy = parts.some((p) => p.mount || p.state === 'part-of-more');
54
+ return {
55
+ name: d.name, path: d.path, sizeMb: MB(d.size), model: (d.model ?? '').trim() || null, removable: Boolean(d.rm), loop: d.type === 'loop',
56
+ system, parts, prepare: system ? 'it is the system\'s disk' : busy ? 'something on it is in use' : d.type === 'loop' ? 'not a whole disk' : '',
57
+ erases: parts.some((p) => p.fstype),
58
+ };
59
+ });
60
+ }
14
61
 
15
62
  export class MachinesMove {
16
63
  #host; #usedMb;
@@ -31,7 +78,9 @@ export class MachinesMove {
31
78
  : need !== undefined && p.freeMb < need ? `too small: ${Math.round(p.freeMb / 1024)} GB free, about ${Math.ceil(need / 1024)} GB needed`
32
79
  : '';
33
80
  }
34
- return { now, places, needMb: need ?? null };
81
+ const old = await this.#host(['machines', 'old']).catch(() => ({ code: 1 }));
82
+ const oldMb = old.code === 0 ? whole(/^old (\d+)$/m.exec(String(old.stdout ?? ''))?.[1]) ?? null : null;
83
+ return { now, places, needMb: need ?? null, oldMb };
35
84
  }
36
85
  async move(at) {
37
86
  const { places } = await this.places();
@@ -42,6 +91,44 @@ export class MachinesMove {
42
91
  if (r.code !== 0) throw new Refusal(r.code === 78 ? 400 : 502, firstLine(r.stderr) || `exit ${r.code}`);
43
92
  return { started: true, to: `${at.replace(/\/$/, '')}/clavarium-machines` };
44
93
  }
94
+ async forgetOld() {
95
+ const r = await this.#host(['machines', 'forget-old']);
96
+ if (r.code !== 0) throw new Refusal(r.code === 78 ? 409 : 502, firstLine(r.stderr) || `exit ${r.code}`);
97
+ return { removed: true };
98
+ }
99
+ async disks() {
100
+ const [r, places] = await Promise.all([this.#host(['disks', 'list']), this.places().catch(() => null)]);
101
+ if (r.code !== 0) throw new Refusal(502, `The disks could not be listed: ${firstLine(r.stderr) || `exit ${r.code}`}`);
102
+ const disks = readDisks(r.stdout);
103
+ const now = places?.now?.place ?? null;
104
+ for (const d of disks) for (const p of d.parts) {
105
+ const at = places?.places.find((x) => x.at === p.mount);
106
+ if (p.state === 'place') { p.freeMb = at?.freeMb ?? null; p.why = at ? at.why : 'not a place the VM manager may use'; }
107
+ if (now && p.mount && (now === p.mount || now.startsWith(`${p.mount.replace(/\/$/, '')}/`))) p.machines = true;
108
+ }
109
+ /* The machines' disk first, then the others by size. */
110
+ disks.sort((a, b) => Number(b.parts.some((p) => p.machines)) - Number(a.parts.some((p) => p.machines)) || b.sizeMb - a.sizeMb);
111
+ return { disks, needMb: places?.needMb ?? null, now };
112
+ }
113
+ async mount(path) {
114
+ const { disks } = await this.disks();
115
+ const p = disks.flatMap((d) => d.parts).find((x) => x.path === path);
116
+ if (!p) throw new Refusal(404, 'Not a disk of this server.');
117
+ if (p.state !== 'mountable') throw new Refusal(409, 'This one cannot be mounted here: it is in use, or holds no file system the machines can live on.');
118
+ const r = await this.#host(['disks', 'mount', path], { timeoutMs: 120_000 });
119
+ if (r.code !== 0) throw new Refusal(r.code === 78 ? 409 : 502, firstLine(r.stderr) || `exit ${r.code}`);
120
+ return { mounted: String(r.stdout).trim().replace(/^mounted /, '') };
121
+ }
122
+ async prepare(path, typed) {
123
+ const { disks } = await this.disks();
124
+ const d = disks.find((x) => x.path === path);
125
+ if (!d) throw new Refusal(404, 'Not a disk of this server.');
126
+ if (d.prepare) throw new Refusal(409, `Not this one: ${d.prepare}.`);
127
+ if (String(typed ?? '') !== d.name) throw new Refusal(400, `Type its name, ${d.name}, to erase it.`);
128
+ const r = await this.#host(['disks', 'prepare', path, d.name], { timeoutMs: 600_000 });
129
+ if (r.code !== 0) throw new Refusal(r.code === 78 ? 409 : 502, firstLine(r.stderr) || `exit ${r.code}`);
130
+ return { prepared: String(r.stdout).trim() };
131
+ }
45
132
  async moving() {
46
133
  const r = await this.#host(['machines', 'moving']);
47
134
  const lines = String(r.stdout ?? '').split('\n');
package/server/main.mjs CHANGED
@@ -59,6 +59,7 @@ import { Certificate } from './certificate.mjs';
59
59
  import { Operators } from './operators.mjs';
60
60
  import { HealthReact } from './healthreact.mjs';
61
61
  import { MachinesMove } from './machinesmove.mjs';
62
+ import { ServerLogs } from './serverlogs.mjs';
62
63
  import { migrateData } from './dataformat.mjs';
63
64
  import { VmWatch } from './vmwatch.mjs';
64
65
 
@@ -120,7 +121,7 @@ const withoutTmux = (env) => Object.fromEntries(Object.entries(env).filter(([key
120
121
 
121
122
  const REFUSED = 'This Clavarium belongs to someone else: your account is not one of its operators.\n';
122
123
 
123
- function serve(port, conversations, resources, { gate = () => 'local', originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, repair, capacity, updates, instance = new Instance(), certificate, team, reacting, machinesMove } = {}) {
124
+ function serve(port, conversations, resources, { gate = () => 'local', originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, repair, capacity, updates, instance = new Instance(), certificate, team, reacting, machinesMove, serverLogs } = {}) {
124
125
  /* Its manifest carries the name of this Clavarium, or the one a device chose (instance.mjs). */
125
126
  const sendManifest = (response, url) => response.writeHead(200, { ...HEADERS, 'content-type': 'application/manifest+json' }).end(instance.manifest(new URL(url ?? '/', 'http://local').searchParams.get('name') ?? undefined));
126
127
  const sendFile = async (response, file) => {
@@ -158,7 +159,7 @@ function serve(port, conversations, resources, { gate = () => 'local', originOk,
158
159
  response.writeHead(403, { ...HEADERS, 'content-type': 'text/plain; charset=utf-8' }).end(REFUSED);
159
160
  return;
160
161
  }
161
- if (conversations && await handleApi(request, response, conversations, HEADERS, resources, originOk, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove)) return;
162
+ if (conversations && await handleApi(request, response, conversations, HEADERS, resources, originOk, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs)) return;
162
163
  if (pathname === '/manifest.webmanifest' && request.method === 'GET') { sendManifest(response, request.url); return; }
163
164
  const file = FILES[pathname];
164
165
  if (!file || (request.method !== 'GET' && request.method !== 'HEAD')) {
@@ -376,7 +377,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
376
377
  a restart, a move) or looked at and put back if they came loose (after
377
378
  a wake), before its tool starts in them. */
378
379
  all.quiet = (name) => health.busy(name);
379
- all.mounted = async (name, again) => { if (again) await folders.remount(name).catch(() => {}); await health.check(name).catch(() => {}); };
380
+ all.mounted = async (name, again) => { if (again) await folders.remount(name).catch(() => {}); await health.check(name, { asked: true }).catch(() => {}); };
380
381
  /* What the VM manager says each machine has is what is recorded (a record
381
382
  may say otherwise: set by hand, or by an earlier version). Not waited for. */
382
383
  void all.reconcileAll?.().catch(() => {});
@@ -400,17 +401,19 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
400
401
  const certificate = new Certificate({ origin: publicOrigin, alerts });
401
402
  /* All the machines to another disk, from Settings (machinesmove.mjs). */
402
403
  const machinesMove = new MachinesMove({ host: asHost, usedMb: () => capacity.machinesUsedMb() });
404
+ /* What the server's programs said, and this server started again, from Settings (serverlogs.mjs). */
405
+ const serverLogs = new ServerLogs({ host: asHost });
403
406
  if (team) {
404
407
  team.useAlerts(alerts);
405
408
  void team.refresh().catch((error) => console.error(`operators: ${error.message}`));
406
409
  const watching = setInterval(() => { void team.watch().catch(() => {}); }, 60_000); watching.unref?.();
407
410
  }
408
- const { server, listening } = serve(port, all, folders, { gate, originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, repair: (name) => repairTerminal(name) });
411
+ const { server, listening } = serve(port, all, folders, { gate, originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, repair: (name) => repairTerminal(name) });
409
412
  server.on('close', () => { closing = true; stopVmWatch(); stopShelf(); stopHealth(); stopUpdates(); stopWatch(); clearInterval(mailTimer); clearInterval(answerTimer); clearInterval(wakeTimer); clearInterval(gitTimer); talk.stop(); });
410
413
  let closing = false;
411
414
  bridge = attachBridge(server, {
412
415
  onRejoin: (name) => all.rejoin(name),
413
- onTyped: (name, data) => { answerer.typed(name, data); talk.typed(name); },
416
+ onTyped: (name, data) => { answerer.typed(name, data); talk.typed(name); all.touch(name); },
414
417
  spawn: async (name, cols, rows, say) => {
415
418
  const [program, ...argv] = await all.open(name, say);
416
419
  const started = pty.spawn(program, argv, { name: 'xterm-256color', env: withoutTmux(env), cols, rows });
@@ -0,0 +1,43 @@
1
+ /* WHAT THE SERVER'S PROGRAMS SAID, for Settings (This server, Logs): read by the
2
+ * host program (journalctl, as root), one source over a span, and shown to the
3
+ * owner to read, copy whole, or keep as a file. And this server started again
4
+ * from the page.
5
+ *
6
+ * read(source, span) { source, span, text, lines, cut } -- what looks like a
7
+ * secret masked: a value after password=, token:, Bearer...;
8
+ * any run of 32 letters and digits or more (a key, a token)
9
+ * restart() this server starts again in two seconds (its machines go on)
10
+ */
11
+ import { Refusal } from './conversations.mjs';
12
+
13
+ export const SOURCES = ['clavarium', 'machines', 'updates', 'web', 'signin', 'tunnel', 'system'];
14
+ export const SPANS = ['1', '6', '24', '168', 'boot'];
15
+ const TEXT_MAX = 24 * 1024 * 1024;
16
+
17
+ const NAMED = /\b(password|passwd|passphrase|secret|token|api[_-]?key|authorization|cookie|bearer|client[_-]?secret)(["']?\s*[=:]\s*|\s+)("[^"]*"|'[^']*'|\S+)/gi;
18
+ const LONG = /[A-Za-z0-9_+/=]{32,}/g;
19
+ export function mask(text) {
20
+ return String(text).replace(NAMED, (all, word, between) => `${word}${between}[masked]`).replace(LONG, '[masked]');
21
+ }
22
+
23
+ export class ServerLogs {
24
+ #host;
25
+ constructor({ host }) { this.#host = host; }
26
+ async read(source, span) {
27
+ if (!SOURCES.includes(source)) throw new Refusal(400, `Not a source of logs: say one of ${SOURCES.join(', ')}.`);
28
+ if (!SPANS.includes(String(span))) throw new Refusal(400, 'Not a span: 1, 6, 24 or 168 hours, or since the server started (boot).');
29
+ const r = await this.#host(['server', 'logs', source, String(span)], { timeoutMs: 120_000, maxBytes: TEXT_MAX * 2 });
30
+ if (r.code !== 0) throw new Refusal(502, `The logs could not be read: ${String(r.stderr ?? '').trim().split('\n').pop()?.replace(/^REFUSED: /, '').slice(0, 200) || `exit ${r.code}`}`);
31
+ let text = String(r.stdout ?? '');
32
+ /* The newest kept when there is too much: they matter most. */
33
+ const cut = text.length > TEXT_MAX;
34
+ if (cut) text = text.slice(text.length - TEXT_MAX).replace(/^[^\n]*\n/, '');
35
+ text = mask(text);
36
+ return { source, span: String(span), text, lines: text ? text.split('\n').filter(Boolean).length : 0, cut };
37
+ }
38
+ async restart() {
39
+ const r = await this.#host(['server', 'restart']);
40
+ if (r.code !== 0) throw new Refusal(502, `This server could not be started again: ${String(r.stderr ?? '').trim().split('\n').pop()?.slice(0, 200) || `exit ${r.code}`}`);
41
+ return { restarting: true };
42
+ }
43
+ }
package/server/talk.mjs CHANGED
@@ -265,7 +265,12 @@ export class Talk {
265
265
  const r = this.#store.get(name);
266
266
  if (r?.on !== true) return null;
267
267
  /* On, but unreadable just now: still said to be on (the share sheet offers its chat by that). */
268
- try { const now = this.#parley(name).read(); return { waiting: now.waiting, state: now.status?.state ?? null }; } catch { return { waiting: 0, state: null }; }
268
+ try {
269
+ const now = this.#parley(name).read();
270
+ /* Its last message, either way: the list says when it last spoke, and what (app.js, Recent). */
271
+ const last = (now.messages ?? []).filter((m) => m.kind !== 'doing').at(-1);
272
+ return { waiting: now.waiting, state: now.status?.state ?? null, ...(last ? { lastAt: last.at, lastFrom: last.from === 'person' ? 'person' : 'agent', lastText: String(last.short || last.text || '').replace(/\s+/g, ' ').trim().slice(0, 90) } : {}) };
273
+ } catch { return { waiting: 0, state: null }; }
269
274
  }
270
275
 
271
276
  async set(name, on) {
package/server/vm.mjs CHANGED
@@ -51,10 +51,47 @@ export function runner(prefix) {
51
51
  });
52
52
  }
53
53
 
54
+ /* 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']);
56
+ export const STATES_FRESH_MS = 3000;
57
+ /* The VM manager did not say what a machine is in: not an answer about the machine. */
58
+ export class VmUnknown extends Error {
59
+ constructor(why) { super(`The VM manager does not answer just now (${why}): try again in a moment.`); this.status = 503; this.retry = true; }
60
+ }
61
+
54
62
  export class Vms {
55
63
  /* `run(argv, options)` reaches the host program; `prefix` is the same
56
64
  route as an argument vector, for the one caller that needs a terminal. */
57
- constructor(run, prefix) { this.run = run; this.prefix = prefix; }
65
+ #ask; #snapshot = null; #asking = null; #now; #freshMs;
66
+ /* `freshMs`: how long one answer serves every caller (0: only those asking meanwhile). */
67
+ constructor(run, prefix, { now = () => Date.now(), freshMs = STATES_FRESH_MS } = {}) {
68
+ this.#ask = run; this.prefix = prefix; this.#now = now; this.#freshMs = freshMs;
69
+ /* What changes a machine makes the states asked again (not taken from before it). */
70
+ this.run = async (argv, options) => {
71
+ const changes = argv[0] === 'vm' && CHANGES.has(argv[1]);
72
+ if (changes) this.#snapshot = null;
73
+ try { return await this.#ask(argv, options); } finally { if (changes) this.#snapshot = null; }
74
+ };
75
+ }
76
+
77
+ /* EVERY MACHINE'S STATE, in one question to the VM manager, shared by every caller for a
78
+ few seconds (and by those who ask while it is being asked). */
79
+ async #states(fresh = false) {
80
+ if (!fresh && this.#snapshot && this.#now() - this.#snapshot.at < this.#freshMs) return this.#snapshot;
81
+ if (this.#asking) return this.#asking;
82
+ this.#asking = (async () => {
83
+ const r = await this.#ask(['vm', 'states'], { timeoutMs: 130_000 }).catch((error) => ({ code: 1, stdout: '', stderr: String(error?.message ?? error) }));
84
+ let states = null; let why = '';
85
+ if (r.code === 0) {
86
+ try { states = new Map((JSON.parse(r.stdout).list ?? []).map((x) => [x.name, x.state])); } catch { why = 'its answer could not be read'; }
87
+ } else why = String(r.stderr || r.stdout || `exit ${r.code}`).trim().split('\n').pop().slice(0, 200);
88
+ const snap = { at: this.#now(), states, why };
89
+ /* Not kept when it did not answer: the next caller asks again. */
90
+ this.#snapshot = states ? snap : null;
91
+ return snap;
92
+ })().finally(() => { this.#asking = null; });
93
+ return this.#asking;
94
+ }
58
95
 
59
96
  launch(conversation, memoryMb) {
60
97
  return this.run(['vm', 'launch', vmName(conversation), String(memoryMb)], { timeoutMs: (LAUNCH_SECONDS + 60) * 1000 });
@@ -76,11 +113,16 @@ export class Vms {
76
113
  }
77
114
 
78
115
  /* "Running", "Stopped", "Suspended", ... or undefined when there is no VM. */
79
- async state(conversation) {
116
+ /* Its state, or undefined when the VM manager lists every machine and not this one. A VM
117
+ manager that does not answer (busy, timed out, restarting) says nothing of the machine:
118
+ that throws (VmUnknown), and is never taken for a machine that is gone (21-10: a machine
119
+ frozen inside had "multipass info" fail, read as "no longer exists"). */
120
+ /* `fresh`: asked now (an owner opening it, building it again), not taken from a few seconds ago. */
121
+ async state(conversation, { fresh = false } = {}) {
80
122
  const name = vmName(conversation);
81
- const r = await this.run(['vm', 'info', name]);
82
- if (r.code !== 0) return undefined;
83
- try { return JSON.parse(r.stdout).info?.[name]?.state; } catch { return undefined; }
123
+ const snap = await this.#states(fresh);
124
+ if (!snap.states) throw new VmUnknown(snap.why);
125
+ return snap.states.get(name);
84
126
  }
85
127
 
86
128
  /* Shows a folder kept by this server in the VM, under /resources/<name>.
@@ -9,7 +9,9 @@
9
9
  * within REVIVE_EVERY_MS, so that it never loops.
10
10
  */
11
11
  export const EVERY_MS = 60_000;
12
- export const STUCK_MS = 5 * 60_000;
12
+ /* Restarting it suspends and resumes EVERY machine: every terminal drops (21-10). Only when it
13
+ has said nothing at all for this long. */
14
+ export const STUCK_MS = 10 * 60_000;
13
15
  export const REVIVE_EVERY_MS = 6 * 3600_000;
14
16
 
15
17
  const said = (r) => String(r?.stderr || r?.stdout || '').trim().split('\n').filter(Boolean).pop()?.slice(0, 200) || `exit ${r?.code}`;
@@ -26,7 +28,7 @@ export class VmWatch {
26
28
 
27
29
  /* One look: 'ok', 'down', 'down; restarted already', 'revived' or 'revive failed'. */
28
30
  async look() {
29
- const r = await this.#run(['vm', 'ping'], { timeoutMs: 30_000 }).catch((e) => ({ code: 1, stderr: e.message }));
31
+ const r = await this.#run(['vm', 'ping'], { timeoutMs: 100_000 }).catch((e) => ({ code: 1, stderr: e.message }));
30
32
  if (r.code === 0) {
31
33
  if (!this.ok) this.#log('vm manager: it answers again');
32
34
  this.ok = true; this.#downSince = null;
package/web/app.js CHANGED
@@ -857,6 +857,11 @@
857
857
  || (c.phase === 'ready' && !c.asleep && ['warn', 'bad'].includes(c.health?.level)));
858
858
  /* Hidden conversations are shown on a click on "N hidden", for this page only. */
859
859
  let showHidden = false;
860
+ /* Recent: a few, or all of them (for this page only). */
861
+ let showAllRecent = false;
862
+ /* A row held or dragged: the list is not painted again under the finger (the browser would cancel
863
+ the touch on a row replaced); it is once the drag ends. */
864
+ let listHeld = false; let paintLater = false;
860
865
  /* ---------- FOLDERS, ORDER, SEARCH ----------
861
866
  One level of folders: a word on each conversation, kept by the server
862
867
  with the order, so that every device shows the same list. Those in no
@@ -872,9 +877,21 @@
872
877
  const matches = (c) => [shownName(c), c.name, c.group, c.toolLabel].some((x) => plain(x).includes(plain(query)));
873
878
  const byRank = (a, b) => (a.rank ?? 0) - (b.rank ?? 0);
874
879
  const groupsInOrder = () => [...new Set(conversations.filter((c) => c.group).sort((a, b) => (a.groupRank ?? 0) - (b.groupRank ?? 0)).map((c) => c.group))];
875
- function itemButton(c) {
880
+ /* WHEN IT WAS LAST USED: its last message (sent or received), or a key typed in its terminal. */
881
+ const activityOf = (c) => Math.max(...[c.talk?.lastAt, c.lastActiveAt, c.createdAt].map((x) => (x ? new Date(x).getTime() : 0)));
882
+ const whenWords = (t) => {
883
+ if (!t) return '';
884
+ const d = new Date(t); const now = new Date();
885
+ if (d.toDateString() === now.toDateString()) return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
886
+ const y = new Date(now); y.setDate(now.getDate() - 1);
887
+ if (d.toDateString() === y.toDateString()) return 'yesterday';
888
+ return now - d < 6 * 86_400_000 ? d.toLocaleDateString([], { weekday: 'short' }) : d.toLocaleDateString([], { day: 'numeric', month: 'short' });
889
+ };
890
+ /* `copy`: a row of Needs you or Recent, beside its place in its group: it is not moved by hand.
891
+ `told`: it says what was said last, and when (a copy always; the one list when there is no group). */
892
+ function itemButton(c, copy = false, told = copy) {
876
893
  const b = document.createElement('button');
877
- b.type = 'button'; b.className = 'item'; b.dataset.phase = c.phase; b.dataset.name = c.name;
894
+ b.type = 'button'; b.className = copy ? 'item copy' : 'item'; b.dataset.phase = c.phase; b.dataset.name = c.name;
878
895
  if (c.group) b.dataset.group = c.group;
879
896
  /* Ready, but its tool not there yet: it still reads as under way. */
880
897
  if (holds(c)) b.dataset.busy = 'true';
@@ -889,7 +906,15 @@
889
906
  const under = c.progress && ['building', 'restarting', 'ready'].includes(c.phase) ? stepNow(c.progress, c.toolLabel) : '';
890
907
  sub.textContent = under ? (c.toolLabel && under.includes(c.toolLabel) ? under : `${c.toolLabel} - ${under}`) : holds(c) && c.phase !== 'building' ? `${c.toolLabel} - ${c.progress.kind === 'build' ? 'starting' : 'restarting'}` : c.phase === 'ready' ? `${c.toolLabel}${c.asleep ? ' - asleep' : ''}` : c.phase === 'building' ? `${c.toolLabel} - ${c.step ?? 'building'}` : c.phase === 'moving' ? `${c.toolLabel} - moving its work` : c.phase === 'restarting' ? `${c.toolLabel} - restarting` : `${c.toolLabel} - failed`;
891
908
  if (c.asleep) b.dataset.asleep = 'true';
892
- b.append(title, sub);
909
+ if (told) {
910
+ /* In words, not a symbol: what a tap on it will do. */
911
+ if (c.asleep) sub.textContent = `${c.toolLabel} - asleep, wakes when opened`;
912
+ /* Beside its name, never in it: the name reads (and is read) as it is. */
913
+ const when = document.createElement('small'); when.className = 'when'; when.textContent = whenWords(activityOf(c));
914
+ if (c.talk?.lastText) { const last = document.createElement('small'); last.className = 'last'; last.textContent = `${c.talk.lastFrom === 'person' ? 'you: ' : ''}${c.talk.lastText}`; b.append(title, last, sub); }
915
+ else b.append(title, sub);
916
+ b.append(when); b.dataset.when = 'true';
917
+ } else b.append(title, sub);
893
918
  /* Found by a search while hidden: said. */
894
919
  if (c.hidden === true && query) { const mark = document.createElement('small'); mark.className = 'shared-mark'; mark.textContent = 'hidden'; b.append(mark); }
895
920
  /* Several models answer its simple questions; or they stopped, and it waits for its owner. */
@@ -904,18 +929,21 @@
904
929
  b.addEventListener('click', () => select(c.name, { step: true }));
905
930
  return b;
906
931
  }
907
- function groupBox(g, inside, all, open) {
908
- const box = document.createElement('div'); box.className = 'group'; box.dataset.group = g;
909
- const head = document.createElement('button'); head.type = 'button'; head.className = 'group-head'; head.dataset.group = g;
932
+ /* `label`: the name shown; the conversations in no group are one of their own ("Not filed", key NONE). */
933
+ const NONE = '\u0000none';
934
+ function groupBox(g, inside, all, open, label = g) {
935
+ const box = document.createElement('div'); box.className = 'group'; box.dataset.group = g === NONE ? '' : g;
936
+ const head = document.createElement('button'); head.type = 'button'; head.className = 'group-head'; head.dataset.group = g === NONE ? '' : g;
937
+ if (g === NONE) head.dataset.fixed = 'true';
910
938
  head.setAttribute('aria-expanded', String(open));
911
939
  const caret = document.createElement('span'); caret.className = 'caret'; caret.setAttribute('aria-hidden', 'true'); caret.textContent = '›';
912
- const label = document.createElement('span'); label.className = 'group-name'; label.textContent = g;
913
- const count = document.createElement('small'); count.className = 'count'; count.textContent = String(all.length);
940
+ const name = document.createElement('span'); name.className = 'group-name'; name.textContent = label;
941
+ const count = document.createElement('small'); count.className = 'count'; count.textContent = `${all.length} conversation${all.length > 1 ? 's' : ''}`;
914
942
  count.setAttribute('aria-label', `${all.length} conversation${all.length > 1 ? 's' : ''}`);
915
943
  /* A small dot for each (up to six); the one that needs you is said even folded. */
916
944
  const dots = document.createElement('span'); dots.className = 'group-dots'; dots.setAttribute('aria-hidden', 'true');
917
945
  for (const c of all.slice(0, 6)) { const d = document.createElement('span'); d.className = 'mini'; d.dataset.phase = holds(c) ? 'building' : c.phase; if (c.asleep) d.dataset.asleep = 'true'; dots.append(d); }
918
- head.append(caret, label, count, dots);
946
+ head.append(caret, name, count, dots);
919
947
  if (all.some(needsYou)) { const n = document.createElement('span'); n.className = 'needs-dot'; n.setAttribute('aria-label', 'one needs you'); head.append(n); head.dataset.needs = 'true'; }
920
948
  head.addEventListener('click', () => {
921
949
  if (query) return;
@@ -923,17 +951,54 @@
923
951
  keepFolded(); paint();
924
952
  });
925
953
  box.append(head);
926
- if (open) { const body = document.createElement('div'); body.className = 'group-body'; body.append(...inside.map(itemButton)); box.append(body); }
954
+ if (open) { const body = document.createElement('div'); body.className = 'group-body'; body.append(...inside.map((c) => itemButton(c))); box.append(body); }
927
955
  return box;
928
956
  }
929
957
  function paint() {
958
+ if (listHeld) { paintLater = true; return; }
930
959
  const items = $('items');
931
960
  items.replaceChildren();
961
+ const top = $('recent'); top.replaceChildren();
932
962
  const hidden = conversations.filter((c) => c.hidden === true);
933
963
  /* The one open stays in sight, hidden or not; a search finds hidden ones too. */
934
964
  const shown = conversations.filter((c) => (query ? matches(c) : c.hidden !== true || showHidden || c.name === current)).sort(byRank);
935
- items.append(...shown.filter((c) => !c.group).map(itemButton));
936
- for (const g of groupsInOrder()) {
965
+ const heading = (text) => { const h = document.createElement('h3'); h.className = 'list-head'; h.textContent = text; return h; };
966
+ const groups = groupsInOrder();
967
+ if (query || DEVICE) {
968
+ /* A search: everything found, in its place. */
969
+ items.append(...shown.filter((c) => !c.group).map((c) => itemButton(c)));
970
+ } else {
971
+ /* NEEDS YOU: whatever its date, until its owner acts; hidden ones too (they said so). */
972
+ const needs = conversations.filter(needsYou).sort((a, b) => activityOf(b) - activityOf(a));
973
+ if (needs.length) top.append(heading('Needs you'), ...needs.map((c) => itemButton(c, true)));
974
+ /* RECENT: by when it was last used; a few, then all. Never a hidden one. Only once there are
975
+ groups: before, the one list below says the same, in the order chosen by hand. */
976
+ const recent = conversations.filter((c) => c.hidden !== true || c.name === current).sort((a, b) => activityOf(b) - activityOf(a));
977
+ const few = 5;
978
+ if (recent.length && groups.length) {
979
+ top.append(heading('Recent'), ...recent.slice(0, showAllRecent ? recent.length : few).map((c) => itemButton(c, true)));
980
+ if (recent.length > few) {
981
+ const more = document.createElement('button'); more.type = 'button'; more.className = 'inline more-recent';
982
+ more.textContent = showAllRecent ? 'Show fewer' : `Show all ${recent.length}`;
983
+ more.addEventListener('click', () => { showAllRecent = !showAllRecent; paint(); });
984
+ top.append(more);
985
+ }
986
+ }
987
+ /* GROUPS: the order chosen by hand, and those in no group as one of their own. */
988
+ if (groups.length) {
989
+ top.append(heading('Groups'));
990
+ const loose = shown.filter((c) => !c.group);
991
+ if (loose.length) items.append(groupBox(NONE, loose, conversations.filter((c) => !c.group).sort(byRank), !folded.has(NONE), 'Not filed'));
992
+ } else {
993
+ /* No group yet: one list, each with what was said last and when. */
994
+ items.append(...shown.map((c) => itemButton(c, false, true)));
995
+ if (conversations.length > 1) {
996
+ const tip = document.createElement('p'); tip.className = 'hint list-tip'; tip.textContent = 'Put conversations in groups to find them by subject: open one, then Settings, Group.';
997
+ items.append(tip);
998
+ }
999
+ }
1000
+ }
1001
+ for (const g of groups) {
937
1002
  const inside = shown.filter((c) => c.group === g);
938
1003
  /* Nothing of it in sight (all hidden, or nothing found): not shown. */
939
1004
  if (inside.length === 0) continue;
@@ -1013,6 +1078,7 @@
1013
1078
  if (!el || el === d.el) return null;
1014
1079
  if (d.kind === 'group') {
1015
1080
  if (el.classList.contains('item')) { if (!el.dataset.group) return null; el = el.closest('.group').querySelector('.group-head'); }
1081
+ if (el.dataset.fixed) return null;
1016
1082
  if (el === d.el) return null;
1017
1083
  }
1018
1084
  const box = el.getBoundingClientRect();
@@ -1025,6 +1091,8 @@
1025
1091
  clearTimeout(drag.timer);
1026
1092
  drag.el.removeAttribute('data-dragging'); $('items').removeAttribute('data-dragging');
1027
1093
  unmark(); drag = null;
1094
+ listHeld = false;
1095
+ if (paintLater) { paintLater = false; paint(); }
1028
1096
  }
1029
1097
  function startDrag() {
1030
1098
  if (!drag) return;
@@ -1056,10 +1124,11 @@
1056
1124
  }
1057
1125
  $('items').addEventListener('pointerdown', (event) => {
1058
1126
  if (DEVICE || query || event.button !== 0) return;
1059
- const el = event.target.closest('.item, .group-head');
1127
+ const el = event.target.closest('.item:not(.copy), .group-head:not([data-fixed])');
1060
1128
  if (!el) return;
1061
1129
  endDrag();
1062
1130
  drag = { el, kind: el.classList.contains('item') ? 'item' : 'group', x: event.clientX, y: event.clientY, id: event.pointerId, on: false, touch: event.pointerType !== 'mouse' };
1131
+ listHeld = true;
1063
1132
  if (drag.touch) drag.timer = setTimeout(startDrag, 450);
1064
1133
  });
1065
1134
  addEventListener('pointermove', (event) => {
@@ -1088,7 +1157,7 @@
1088
1157
  $('items').addEventListener('click', (event) => { if (justDragged) { event.stopPropagation(); event.preventDefault(); } }, true);
1089
1158
  $('items').addEventListener('keydown', async (event) => {
1090
1159
  if (!event.altKey || (event.key !== 'ArrowUp' && event.key !== 'ArrowDown')) return;
1091
- const el = event.target.closest('.item, .group-head');
1160
+ const el = event.target.closest('.item:not(.copy), .group-head:not([data-fixed])');
1092
1161
  if (!el) return;
1093
1162
  event.preventDefault();
1094
1163
  const to = event.key === 'ArrowUp' ? 'up' : 'down';
@@ -3528,7 +3597,7 @@
3528
3597
  for (const [label, value, sub] of rows) {
3529
3598
  if (value === null || value === undefined) continue;
3530
3599
  const dt = document.createElement('dt'); dt.textContent = label; if (sub) dt.className = 'sub';
3531
- const dd = document.createElement('dd'); dd.textContent = typeof value === 'number' ? GB(value) : value; if (sub) dd.className = 'sub';
3600
+ const dd = document.createElement('dd'); dd.textContent = typeof value === 'number' ? GB(value) : value; dd.className = [sub ? 'sub' : '', typeof value === 'number' ? '' : 'words'].filter(Boolean).join(' ');
3532
3601
  dl.append(dt, dd);
3533
3602
  }
3534
3603
  }
@@ -3579,26 +3648,131 @@
3579
3648
  box.append(block);
3580
3649
  }
3581
3650
  }
3582
- /* ALL THE MACHINES TO ANOTHER DISK: the disks they may go to, those they may not and why; then how it went. */
3651
+ /* ALL THE MACHINES TO ANOTHER DISK: every disk of this server, whole, formatted or not; for each,
3652
+ what can be done -- move the machines to it, mount it, prepare (erase) it -- or why not. */
3583
3653
  async function paintMoveMachines() {
3584
- const [p, m] = await Promise.all([fetch(`${API}/machines/places`).then((r) => (r.ok ? r.json() : null)).catch(() => null), fetch(`${API}/machines/moving`).then((r) => (r.ok ? r.json() : null)).catch(() => null)]);
3654
+ const size = (mb) => (mb >= 1024 * 1024 ? `${(mb / 1024 / 1024).toFixed(1)} TB` : GB(mb));
3655
+ const [p, m] = await Promise.all([fetch(`${API}/machines/disks`).then((r) => (r.ok ? r.json() : null)).catch(() => null), fetch(`${API}/machines/moving`).then((r) => (r.ok ? r.json() : null)).catch(() => null)]);
3656
+ const old = await fetch(`${API}/machines/places`).then((r) => (r.ok ? r.json() : null)).catch(() => null);
3585
3657
  const rows = $('move-machines-rows'); rows.replaceChildren();
3586
- if (m?.said?.length) $('move-machines-said').textContent = m.done ? `The last move: ${m.said.find((l) => l.startsWith('Done:'))}` : m.failed ? `The last move did not happen: ${m.said.filter(Boolean).at(-1)}` : m.state === 'active' ? `Moving: ${m.said.at(-1)}` : '';
3587
- if (!p) return;
3588
- if (!p.places.length) rows.append(el('p', 'hint', 'No other disk is mounted under /mnt or /media: the VM manager can only keep its machines there (or under /home).'));
3589
- for (const x of p.places) {
3590
- const row = el('div', 'folder');
3591
- row.append(el('b', '', x.at), el('small', 'hint', ` ${Math.round(x.freeMb / 1024)} GB free of ${Math.round(x.sizeMb / 1024)} GB${x.why ? ` -- ${x.why}` : ''}`));
3592
- const go = el('button', 'danger', 'Move them here...'); go.type = 'button'; go.disabled = Boolean(x.why);
3593
- go.addEventListener('click', () => {
3594
- if (go.dataset.sure !== 'yes') { go.dataset.sure = 'yes'; go.textContent = `Yes: stop every machine and this server, and move them to ${x.at}`; return; }
3595
- go.disabled = true;
3596
- void post(`${API}/machines/move`, { to: x.at }).then(() => { $('move-machines-said').textContent = 'Moving: this server stops now, and comes back by itself. Reload this page in a few minutes.'; }).catch((error) => { $('move-machines-said').textContent = error.message; go.disabled = false; });
3658
+ const said = (text) => { $('move-machines-said').textContent = text; };
3659
+ if (m?.said?.length) said(m.done ? `The last move: ${m.said.find((l) => l.startsWith('Done:'))}` : m.failed ? `The last move did not happen: ${m.said.filter(Boolean).at(-1)}` : m.state === 'active' ? `Moving: ${m.said.at(-1)}` : '');
3660
+ /* A move copies, never moves: the copy left behind takes its room until it is removed. */
3661
+ if (old?.oldMb) {
3662
+ const row = el('div', 'folder'); row.id = 'move-machines-old';
3663
+ row.append(el('b', '', 'The old copy'), el('small', 'hint', ` ${GB(old.oldMb)} left on the first disk by the move; the machines run from ${old.now?.place ?? 'the new place'}`));
3664
+ const forget = el('button', 'danger', 'Remove the old copy...'); forget.type = 'button';
3665
+ forget.addEventListener('click', () => {
3666
+ if (forget.dataset.sure !== 'yes') { forget.dataset.sure = 'yes'; forget.textContent = `Yes: remove ${GB(old.oldMb)} for good`; return; }
3667
+ forget.disabled = true;
3668
+ void post(`${API}/machines/forget-old`, {}).then(() => { said(`The old copy was removed: ${GB(old.oldMb)} free again.`); void paintMoveMachines(); }).catch((error) => { said(error.message); forget.disabled = false; });
3597
3669
  });
3598
- row.append(go); rows.append(row);
3670
+ row.append(forget); rows.append(row);
3599
3671
  }
3672
+ if (!p) { rows.append(el('p', 'hint', 'The disks cannot be listed just now.')); return; }
3673
+ for (const d of p.disks) {
3674
+ const card = el('div', 'disk-card'); card.dataset.disk = d.name;
3675
+ const head = el('div', 'disk-head');
3676
+ head.append(el('b', '', d.model ? `${d.model}` : d.loop ? 'A disk image' : 'A disk'), el('span', 'disk-size', size(d.sizeMb)), el('code', 'disk-name', d.name));
3677
+ card.append(head);
3678
+ const notes = [];
3679
+ if (d.system) notes.push("The system's disk.");
3680
+ if (d.parts.some((x) => x.machines)) notes.push('The machines are here now.');
3681
+ if (d.removable) notes.push('Removable: the machines would stop if it were unplugged.');
3682
+ if (notes.length) card.append(el('p', 'hint', notes.join(' ')));
3683
+ /* What is on it, without the little partitions a system keeps for starting. */
3684
+ for (const x of d.parts.filter((q) => q.sizeMb >= 256 || d.parts.length === 1)) {
3685
+ if (x.state === 'empty' && d.parts.length === 1 && x.name === d.name) { card.append(el('p', 'disk-part', 'Empty: never formatted.')); continue; }
3686
+ const line = el('div', 'disk-part');
3687
+ const what = { system: `used by the system (${x.mount})`, place: `mounted at ${x.mount}`, 'in-use': `in use at ${x.mount}`, mountable: `${x.fstype}, not mounted`, other: `${x.fstype}: not a file system the machines can live on`, empty: 'no file system', 'part-of-more': 'part of a volume, an array or an encrypted disk' }[x.state];
3688
+ line.append(el('span', '', `${x.name === d.name ? 'The whole disk' : x.name}${x.label ? ` "${x.label}"` : ''}: ${size(x.sizeMb)}, ${what}${x.freeMb != null ? `, ${size(x.freeMb)} free` : ''}`));
3689
+ if (x.state === 'place' && !x.machines) {
3690
+ const go = el('button', 'danger', 'Move the machines here...'); go.type = 'button'; go.disabled = Boolean(x.why);
3691
+ if (x.why) line.append(el('small', 'hint', ` -- ${x.why}`));
3692
+ go.addEventListener('click', () => {
3693
+ if (go.dataset.sure !== 'yes') { go.dataset.sure = 'yes'; go.textContent = `Yes: stop every machine and this server, and move them to ${x.mount}`; return; }
3694
+ go.disabled = true;
3695
+ void post(`${API}/machines/move`, { to: x.mount }).then(() => said('Moving: this server stops now, and comes back by itself. Reload this page in a few minutes.')).catch((error) => { said(error.message); go.disabled = false; });
3696
+ });
3697
+ line.append(go);
3698
+ }
3699
+ if (x.state === 'mountable') {
3700
+ const mount = el('button', '', 'Mount it'); mount.type = 'button';
3701
+ mount.addEventListener('click', () => { mount.disabled = true; void post(`${API}/machines/mount`, { path: x.path }).then((r) => { said(`Mounted at ${r.mounted}: nothing on it was changed.`); void paintMoveMachines(); }).catch((error) => { said(error.message); mount.disabled = false; }); });
3702
+ line.append(mount);
3703
+ }
3704
+ card.append(line);
3705
+ }
3706
+ /* PREPARE: erase it, one file system on it, mounted. Its name typed again. */
3707
+ if (!d.prepare) {
3708
+ const box = el('div', 'disk-prepare');
3709
+ const go = el('button', 'danger', d.erases ? 'Erase and prepare for the machines...' : 'Prepare for the machines...'); go.type = 'button';
3710
+ go.addEventListener('click', () => {
3711
+ go.hidden = true;
3712
+ const warn = el('p', 'error', d.erases ? `Everything on ${d.name} (${size(d.sizeMb)}) is erased for good: ${d.parts.filter((q) => q.fstype).map((q) => `${q.name}${q.label ? ` "${q.label}"` : ''} (${q.fstype})`).join(', ')}.` : `${d.name} (${size(d.sizeMb)}) gets one file system, mounted at /mnt/${d.name}.`);
3713
+ const field = el('input', ''); field.placeholder = d.name; field.setAttribute('aria-label', `Type ${d.name} to go on`); field.autocomplete = 'off'; field.spellcheck = false;
3714
+ const yes = el('button', 'danger', `Erase ${d.name}`); yes.type = 'button'; yes.disabled = true;
3715
+ field.addEventListener('input', () => { yes.disabled = field.value.trim() !== d.name; });
3716
+ const no = el('button', '', 'Cancel'); no.type = 'button'; no.addEventListener('click', () => { void paintMoveMachines(); });
3717
+ yes.addEventListener('click', () => { yes.disabled = true; said(`Preparing ${d.name}...`); void post(`${API}/machines/prepare`, { path: d.path, typed: field.value.trim() }).then((r) => { said(`${r.prepared}. The machines can be moved there now.`); void paintMoveMachines(); }).catch((error) => { said(error.message); yes.disabled = false; }); });
3718
+ const row = el('div', 'row'); row.append(el('span', 'hint', `Type ${d.name}:`), field, yes, no);
3719
+ box.append(warn, row);
3720
+ });
3721
+ box.append(go); card.append(box);
3722
+ } else if (!d.system && !d.parts.some((x) => x.state === 'place')) card.append(el('p', 'hint', `Not prepared here: ${d.prepare}.`));
3723
+ rows.append(card);
3724
+ }
3725
+ if (!p.disks.some((d) => !d.system)) rows.append(el('p', 'hint', 'No other disk: plug one in (or add one to this server), then open this again.'));
3600
3726
  }
3601
3727
  $('move-machines-box').addEventListener('toggle', () => { if ($('move-machines-box').open) void paintMoveMachines(); });
3728
+ /* WHAT THE SERVER'S PROGRAMS SAID: one source over a span, to read, copy whole or keep as a file. */
3729
+ let logsShown = null;
3730
+ $('logs-show').addEventListener('click', async () => {
3731
+ const source = $('logs-source').value; const span = $('logs-span').value;
3732
+ $('logs-said').textContent = 'Reading...'; $('logs-show').disabled = true;
3733
+ try {
3734
+ const r = await fetch(`${API}/server/logs?source=${encodeURIComponent(source)}&span=${encodeURIComponent(span)}`);
3735
+ const body = await r.json().catch(() => ({}));
3736
+ if (!r.ok) throw new Error(body.error ?? `The logs could not be read (${r.status}).`);
3737
+ logsShown = body;
3738
+ $('logs-text').textContent = body.text || '';
3739
+ $('logs-text').hidden = !body.text; $('logs-acts').hidden = !body.text;
3740
+ $('logs-said').textContent = body.lines ? `${body.lines} line${body.lines > 1 ? 's' : ''}${body.cut ? ' (the newest only: there were more)' : ''}.` : 'Nothing was said over that span.';
3741
+ /* The newest at the bottom, in sight. */
3742
+ $('logs-text').scrollTop = $('logs-text').scrollHeight;
3743
+ } catch (error) { $('logs-said').textContent = error.message; }
3744
+ $('logs-show').disabled = false;
3745
+ });
3746
+ $('logs-copy').addEventListener('click', async () => {
3747
+ if (!logsShown?.text) return;
3748
+ try { await navigator.clipboard.writeText(logsShown.text); $('logs-said').textContent = `Copied: ${logsShown.lines} lines.`; }
3749
+ catch {
3750
+ /* No clipboard (plain http, an old browser): all of it selected, for Ctrl+C. */
3751
+ const range = document.createRange(); range.selectNodeContents($('logs-text'));
3752
+ const sel = getSelection(); sel.removeAllRanges(); sel.addRange(range);
3753
+ $('logs-said').textContent = 'Selected: copy it with Ctrl+C (or the menu of your device).';
3754
+ }
3755
+ });
3756
+ $('logs-save').addEventListener('click', () => {
3757
+ if (!logsShown?.text) return;
3758
+ const a = document.createElement('a');
3759
+ a.href = URL.createObjectURL(new Blob([logsShown.text], { type: 'text/plain' }));
3760
+ a.download = `clavarium-${logsShown.source}-${logsShown.span === 'boot' ? 'since-start' : `${logsShown.span}h`}-${new Date().toISOString().slice(0, 16).replace(':', '')}.log`;
3761
+ document.body.append(a); a.click(); a.remove();
3762
+ setTimeout(() => URL.revokeObjectURL(a.href), 60_000);
3763
+ });
3764
+ /* THIS SERVER STARTED AGAIN: asked twice (the second says what it does). */
3765
+ $('server-restart').addEventListener('click', () => {
3766
+ const go = $('server-restart');
3767
+ if (go.dataset.sure !== 'yes') { go.dataset.sure = 'yes'; go.textContent = 'Yes: restart this server now'; return; }
3768
+ go.disabled = true;
3769
+ void post(`${API}/server/restart`, {}).then(() => {
3770
+ $('server-restart-said').textContent = 'Restarting: this page comes back by itself.';
3771
+ /* Back once it answers again. */
3772
+ const back = async () => { try { if ((await fetch(`${API}/updates`, { cache: 'no-store' })).ok) { location.reload(); return; } } catch { /* not yet */ } setTimeout(back, 2000); };
3773
+ setTimeout(back, 5000);
3774
+ }).catch((error) => { $('server-restart-said').textContent = error.message; go.disabled = false; delete go.dataset.sure; go.textContent = 'Restart this server...'; });
3775
+ });
3602
3776
  async function paintServer() {
3603
3777
  clearTimeout(serverTimer);
3604
3778
  const r = await fetch(`${API}/server`).then((x) => (x.ok ? x.json() : null)).catch(() => null);
package/web/index.html CHANGED
@@ -24,7 +24,7 @@
24
24
  <input id="create-id" maxlength="32" pattern="[a-z]([a-z0-9\-]{0,30}[a-z0-9])?" title="Lower-case letters, digits and hyphens; starts with a letter, does not end with a hyphen" placeholder="website-redesign" spellcheck="false" autocapitalize="none">
25
25
  <p class="hint">Used for its machine, its folders, its address and what is given to it. Drawn from the name when empty; it cannot be changed later. The name can.</p>
26
26
  </details>
27
- <label for="create-group">Folder <span class="hint">(optional)</span></label>
27
+ <label for="create-group">Group <span class="hint">(optional)</span></label>
28
28
  <input id="create-group" maxlength="40" list="group-names" placeholder="None" spellcheck="false" autocomplete="off">
29
29
  <datalist id="group-names"></datalist>
30
30
  <span class="legend">What runs in it</span>
@@ -35,6 +35,8 @@
35
35
  <div class="row"><button type="submit" class="primary">Create</button><button type="button" id="create-cancel">Cancel</button>
36
36
  <span class="hint">a new machine takes a few minutes</span></div>
37
37
  </form>
38
+ <!-- Needs you and Recent: copies of rows of the list below, by when they were last used (app.js, paint). -->
39
+ <div id="recent"></div>
38
40
  <div id="items"></div>
39
41
  <p id="search-none" class="hint" hidden>Nothing found.</p>
40
42
  <!-- Hidden conversations still run; this shows them, and says when one needs you. -->
@@ -129,10 +131,10 @@
129
131
  <form id="title-form" class="row" autocomplete="off"><label for="title-name">Name</label><input id="title-name" maxlength="60" spellcheck="false"><button type="submit">Save</button></form>
130
132
  </div>
131
133
  <div id="group-box" hidden>
132
- <form id="group-form" class="row" autocomplete="off"><label for="group-name">Folder</label><input id="group-name" maxlength="40" list="group-names" placeholder="None" spellcheck="false"><button type="submit">Save</button></form>
134
+ <form id="group-form" class="row" autocomplete="off"><label for="group-name">Group</label><input id="group-name" maxlength="40" list="group-names" placeholder="None" spellcheck="false"><button type="submit">Save</button></form>
133
135
  <p class="hint">A folder of the list, shared by every device: choose one, type a new one, or empty it for none.</p>
134
- <form id="group-rename-form" class="row" autocomplete="off" hidden><label for="group-rename">Rename its folder</label><input id="group-rename" maxlength="40" spellcheck="false"><button type="submit">Rename for all</button></form>
135
- <div class="row" id="order-row"><span>Its place</span><button type="button" id="move-up">Move up</button><button type="button" id="move-down">Move down</button><button type="button" id="group-up" hidden>Folder up</button><button type="button" id="group-down" hidden>Folder down</button></div>
136
+ <form id="group-rename-form" class="row" autocomplete="off" hidden><label for="group-rename">Rename its group</label><input id="group-rename" maxlength="40" spellcheck="false"><button type="submit">Rename for all</button></form>
137
+ <div class="row" id="order-row"><span>Its place</span><button type="button" id="move-up">Move up</button><button type="button" id="move-down">Move down</button><button type="button" id="group-up" hidden>Group up</button><button type="button" id="group-down" hidden>Group down</button></div>
136
138
  <p class="hint" id="order-hint">The same order on every device. In the list: drag it (on a phone or tablet, hold it, then drag), or Alt and an arrow key.</p>
137
139
  </div>
138
140
  <div id="hide-box" hidden>
@@ -652,7 +654,7 @@
652
654
  <div id="server-disks"></div>
653
655
  <!-- ALL THE MACHINES TO ANOTHER DISK (server/machinesmove.mjs). -->
654
656
  <details id="move-machines-box">
655
- <summary>Move all the machines to another disk...</summary>
657
+ <summary>The disks, and moving all the machines to another one...</summary>
656
658
  <p class="hint">Every machine is stopped, its disk copied to the disk you choose, and started again as its conversation is opened. <b>This server stops meanwhile</b>: this page comes back by itself. It takes from a few minutes to much longer, with the size of the machines. The copy on the disk of now is kept until you remove it.</p>
657
659
  <div id="move-machines-rows"></div>
658
660
  <p class="hint" id="move-machines-said" role="status"></p>
@@ -716,6 +718,38 @@
716
718
  </div>
717
719
  </div>
718
720
  </details>
721
+ <!-- WHAT THE SERVER'S PROGRAMS SAID, to read, copy whole or keep (server/serverlogs.mjs);
722
+ and this server started again. -->
723
+ <details class="chapter" id="settings-logs-top" data-chapter="s-logs">
724
+ <summary><span class="chapter-title">Logs and restart</span><span class="chapter-about">What the server's programs said; start it again.</span></summary>
725
+ <div class="chapter-body">
726
+ <div class="row logs-pick">
727
+ <label>Source <select id="logs-source" class="pill">
728
+ <option value="clavarium">Clavarium</option>
729
+ <option value="machines">The VM manager (machines)</option>
730
+ <option value="system">The system (kernel: memory, disks)</option>
731
+ <option value="updates">Updates and certificate</option>
732
+ <option value="web">Web front and its door</option>
733
+ <option value="signin">Sign-in</option>
734
+ <option value="tunnel">Tunnel</option>
735
+ </select></label>
736
+ <label>Over <select id="logs-span" class="pill">
737
+ <option value="1">the last hour</option>
738
+ <option value="6">the last 6 hours</option>
739
+ <option value="24" selected>the last 24 hours</option>
740
+ <option value="168">the last 7 days</option>
741
+ <option value="boot">since the server started</option>
742
+ </select></label>
743
+ <button type="button" id="logs-show">Show</button>
744
+ </div>
745
+ <p class="hint" id="logs-said" role="status"></p>
746
+ <div class="row" id="logs-acts" hidden><button type="button" id="logs-copy">Copy all</button><button type="button" id="logs-save">Download</button></div>
747
+ <pre id="logs-text" class="logs-text" tabindex="0" hidden></pre>
748
+ <p class="hint">What looks like a password, a token or a key is masked. The newest lines are at the bottom.</p>
749
+ <div class="row"><button type="button" class="danger" id="server-restart">Restart this server...</button><span class="hint" id="server-restart-said" role="status"></span></div>
750
+ <p class="hint">Its machines go on running; the page comes back by itself in a few seconds.</p>
751
+ </div>
752
+ </details>
719
753
  <details class="chapter" id="settings-ch-backup" data-chapter="s-backup">
720
754
  <summary><span class="chapter-title">Storage &amp; backup</span><span class="chapter-about">Disk sizes, and how to back up.</span></summary>
721
755
  <div class="chapter-body">
package/web/style.css CHANGED
@@ -27,7 +27,7 @@ button:focus-visible, input:focus-visible { outline: 2px solid var(--brass); out
27
27
  #app:has(> #list[hidden]) #room { grid-column: 1 / -1; }
28
28
  #list { grid-column: 1; grid-row: 1; min-height: 0; display: flex; flex-direction: column; gap: 8px; padding: 10px; background: var(--panel); border-right: 1px solid var(--line); overflow-y: auto; }
29
29
  #list .top { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
30
- #items { display: flex; flex-direction: column; gap: 6px; }
30
+ #items, #recent { display: flex; flex-direction: column; gap: 6px; }
31
31
  .item { display: block; width: 100%; text-align: left; padding: 9px 10px; background: var(--bar); font-weight: 400; }
32
32
  .item[aria-current="true"] { border-color: var(--brass); box-shadow: 0 0 0 1px var(--brass); }
33
33
  .item b { display: block; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
@@ -970,10 +970,12 @@ button.inline:hover { color: var(--brass); }
970
970
  .server-meter .zone { position: absolute; top: 0; bottom: 0; right: 0; background: repeating-linear-gradient(135deg, transparent 0 3px, color-mix(in srgb, var(--ink2) 45%, transparent) 3px 5px); }
971
971
  .server-meter .mark { position: absolute; top: -1px; bottom: -1px; width: 2px; margin-left: -1px; background: var(--ink); opacity: .7; }
972
972
  .server-note { margin: 0; font-size: .75rem; color: var(--ink2); }
973
- .server-parts { display: grid; grid-template-columns: 1fr auto; gap: 2px 16px; margin: 2px 0 0; font-size: .8125rem; max-width: 30rem; }
973
+ /* The labels never squeezed by a long value: a value in words wraps in a column of its own width. */
974
+ .server-parts { display: grid; grid-template-columns: minmax(9rem, 1fr) minmax(4.5rem, max-content); gap: 2px 16px; margin: 2px 0 0; font-size: .8125rem; max-width: 30rem; }
974
975
  .server-parts dt { margin: 0; font-weight: 600; min-width: 0; overflow-wrap: anywhere; }
975
976
  .server-parts dd { margin: 0; text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
976
977
  .server-parts .sub { font-weight: normal; color: var(--ink2); }
978
+ .server-parts dd.words { white-space: normal; overflow-wrap: anywhere; max-width: 18rem; }
977
979
  .server-parts dt.sub { padding-left: 14px; }
978
980
  .reserve-row { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 14px; }
979
981
  .reserve-what { min-width: 4.5em; font-weight: 600; }
@@ -1273,3 +1275,32 @@ select.pill { appearance: auto; }
1273
1275
 
1274
1276
  /* A secret of several lines (a key): masked as the line is, never shown as it is typed. */
1275
1277
  .secret-lines { width: 100%; min-height: 6rem; margin-top: .5rem; font: .8rem ui-monospace, Menlo, Consolas, monospace; padding: .5rem .6rem; border-radius: 8px; border: 1px solid var(--line); background: var(--bg); color: var(--ink); resize: vertical; -webkit-text-security: disc; }
1278
+
1279
+ /* THE LIST: Needs you, Recent (copies, with what was said last and when), then the groups. */
1280
+ .list-head { margin: 10px 2px 2px; font-size: .78rem; font-weight: 600; letter-spacing: .04em; text-transform: uppercase; color: var(--ink2); }
1281
+ .list-head:first-child { margin-top: 2px; }
1282
+ .item[data-when] { position: relative; }
1283
+ .item[data-when] > b { padding-right: 5.5em; }
1284
+ .item .when { position: absolute; top: 9px; right: 10px; max-width: 5em; overflow: hidden; white-space: nowrap; font-weight: 400; color: var(--ink2); }
1285
+ .item .last { display: block; color: var(--ink); opacity: .85; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1286
+ .more-recent { align-self: flex-start; }
1287
+ .list-tip { margin: 8px 2px; }
1288
+ /* Needs you and Recent above the groups, in the list's own scroll: never a box scrolled inside it
1289
+ (a row cut in half at its bottom). A few rows, then "Show all". */
1290
+ #list #recent { flex: 0 0 auto; }
1291
+ #list #recent:empty { display: none; }
1292
+
1293
+ /* Settings, Logs: the lines as they were written, wide ones scrolled sideways, never wrapped into a column. */
1294
+ .logs-pick { flex-wrap: wrap; gap: 8px 12px; align-items: center; }
1295
+ .logs-text { max-height: 60vh; overflow: auto; margin: 8px 0; padding: 8px 10px; background: var(--bg); border: 1px solid var(--line); border-radius: 8px; font: .75rem/1.4 ui-monospace, Menlo, Consolas, monospace; white-space: pre; color: var(--ink); }
1296
+
1297
+ /* Settings, Move all the machines: a card per disk, what is on it, what can be done. */
1298
+ .disk-card { border: 1px solid var(--line); border-radius: 8px; padding: 8px 10px; margin: 8px 0; display: flex; flex-direction: column; gap: 4px; }
1299
+ .disk-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 10px; }
1300
+ .disk-head b { min-width: 0; overflow-wrap: anywhere; }
1301
+ .disk-size { font-variant-numeric: tabular-nums; }
1302
+ .disk-name { color: var(--ink2); }
1303
+ .disk-part { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 10px; margin: 0; font-size: .875rem; }
1304
+ .disk-part > span { min-width: 0; overflow-wrap: anywhere; }
1305
+ .disk-prepare .row { flex-wrap: wrap; gap: 6px 8px; align-items: center; }
1306
+ .disk-prepare input { width: 9rem; }