clavarium 0.2.214-beta.1 → 0.2.215-beta.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.
@@ -85,6 +85,10 @@ const WATCH_EVERY_MS = 3600_000;
85
85
  const WATCH_RECENT_MS = 24 * 3600_000;
86
86
  const HISTORY_MAX = 30;
87
87
  const ASK_EVERY_MS = 6 * 3600_000;
88
+ /* A VERSION THAT COULD NOT EVEN BE FETCHED (16-11: npm asked one minute after it came out, before every mirror
89
+ had it): nothing of it ran here, so it is tried again by itself, this long after, this many times at most. */
90
+ export const FETCH_AGAIN_MS = 30 * 60_000;
91
+ export const FETCH_TRIES = 3;
88
92
  /* Between "Switching" said in state.json and the server stopped: the pages ask the server every
89
93
  10 seconds at most (app.js), and the server says it in each answer (updates.mjs, notice): each
90
94
  gives way to the maintenance page before the server goes. */
@@ -602,7 +606,7 @@ export class Updater {
602
606
  const unlock = this.#lock();
603
607
  try {
604
608
  let release;
605
- try { release = await this.prepare({ version }); } catch (error) { this.#history({ action: 'update', from: from?.version ?? null, to: version, result: 'failed', why: error.message }); throw error; }
609
+ try { release = await this.prepare({ version }); } catch (error) { this.#history({ action: 'update', from: from?.version ?? null, to: version, result: 'failed', why: error.message, ...(/^npm could not install /.test(error.message) ? { fetch: true } : {}) }); throw error; }
606
610
  const before = this.#dataFormat();
607
611
  let archive;
608
612
  try {
@@ -714,8 +718,13 @@ export class Updater {
714
718
  const available = await this.check();
715
719
  if (!available) return 'up to date';
716
720
  if (conf.MODE === 'ask') return `${available} is out: waiting for the owner`;
717
- /* A version that failed here is not tried again by itself: the owner can, from Settings. */
718
- if ((state.history ?? []).some((h) => h.to === available && h.action === 'update' && h.result !== 'done')) return `${available} failed here before: not tried again by itself`;
721
+ /* A version that failed here is not tried again by itself: the owner can, from Settings. One that only
722
+ could not be fetched (nothing of it ran) is, later, a few times. */
723
+ const failed = (state.history ?? []).filter((h) => h.to === available && h.action === 'update' && h.result !== 'done');
724
+ if (failed.some((h) => h.fetch !== true)) return `${available} failed here before: not tried again by itself`;
725
+ if (failed.length >= FETCH_TRIES) return `${available} could not be fetched ${failed.length} times: not tried again by itself`;
726
+ const lastAt = Math.max(...failed.map((h) => new Date(h.at ?? 0).getTime()), -Infinity);
727
+ if (failed.length && now - lastAt < FETCH_AGAIN_MS) return `${available} could not be fetched: tried again later`;
719
728
  const why = await this.busy(); if (why) return why;
720
729
  await this.apply(available);
721
730
  /* What the history says, not what was hoped: a version that did not start was undone. */
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.214-beta.1",
3
+ "version": "0.2.215-beta.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.214-beta.1",
9
+ "version": "0.2.215-beta.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.214-beta.1",
3
+ "version": "0.2.215-beta.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/bridge.mjs CHANGED
@@ -31,6 +31,9 @@ export const CLOSE_ENDED = 1000;
31
31
  export const CLOSE_TAKEN = 4001;
32
32
  /* A device whose right on this terminal was taken back (or its session ended): put out at once. */
33
33
  export const CLOSE_REVOKED = 4003;
34
+ /* A page that came back by itself (a dropped connection, this server restarted) to a machine put to sleep or
35
+ stopped: not woken -- only a person opening it wakes it (16-11: a tab left open woke a sleeper at each update). */
36
+ export const CLOSE_ASLEEP = 4004;
34
37
  /* A channel that dropped is reopened after a moment, a few times a minute at most. */
35
38
  export const REOPEN_AFTER_MS = 1000;
36
39
  export const REDRAW_AFTER_MS = 250;
@@ -87,7 +90,7 @@ export const sameOrigin = makeOriginCheck();
87
90
  const BY_ITSELF = /\x1b\[[IO]|\x1b\[\??[>=]?[\d;]*c|\x1b\[\d+;\d+R|\x1b\][\d;]*(?:rgb:[0-9a-fA-F/]+)?(?:\x07|\x1b\\)|\x1bP[^\x1b]*\x1b\\/g;
88
91
  export const byHand = (typed) => String(typed ?? '').replace(BY_ITSELF, '').length > 0;
89
92
 
90
- export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () => {}, originOk = sameOrigin, gate = () => 'local', deviceName = () => undefined, onRejoin = () => {}, onTyped = () => {} }) {
93
+ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () => {}, originOk = sameOrigin, gate = () => 'local', deviceName = () => undefined, onRejoin = () => {}, onTyped = () => {}, asleep = () => false }) {
91
94
  const sockets = new WebSocketServer({ noServer: true });
92
95
  const seats = new Seats();
93
96
  /* THE DEVICES AT A TERMINAL, each with what lets it stay: asked again when the owner changes
@@ -123,9 +126,11 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
123
126
  } else return;
124
127
  const cols = Number(url.searchParams.get('cols'));
125
128
  const rows = Number(url.searchParams.get('rows'));
129
+ /* `resume=1`: the page comes back by itself, nobody asked to open it. */
130
+ const resume = url.searchParams.get('resume') === '1';
126
131
  sockets.handleUpgrade(request, socket, head, (viewer) => {
127
132
  if (still) { deviceSeats.set(viewer, still); viewer.on('close', () => deviceSeats.delete(viewer)); }
128
- seat(viewer, name, within(cols, COLS) ? cols : 80, within(rows, ROWS) ? rows : 24);
133
+ seat(viewer, name, within(cols, COLS) ? cols : 80, within(rows, ROWS) ? rows : 24, resume);
129
134
  });
130
135
  });
131
136
 
@@ -180,7 +185,9 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
180
185
  return run;
181
186
  }
182
187
  async function openNow(name, cols, rows, sink, say) {
183
- const terminal = await spawn(name, cols, rows, say);
188
+ /* Who opens it, for What happened when it wakes a sleeper: a screen, or this server (warm). */
189
+ const who = sink ? (deviceSeats.has(sink) ? 'a paired device' : 'a page') : undefined;
190
+ const terminal = await spawn(name, cols, rows, say, who);
184
191
  /* While it was being opened another one may have been: the newest wins. */
185
192
  if (live.has(name)) close(name);
186
193
  const kept = { terminal, sink, cols, rows, openedAt: Date.now(), outputAt: Date.now() };
@@ -211,7 +218,7 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
211
218
  return kept;
212
219
  }
213
220
 
214
- async function seat(viewer, name, cols, rows) {
221
+ async function seat(viewer, name, cols, rows, resume = false) {
215
222
  const previous = seats.take(name, viewer);
216
223
  if (previous) {
217
224
  previous.send(JSON.stringify({ type: 'taken' }));
@@ -249,6 +256,8 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
249
256
  resize(taken, cols, Math.max(2, rows - 1));
250
257
  setTimeout(() => { if (live.get(name) === taken && taken.sink === viewer) resize(taken, taken.cols, taken.rows); }, REDRAW_AFTER_MS);
251
258
  } else {
259
+ /* Asleep or stopped, and nobody asked: left so; the page offers to wake it. */
260
+ if (resume && (() => { try { return asleep(name) === true; } catch { return false; } })()) { viewer.close(CLOSE_ASLEEP, 'asleep'); return; }
252
261
  try { kept = await open(name, cols, rows, viewer, say); }
253
262
  catch (error) {
254
263
  /* Only a message written for the person is passed on. */
@@ -163,6 +163,9 @@ export class Conversations {
163
163
  /* Set by the server: its wake-ups, for a whole export; and on its import, when asked, its reminders (from the
164
164
  export's work folder) and those wake-ups given again (15-11, as a copy does). */
165
165
  wakeupsOf = () => undefined;
166
+ /* Set by the server: a machine put to sleep or stopped, woken by an opening -- `by` who (16-11: a sleeper found
167
+ awake in the morning, and nothing said who woke it). Said in What happened. */
168
+ woken = () => {};
166
169
  importReminders = async () => {};
167
170
 
168
171
  /* `uid`/`gid`: the account this server runs as; files the tool writes in
@@ -560,7 +563,7 @@ export class Conversations {
560
563
  }
561
564
 
562
565
  /* What a terminal must run to reach this conversation. Wakes the VM first. */
563
- async open(name, say = () => {}) {
566
+ async open(name, say = () => {}, by = 'the server') {
564
567
  const c = this.#store.get(name);
565
568
  if (!c) throw new Refusal(404, 'No such conversation.');
566
569
  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.');
@@ -571,6 +574,7 @@ export class Conversations {
571
574
  /* Opening is the explicit gesture that ends a sleep, or a stop its owner asked for. */
572
575
  if (c.asleep) this.#store.patch(name, { asleep: false });
573
576
  if (c.stopped) this.#store.patch(name, { stopped: undefined });
577
+ if (c.asleep || c.stopped) { try { this.woken(name, by, c.asleep ? 'asleep' : 'stopped'); } catch { /* said, nothing more */ } }
574
578
  this.#watching.set(name, (this.#watching.get(name) ?? 0) + 1);
575
579
  /* Another screen is applying the size kept for its wake: this one opens once it is over. */
576
580
  await this.#resizing.get(name)?.catch(() => {});
package/server/guide.mjs CHANGED
@@ -129,7 +129,7 @@ export function ownText({ name, tool, shared, workKept, resources = [], chat, on
129
129
  /* The thread is kept whole: after a restart, its end is read, and further back on demand. */
130
130
  if (chat && reread) out.push(`- After a restart: ${plain(reread, 60)}, the end of the chat; it says how to read further back.`);
131
131
  /* 02-11: the one command a tool may ask of the server. */
132
- if (chat) out.push('- To be restarted (new tools to take up, or anything stuck): finish what runs, then `touch /work/.parley/restart-asked`; the server restarts you once your turn ends, and your work picks up where it was.');
132
+ if (chat) out.push('- To be restarted (new tools to take up, or anything stuck): finish what runs, then `touch /work/.parley/restart-asked`; the server restarts you once your turn ends, and your work picks up where it was. /work itself fails ("not connected"): `cd / && touch /var/tmp/clavarium-restart-asked` instead.');
133
133
  /* Its docket (dockets.mjs): what wakes it waits there until it says done or failed. */
134
134
  if (chat) out.push('- What wakes you (a file arrived, the clock, a call) waits in your docket: when told "run docket", run it, do each, then docket done ID or docket failed ID "why". To be reminded later: docket remind --at "2026-10-23 09:00" (or --in 2h, --cron "0 9 * * 1") "what for". docket --help says all.');
135
135
  /* Its lists (binders.mjs): kept on the server, asked for through .binder; a person approves. */
package/server/health.mjs CHANGED
@@ -25,6 +25,20 @@
25
25
  shell. It prints one fact per line; the server reads only these lines. */
26
26
  import { SHARING_STEP } from './vm.mjs';
27
27
  import { WHY } from './linkguard.mjs';
28
+ import { SOCKET } from './tmux.mjs';
29
+ import { SESSION } from './conversations.mjs';
30
+
31
+ /* A FILE OUTSIDE /work where its tool may ask to be restarted when /work itself is dead (16-11): the
32
+ one in its chat's folder (talk.mjs, RESTART_ASKED) cannot be written then. Read by the probe. */
33
+ export const RESTART_OUTSIDE = '/var/tmp/clavarium-restart-asked';
34
+ /* The host of its tools, as pgrep -f reads it (the bracket: never the shell that asks). */
35
+ export const TOOLS_HOST_PATTERN = '/tools/launch/[t]ools-host.mjs';
36
+ /* What a folder that came loose looks like on a terminal (the kernel's words for ENOTCONN). */
37
+ const LOOSE_WORDS = 'transport endpoint is not connected|socket is not connected|ENOTCONN';
38
+ /* A WORK FOLDER THE VM MANAGER CANNOT TAKE BACK (16-11, tried on a test server): its mount program died, multipass
39
+ cannot unmount it ("Failed to terminate SSHFS mount process") and then refuses to mount it again ("already
40
+ mounted"). Only a restart of its machine mounts it again. */
41
+ export const STUCK_MOUNT = /already mounted|terminate SSHFS mount process/i;
28
42
 
29
43
  /* How long installing the shared-folder helper in a machine may take (it comes from the snap store). */
30
44
  export const SHARING_MS = 180_000;
@@ -41,6 +55,18 @@ export const PROBE = [
41
55
  ' else echo "mount missing $p"; fi',
42
56
  'done',
43
57
  'if [ -d /work ] && awk \'$2=="/work"{f=1} END{exit !f}\' /proc/mounts; then timeout 5 df -Pm /work 2>/dev/null | awk \'NR==2{print "disk /work", $4, $2}\'; fi',
58
+ /* ITS TOOL STILL IN A FOLDER THAT WENT (16-11). A folder put back is a NEW mount: a program that was
59
+ in the old one stays in it, dead ("Transport endpoint is not connected"), until it is started
60
+ again -- the folder looks well, its tool does not. So each program of its tool's session whose
61
+ folder is ours to read (readlink) and cannot be entered is said; the first one is enough. */
62
+ `t=$(tmux -L ${SOCKET} list-panes -t '=${SESSION}:' -F '#{pane_pid}' 2>/dev/null | head -n 1)`,
63
+ 'case "$t" in ""|*[!0-9]*) ;; *) timeout 5 sh -c \'for p in $(ps -o pid= -s "$1" 2>/dev/null); do l=$(readlink "/proc/$p/cwd" 2>/dev/null) || continue; [ -n "$l" ] || continue; [ -d "/proc/$p/cwd/." ] || { echo "stale $p"; exit 0; }; done\' stale "$t";; esac',
64
+ /* What its terminal shows now: a folder that is not connected, said by its tool (a symptom, not a proof). */
65
+ /* And the host of its tools (config/launch/tools-host.mjs: Parley, Docket... for its agent), started in its own
66
+ session from the tool's folder: left in a dead one, every tool it serves fails, the tool restarted or not. */
67
+ `for p in $(pgrep -f '${TOOLS_HOST_PATTERN}' 2>/dev/null); do [ -d "/proc/$p/cwd/." ] || { echo "stale $p"; break; }; done`,
68
+ `tmux -L ${SOCKET} capture-pane -p -t '=${SESSION}:' 2>/dev/null | grep -c -i -E '${LOOSE_WORDS}' | awk '{print "screen", $1+0}'`,
69
+ `if [ -f ${RESTART_OUTSIDE} ]; then echo "restart asked"; fi`,
44
70
  ].join('\n');
45
71
  export const PROBE_NAME = 'clavarium-health';
46
72
 
@@ -76,6 +102,9 @@ export function readProbe(text, paths = []) {
76
102
  if (parts[0] === 'oomkinds' && parts.length === 3 && a !== undefined && b !== undefined) facts.oomKinds = { machine: a, limit: b };
77
103
  if (parts[0] === 'disk' && parts.length === 4 && disks.has(parts[1]) && b !== undefined && c !== undefined) facts.disks[parts[1]] = { availableMb: b, sizeMb: c };
78
104
  if (parts[0] === 'mount' && parts.length === 3 && expected.has(parts[2]) && MOUNT_STATES.has(parts[1])) facts.mounts[parts[2]] = parts[1];
105
+ if (parts[0] === 'stale' && parts.length === 2 && a !== undefined) facts.stale = true;
106
+ if (parts[0] === 'screen' && parts.length === 2 && a !== undefined) facts.screenLoose = a;
107
+ if (line.trim() === 'restart asked') facts.restartAsked = true;
79
108
  }
80
109
  return facts;
81
110
  }
@@ -123,6 +152,10 @@ export function judge(record) {
123
152
  for (const path of record.remounted ?? []) add('info', 'mount', `remounted:${path}`, `${path} had come loose in the machine: it was mounted again.`);
124
153
  for (const { path, why } of record.failed ?? []) add('bad', 'mount', `failed:${path}`, `${path} is not reachable in the machine and could not be mounted again${why ? `: ${why}` : ''}.`);
125
154
  for (const path of record.missing ?? []) if (!(record.failed ?? []).some((f) => f.path === path)) add('warn', 'mount', `missing:${path}`, `${path} is not reachable in the machine.`);
155
+ if (record.stuckWork) add('bad', 'mount', 'stuck-work', 'Its work folder cannot be mounted again in its machine: its machine is restarted, its work picks up where it was.');
156
+ if (record.stale) add('bad', 'mount', 'stale-tool', 'Its tool is still in a folder that came loose: it is restarted, its work picks up where it was.');
157
+ /* Its terminal says so while its folders look well: said, nothing done (its tool may only be quoting it). */
158
+ else if (record.screenLoose > 0 && !(record.missing ?? []).length) add('warn', 'mount', 'screen-loose', 'Its terminal says a folder is not connected, though its folders look well.');
126
159
  }
127
160
  /* Links its folders hold that the share cannot serve (linkguard.mjs): looked at on this server, whatever its machine does. */
128
161
  for (const l of record.links?.removed ?? []) add('info', 'link', `link-removed:${l.folder}/${l.path}`, `/resources/${l.folder}/${l.path} was a broken link (${WHY[l.kind] ?? l.kind}): it was removed on the server, what it pointed to left as it was.`);
@@ -226,6 +259,8 @@ export class Health {
226
259
  return this.#keep(name, {
227
260
  at, state, answering: true, memory: facts.memory, oomKills: facts.oomKills ?? 0, ...(facts.oomKinds ? { oomKinds: facts.oomKinds } : {}), disks: facts.disks,
228
261
  paths, missing: loose(), ...(remounted.length ? { remounted } : {}), ...(failed.length ? { failed } : {}), ...(links ? { links } : {}),
262
+ ...(failed.some((f) => f.path === '/work' && STUCK_MOUNT.test(f.why ?? '')) ? { stuckWork: true } : {}),
263
+ ...(facts.stale ? { stale: true } : {}), ...(facts.screenLoose ? { screenLoose: facts.screenLoose } : {}), ...(facts.restartAsked ? { restartAsked: true } : {}),
229
264
  /* What was put back stays said until a later look finds nothing to put back. */
230
265
  });
231
266
  }
package/server/main.mjs CHANGED
@@ -59,7 +59,8 @@ import { GitChecks } from './gitchecks.mjs';
59
59
  import { GitKeeper } from './gitkeeper.mjs';
60
60
  import { GitRunner } from './gitrunner.mjs';
61
61
  import { Shelf } from './shelf.mjs';
62
- import { Health } from './health.mjs';
62
+ import { Health, RESTART_OUTSIDE, TOOLS_HOST_PATTERN } from './health.mjs';
63
+ import { Revive } from './revive.mjs';
63
64
  import { LinkGuard, removedLine, toolLine } from './linkguard.mjs';
64
65
  import { Setup } from './setup.mjs';
65
66
  import { Capacity } from './capacity.mjs';
@@ -482,7 +483,10 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
482
483
  /* A sign-in a companion did for another conversation (signinhelp.mjs, made below): its answer typed there. */
483
484
  acked: (name, e) => signinHelp?.acked(name, e) });
484
485
  const typingWatch = new TypingWatch();
485
- const wakeups = new Wakeups({ store: new Store(`${dataDir}/wakeups.json`), vms, conversations: all, resources: folders, warm: (name) => bridge?.warm(name), docket: dockets, typing: (name) => typingWatch.busy(name),
486
+ /* WHO WOKE IT (16-11): this server opens a terminal for others (a wake-up, a key); said once it wakes one. */
487
+ const wakeWhy = { why: new Map(), set(name, by) { this.why.set(name, by); }, take(name) { const by = this.why.get(name); this.why.delete(name); return by ?? 'the server'; } };
488
+ all.woken = (name, by, was) => events.add({ kind: 'machine', text: `Machine of ${name}: woken by ${by} (it was ${was})`, conversation: name });
489
+ const wakeups = new Wakeups({ store: new Store(`${dataDir}/wakeups.json`), vms, conversations: all, resources: folders, warm: (name) => { if (!all.awake().includes(name)) wakeWhy.set(name, 'its wake-up'); return bridge?.warm(name); }, docket: dockets, typing: (name) => typingWatch.busy(name),
486
490
  fired: (name, { text }) => talk.event(name, { kind: 'wakeup', text, topic: 'Wake-up' }) });
487
491
  const wakeTimer = wakeups.start(wakeEveryMs);
488
492
  const docketTimer = dockets.start(wakeEveryMs);
@@ -613,7 +617,29 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
613
617
  /* A TOOL THAT ASKS TO BE RESTARTED (02-11: to take up its tools, after an update): its tool restarted by this server
614
618
  once its turn has ended (its pulse no longer busy), said in its chat; once per ten minutes at most. */
615
619
  const restartedAt = new Map();
620
+ /* ITS TOOL STILL IN A FOLDER THAT CAME LOOSE, or asking from outside /work (16-11, revive.mjs): restarted
621
+ by the server, its tool only; told through its docket first (read as it starts), its chat after. */
622
+ const revive = new Revive({
623
+ /* Its tools' host stopped first (it starts again at the tool's first tool, from the folder put back). */
624
+ restart: async (name) => { await vms.exec(name, ['sh', '-c', `for p in $(pgrep -f '${TOOLS_HOST_PATTERN}'); do kill "$p"; done; true`], { timeoutMs: 10_000 }).catch(() => {}); return all.restartTool(name); },
625
+ restartMachine: async (name) => { const r = await all.machineAction(name, 'restart', { wait: true }); return r?.ok !== false; },
626
+ busy: (name) => talk.pulse(name)?.busy === true,
627
+ taken: (name) => vms.exec(name, ['rm', '-f', RESTART_OUTSIDE], { timeoutMs: 10_000 }),
628
+ tell: (name, why, step) => {
629
+ const loose = why === 'stale' || why === 'stuck';
630
+ if (step === 'before') {
631
+ if (loose) try { if (dockets.on(name)) dockets.post(name, { kind: 'restarted', text: 'Your work folder came loose in your machine and was put back: your tool was restarted to see it again (what was in the old one could not be reached). Your work picks up where it was; what ran in the background stopped.' }); } catch { /* its docket may be off */ }
632
+ return;
633
+ }
634
+ const text = step === 'done'
635
+ ? (why === 'stuck' ? 'Its work folder could not be mounted again: its machine was restarted, the folder is back. Its work picks up where it was.' : loose ? 'Its work folder had come loose: its tool was restarted to see it again. Its work picks up where it was.' : 'Its tool was restarted as it asked: its work picks up where it was.')
636
+ : 'Its tool could not be restarted: open its terminal and type exit, it starts again.';
637
+ try { talk.event(name, { kind: step === 'done' ? 'restarted' : 'machine-problem', text, topic: step === 'done' ? 'Restarted' : 'Machine', ...(step === 'done' ? {} : { tone: 'warn' }) }); } catch { /* its chat is off */ }
638
+ if (step === 'failed') events.add({ kind: 'machine', text: `${name}: ${text}`, conversation: name });
639
+ },
640
+ });
616
641
  const restartTimer = setInterval(() => {
642
+ void revive.tick().catch(() => {});
617
643
  for (const name of all.awake()) {
618
644
  if (!talk.restartAsked(name)) continue;
619
645
  if (talk.pulse(name)?.busy) continue;
@@ -646,7 +672,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
646
672
  /* Where its chat is on, its agent is given an event when its disk or memory crosses a level (healthdocket.mjs);
647
673
  not where its owner turned on its own reaction (above): one way of telling it, not two. */
648
674
  const healthDocket = new HealthDocket({ store: new Store(`${dataDir}/health-docket.json`), dockets, reacting: (name) => reacting.settings(name).on });
649
- health.forgotten = (name) => { healthDocket.forget(name); watchdog.forget(name); };
675
+ health.forgotten = (name) => { healthDocket.forget(name); watchdog.forget(name); revive.forget(name); };
650
676
  /* A machine's problems worth keeping in What happened: said once, until they went away. */
651
677
  const problemsSaid = new Map();
652
678
  /* ITS WATCHDOG (watchdog.mjs): mute or full for as long as its owner set, forced off then started, once;
@@ -662,6 +688,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
662
688
  alert: (payload) => { events.add({ kind: 'machine', text: `${payload.title}: ${payload.body ?? ''}`.trim() }); void alerts.tell(payload)?.catch?.(() => {}); } });
663
689
  health.judged = (name, record) => {
664
690
  void watchdog.judged(name, record).catch(() => {});
691
+ try { revive.judged(name, record); } catch { /* its tool: nothing more */ }
665
692
  talk.machine(name, record); void reacting.judged(name, record).catch(() => {});
666
693
  /* A folder that came loose and was put back: said once, in its chat (the look that put it back). */
667
694
  for (const path of record?.remounted ?? []) { try { talk.event(name, { kind: 'machine-ok', text: `Le dossier ${path} s'était détaché de la machine : il a été remonté.`, topic: 'Machine', brief: 'Shared folder' }); } catch { /* its chat is off */ } }
@@ -843,6 +870,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
843
870
  wake: (name) => {
844
871
  const c = all.get(name);
845
872
  if (c?.phase !== 'ready') throw new Refusal(409, 'This conversation is not ready.');
873
+ if (c.asleep === true || c.stopped === true) wakeWhy.set(name, 'a key (API)');
846
874
  void bridge?.warm(name);
847
875
  return { state: c.asleep === true ? 'waking' : 'awake' };
848
876
  },
@@ -895,9 +923,11 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
895
923
  try { syncTargets(tethers.store(), boxes.all()); } catch (error) { console.error(`voice boxes in Tether: ${error.message}`); }
896
924
  bridge = attachBridge(server, {
897
925
  onRejoin: (name) => all.rejoin(name),
926
+ /* Put to sleep or stopped: a page that comes back by itself does not wake it (bridge.mjs, CLOSE_ASLEEP). */
927
+ asleep: (name) => { const c = all.get(name); return c?.asleep === true || c?.stopped === true; },
898
928
  onTyped: (name, data) => { answerer.typed(name, data); talk.typed(name); all.touch(name); typingWatch.typed(name, data); },
899
- spawn: async (name, cols, rows, say) => {
900
- const [program, ...argv] = await all.open(name, say);
929
+ spawn: async (name, cols, rows, say, who) => {
930
+ const [program, ...argv] = await all.open(name, say, who ?? wakeWhy.take(name));
901
931
  const started = pty.spawn(program, argv, { name: 'xterm-256color', env: withoutTmux(env), cols, rows });
902
932
  /* Its start is over once something is drawn (nothing of it is
903
933
  read), once it ends, or after a while whatever happens. Not
@@ -0,0 +1,70 @@
1
+ /* ITS TOOL STARTED AGAIN WHEN A FOLDER IT WAS IN CAME LOOSE (16-11).
2
+ *
3
+ * Seen in production: /work of a conversation came loose ("socket is not connected"). Putting the
4
+ * folder back (health.mjs, resources.mjs repair) makes a NEW mount; its tool, and every program it
5
+ * started (its shell, Parley, Docket), stays in the old one, dead, until it is started again. It cannot
6
+ * even ask to be restarted: that request is a file in /work. Its owner typed exit by hand; this does it.
7
+ *
8
+ * Told by health.mjs, each look (`judged`):
9
+ * - `stale`: a program of its tool's session is in a folder that cannot be entered;
10
+ * - `restartAsked`: its tool asked from outside /work (health.mjs, RESTART_OUTSIDE);
11
+ * - `stuckWork`: its work folder cannot be mounted again (health.mjs, STUCK_MOUNT): its MACHINE is restarted
12
+ * (`restartMachine`), the one thing that mounts it again; it outranks the others.
13
+ * Then, at the next tick: its tool only is restarted (conversations.mjs restartTool, never its
14
+ * machine), once its turn has ended -- or after WAIT_MS anyway when stale: a tool stuck in a dead
15
+ * folder cannot say its turn ended (its pulse is in /work). Never a loop: not again within AGAIN_MS.
16
+ * Its tool told through its docket before it starts again, its owner through What happened.
17
+ */
18
+ export const WAIT_MS = 5 * 60_000;
19
+ export const AGAIN_MS = 30 * 60_000;
20
+
21
+ export class Revive {
22
+ #restart; #restartMachine; #busy; #tell; #taken; #now; #wanted = new Map(); #lastAt = new Map(); #going = new Set();
23
+
24
+ /* `restart(name)`: its tool restarted, resolves with whether it was. `busy(name)`: its turn goes on.
25
+ `tell(name, why, step)`: said where it should be, step 'before' (its docket), then 'done' or 'failed' (main.mjs).
26
+ `taken(name)`: the request outside /work removed (in its machine). */
27
+ constructor({ restart, restartMachine = async () => false, busy = () => false, tell = () => {}, taken = async () => {}, now = Date.now }) {
28
+ this.#restart = restart; this.#restartMachine = restartMachine; this.#busy = busy; this.#tell = tell; this.#taken = taken; this.#now = now;
29
+ }
30
+
31
+ /* What one look found. A look that finds it well forgets a stale one not yet acted on. */
32
+ judged(name, record) {
33
+ if (!record || record.state !== 'Running' || record.answering !== true) return;
34
+ if (record.restartAsked) { void Promise.resolve().then(() => this.#taken(name)).catch(() => {}); this.#want(name, 'asked'); }
35
+ if (record.stuckWork) this.#want(name, 'stuck');
36
+ else if (record.stale) this.#want(name, 'stale');
37
+ else if (['stale', 'stuck'].includes(this.#wanted.get(name)?.why)) this.#wanted.delete(name);
38
+ }
39
+
40
+ #want(name, why) {
41
+ const had = this.#wanted.get(name);
42
+ /* stuck over stale over a plain request: the stronger is acted on, even while it looks busy. */
43
+ const rank = { asked: 0, stale: 1, stuck: 2 };
44
+ if (!had || rank[why] > rank[had.why]) this.#wanted.set(name, { why, since: had?.since ?? this.#now() });
45
+ }
46
+
47
+ wanted(name) { return this.#wanted.get(name)?.why ?? null; }
48
+ forget(name) { this.#wanted.delete(name); this.#lastAt.delete(name); }
49
+
50
+ /* One pass: each one wanted, restarted when it may be. Resolves with the names restarted. */
51
+ async tick() {
52
+ const done = [];
53
+ for (const [name, { why, since }] of [...this.#wanted]) {
54
+ if (this.#going.has(name)) continue;
55
+ const busy = (() => { try { return this.#busy(name); } catch { return false; } })();
56
+ if (busy && !(why !== 'asked' && this.#now() - since >= WAIT_MS)) continue;
57
+ this.#wanted.delete(name);
58
+ if (this.#now() - (this.#lastAt.get(name) ?? -Infinity) < AGAIN_MS) continue;
59
+ this.#lastAt.set(name, this.#now());
60
+ this.#going.add(name);
61
+ try {
62
+ try { this.#tell(name, why, 'before'); } catch { /* told, nothing more */ }
63
+ const ok = await (why === 'stuck' ? this.#restartMachine(name) : this.#restart(name)).catch(() => false);
64
+ if (ok) done.push(name);
65
+ try { this.#tell(name, why, ok ? 'done' : 'failed'); } catch { /* told, nothing more */ }
66
+ } finally { this.#going.delete(name); }
67
+ }
68
+ return done;
69
+ }
70
+ }
package/web/app.js CHANGED
@@ -4,6 +4,7 @@
4
4
  (() => {
5
5
  const CLOSE_ENDED = 1000;
6
6
  const CLOSE_TAKEN = 4001;
7
+ const CLOSE_ASLEEP = 4004;
7
8
  const CLOSE_FAILED = 1011;
8
9
  const RETRY_MS = 1500;
9
10
  const NAME = /^[a-z](?:[a-z0-9-]{0,30}[a-z0-9])?$/;
@@ -821,11 +822,16 @@
821
822
  /* When this wait began (kept across the tries made by the page itself), and whether the server repaired it meanwhile. */
822
823
  let waitingSince = 0;
823
824
  let repairedFor = '';
825
+ let resumeWait = false;
824
826
  const disconnect = () => { wanted = false; clearSlow(); socket?.close(); socket = undefined; stopVoice?.(); };
825
827
 
826
828
  /* `again`: a try made by the page itself, within the same wait. */
829
+ /* `resume`: the page comes back by itself (a dropped connection, the server restarted): a machine asleep stays so. */
827
830
  function connect(options) {
828
831
  const again = options?.again === true;
832
+ /* Tries the page makes by itself within that wait keep it: a server still restarting refuses a few first. */
833
+ const resume = options?.resume === true || (again && resumeWait);
834
+ resumeWait = resume;
829
835
  disconnect();
830
836
  if (!NAME.test(current)) return;
831
837
  const name = current;
@@ -835,7 +841,7 @@
835
841
  say('connecting', 'connecting');
836
842
  fit.fit();
837
843
  const scheme = location.protocol === 'https:' ? 'wss' : 'ws';
838
- const where = DEVICE ? `/c/terminal?d=${pairing}&c=${encodeURIComponent(name)}&cols=${terminal.cols}&rows=${terminal.rows}` : `/terminal?c=${encodeURIComponent(name)}&cols=${terminal.cols}&rows=${terminal.rows}`;
844
+ const where = DEVICE ? `/c/terminal?d=${pairing}&c=${encodeURIComponent(name)}&cols=${terminal.cols}&rows=${terminal.rows}${resume ? '&resume=1' : ''}` : `/terminal?c=${encodeURIComponent(name)}&cols=${terminal.cols}&rows=${terminal.rows}${resume ? '&resume=1' : ''}`;
839
845
  const mine = new WebSocket(`${scheme}://${location.host}${where}`);
840
846
  socket = mine;
841
847
  mine.binaryType = 'arraybuffer';
@@ -904,7 +910,11 @@
904
910
  };
905
911
  mine.onclose = (event) => {
906
912
  if (socket !== mine || !wanted) return; /* we moved on, or closed it ourselves */
907
- if (event.code === CLOSE_TAKEN) {
913
+ if (event.code === CLOSE_ASLEEP) {
914
+ say('asleep', 'waiting');
915
+ show(uiSaid('set-asleep-page', 'Asleep. It wakes only when you wake it.'), uiSaid('set-wake-it', 'Wake it'), connect); mascot('asleep');
916
+ if (DEVICE) void refresh();
917
+ } else if (event.code === CLOSE_TAKEN) {
908
918
  say('open elsewhere', 'waiting');
909
919
  show('This conversation is now open on another screen.', 'Use it here', connect);
910
920
  } else if (event.code === CLOSE_ENDED) {
@@ -939,7 +949,7 @@
939
949
  } else {
940
950
  say('reconnecting', 'connecting');
941
951
  if (DEVICE) void refresh(); /* removed meanwhile? then say it, do not retry for ever */
942
- setTimeout(() => { if (socket === mine && wanted) connect(); }, RETRY_MS);
952
+ setTimeout(() => { if (socket === mine && wanted) connect({ resume: true }); }, RETRY_MS);
943
953
  }
944
954
  };
945
955
  }
@@ -951,7 +961,7 @@
951
961
  if (!current || !socket || !wanted) return;
952
962
  const dead = socket; socket = undefined;
953
963
  try { dead.close(); } catch { /* gone */ }
954
- connect();
964
+ connect({ resume: true });
955
965
  });
956
966
 
957
967
  terminal.onData(send);
@@ -8177,7 +8187,8 @@
8177
8187
  apply.dataset.retry = String(failedHere);
8178
8188
  apply.className = failedHere ? '' : 'primary';
8179
8189
  apply.textContent = failedHere ? `Try ${u.available} again\u2026` : `Update to ${u.available ?? ''}`;
8180
- $('updates-retry-note').textContent = failedHere ? `It did not start here before. If it fails again, ${u.version} is put back.` : '';
8190
+ const onlyFetch = failedHere && u.history.filter((h) => h.action === 'update' && h.to === u.available && h.result !== 'done').every((h) => h.fetch === true);
8191
+ $('updates-retry-note').textContent = !failedHere ? '' : onlyFetch ? 'It could not be downloaded before; it is tried again by itself.' : `It did not start here before. If it fails again, ${u.version} is put back.`;
8181
8192
  $('updates-retry-note').hidden = !failedHere;
8182
8193
  $('updates-retry-yes').hidden = true; $('updates-retry-no').hidden = true; apply.hidden = false;
8183
8194
  /* The last thing that went wrong, said once at the top, in words: a version put