clavarium 0.2.73-next.1 → 0.2.74-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.
@@ -211,6 +211,18 @@ run() { if [ "$SAY" = "yes" ]; then printf '%s\n' "$*"; else exec "$@"; fi; }
211
211
  # with a letter; no trailing hyphen; 32 at most. The same rule as the server.
212
212
  is_name() { [[ "$1" =~ ^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$ ]]; }
213
213
  vm_of() { is_name "${1#clv-}" && [ "$1" != "${1#clv-}" ] || refuse "not one of our VMs: ${1:-<empty>}"; }
214
+ # The qemu process(es) of one of our machines -- a qemu-system whose disk is in
215
+ # that instance, the mapping "server room" also uses. Empty when none is left,
216
+ # which is what a suspend that freed the RAM leaves behind.
217
+ vm_qemu_pids() {
218
+ local want="$1" pid vm
219
+ for pid in $(pgrep qemu-system 2>/dev/null || true); do
220
+ vm="$(tr '\0' '\n' < "/proc/$pid/cmdline" 2>/dev/null | grep -oE '/instances/clv(shelf)?-[a-z0-9-]+/' | head -1 | cut -d/ -f3)" || vm=""
221
+ [ "$vm" = "$want" ] && printf '%s\n' "$pid"
222
+ done
223
+ }
224
+ # No qemu left for this machine after a short grace: its RAM has been freed.
225
+ vm_freed() { local v="$1" i; for i in $(seq 1 24); do [ -z "$(vm_qemu_pids "$v")" ] && return 0; sleep 0.5; done; return 1; }
214
226
  number() { [[ "$1" =~ ^[0-9]{1,6}$ ]] || refuse "not a number: ${1:-<empty>}"; }
215
227
  # A disk or partition named by its device: /dev/sdX, /dev/vdX, /dev/nvmeNnN(pN),
216
228
  # /dev/xvdX, /dev/mmcblkN(pN), with a digit or two at the end; a loop device only
@@ -770,9 +782,51 @@ case "$AREA $VERB" in
770
782
  "vm info")
771
783
  [ $# -eq 1 ] || usage; vm_of "$1"
772
784
  run "$MULTIPASS" info "$1" --format json ;;
773
- "vm start"|"vm stop"|"vm suspend")
785
+ "vm start"|"vm stop")
774
786
  [ $# -eq 1 ] || usage; vm_of "$1"
775
787
  run "$MULTIPASS" "$VERB" "$1" ;;
788
+ "vm suspend")
789
+ # Veille: suspend must save the machine's state AND free its RAM by ending
790
+ # its qemu process. Multipass saves the state reliably but at times leaves
791
+ # qemu alive (canonical/multipass #446, #2152, #5432), so the RAM stays
792
+ # taken though the machine shows "Suspended". The state being saved, we make
793
+ # the RAM come back, gentlest first: a second suspend from a clean running
794
+ # state usually ends qemu (and keeps the ~2s resume); failing that, a clean
795
+ # stop frees it for sure (it then wakes by a boot). Normally qemu is already
796
+ # gone after the first suspend and none of this runs.
797
+ [ $# -eq 1 ] || usage; vm_of "$1"
798
+ if [ "$SAY" = "yes" ]; then
799
+ printf '%s\n' "$MULTIPASS suspend $1" \
800
+ "if its qemu still holds the RAM: $MULTIPASS start $1 && $MULTIPASS suspend $1 (wake+resleep)" \
801
+ "if it still does: $MULTIPASS stop $1 (free it; it wakes by a boot)"
802
+ exit 0
803
+ fi
804
+ "$MULTIPASS" suspend "$1" || refuse "suspend of $1 failed"
805
+ vm_freed "$1" && exit 0
806
+ "$MULTIPASS" start "$1" >/dev/null 2>&1 && "$MULTIPASS" suspend "$1" >/dev/null 2>&1
807
+ vm_freed "$1" && exit 0
808
+ "$MULTIPASS" stop "$1" >/dev/null 2>&1 || true
809
+ vm_freed "$1" && exit 0
810
+ refuse "suspended $1 but its memory was not freed (its qemu stayed); the VM manager likely needs a restart" ;;
811
+ "vm reclaim")
812
+ # Free a machine that is ASLEEP but whose qemu still holds the RAM -- a
813
+ # suspend (maybe from before this existed) that did not end the process.
814
+ # Idempotent and safe for an asleep machine (nobody is using it): if its
815
+ # qemu is already gone, nothing happens. Touches only this machine, and
816
+ # never restarts the VM manager.
817
+ [ $# -eq 1 ] || usage; vm_of "$1"
818
+ if [ "$SAY" = "yes" ]; then
819
+ printf '%s\n' "if $1's qemu still holds the RAM: $MULTIPASS start $1 && $MULTIPASS suspend $1 (wake+resleep)" \
820
+ "if it still does: $MULTIPASS stop $1 (free it; it wakes by a boot)"
821
+ exit 0
822
+ fi
823
+ # Each step that frees the RAM says how, so the server can tell the owner.
824
+ vm_freed "$1" && { echo "freed-already"; exit 0; }
825
+ "$MULTIPASS" start "$1" >/dev/null 2>&1 && "$MULTIPASS" suspend "$1" >/dev/null 2>&1
826
+ vm_freed "$1" && { echo "freed-resleep"; exit 0; }
827
+ "$MULTIPASS" stop "$1" >/dev/null 2>&1 || true
828
+ vm_freed "$1" && { echo "freed-stop"; exit 0; }
829
+ refuse "could not free $1's memory (its qemu stayed); the VM manager likely needs a restart" ;;
776
830
  "vm kill")
777
831
  # A stop that does not wait for the system inside: asked only after a
778
832
  # clean stop hung or failed (a restart the owner asked for).
package/deploy/install.sh CHANGED
@@ -605,7 +605,7 @@ $BIND
605
605
  @api path /api/* /c/api/*
606
606
  handle @api {
607
607
  header Content-Type "application/json; charset=utf-8"
608
- respond "{\"error\":\"Clavarium is being updated or restarted: it comes back by itself in a moment.\",\"down\":true}" 503
608
+ respond "{\"error\":\"Clavarium did not answer just now -- it may be busy or restarting. It comes back by itself; try again in a moment.\",\"down\":true}" 503
609
609
  }
610
610
  handle {
611
611
  root * /var/lib/clavarium/maintenance
@@ -140,7 +140,7 @@ export const MAINTENANCE_BLOCK = [
140
140
  '\t\t\t\t@api path /api/* /c/api/*',
141
141
  '\t\t\t\thandle @api {',
142
142
  '\t\t\t\t\theader Content-Type "application/json; charset=utf-8"',
143
- '\t\t\t\t\trespond "{\\"error\\":\\"Clavarium is being updated or restarted: it comes back by itself in a moment.\\",\\"down\\":true}" 503',
143
+ '\t\t\t\t\trespond "{\\"error\\":\\"Clavarium did not answer just now -- it may be busy or restarting. It comes back by itself; try again in a moment.\\",\\"down\\":true}" 503',
144
144
  '\t\t\t\t}',
145
145
  '\t\t\t\thandle {',
146
146
  `\t\t\t\t\troot * ${MAINTENANCE_DIR}`,
@@ -1,20 +1,20 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.73-next.1",
3
+ "version": "0.2.74-beta.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.73-next.1",
9
+ "version": "0.2.74-beta.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
13
13
  "@xterm/xterm": "^6.0.0",
14
- "clavarium-binder": "0.1.8-next.1",
14
+ "clavarium-binder": "0.1.12-next.1",
15
15
  "clavarium-docket": "0.1.1",
16
16
  "clavarium-parley": "0.17.11-next.1",
17
- "clavarium-tether": "0.1.0-next.11",
17
+ "clavarium-tether": "0.1.0-next.23",
18
18
  "mermaid": "11.17.2",
19
19
  "node-pty": "^1.1.0",
20
20
  "pdfjs-dist": "6.4.299",
@@ -716,9 +716,9 @@
716
716
  }
717
717
  },
718
718
  "node_modules/clavarium-binder": {
719
- "version": "0.1.8-next.1",
720
- "resolved": "https://registry.npmjs.org/clavarium-binder/-/clavarium-binder-0.1.8-next.1.tgz",
721
- "integrity": "sha512-0ZvTgn4z3IzLWjVyt5H82tnrE4g4Zdh0eb0kKrpVYjJ8vEfun6CmzHFclce9lb7vH+CC5ozKETuTAmSVYkk+lg==",
719
+ "version": "0.1.12-next.1",
720
+ "resolved": "https://registry.npmjs.org/clavarium-binder/-/clavarium-binder-0.1.12-next.1.tgz",
721
+ "integrity": "sha512-V/+nRPEVjD9alhZqHqqFEyIVj17jhMyUtOSVD3TzwnITWg7TpvS+KCkgGoJek7XBd4ZooOlkaAFlLU8vzVMSVw==",
722
722
  "license": "MIT",
723
723
  "bin": {
724
724
  "binder": "bin/binder.mjs",
@@ -755,9 +755,9 @@
755
755
  }
756
756
  },
757
757
  "node_modules/clavarium-tether": {
758
- "version": "0.1.0-next.11",
759
- "resolved": "https://registry.npmjs.org/clavarium-tether/-/clavarium-tether-0.1.0-next.11.tgz",
760
- "integrity": "sha512-GiLaCXmANy8OsiTacZIe5n+UUK+Lw33QzonZkU+vTVSx8X5g4fF4hzUkfRmpXWMDVWMuvTvptL/qIrJNbXJ9+Q==",
758
+ "version": "0.1.0-next.23",
759
+ "resolved": "https://registry.npmjs.org/clavarium-tether/-/clavarium-tether-0.1.0-next.23.tgz",
760
+ "integrity": "sha512-/Ke9LtsbVElZxQ53n9bkcfwODYQeNOmG62JTyW4rLmFVWcgvVgsN41HbhF+WWBwhP3/zU+/NexXsSkefnGbR7w==",
761
761
  "license": "MIT",
762
762
  "bin": {
763
763
  "tether": "bin/cli.mjs",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.73-next.1",
3
+ "version": "0.2.74-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.",
@@ -44,10 +44,10 @@
44
44
  "dependencies": {
45
45
  "@xterm/addon-fit": "^0.11.0",
46
46
  "@xterm/xterm": "^6.0.0",
47
- "clavarium-binder": "0.1.8-next.1",
47
+ "clavarium-binder": "0.1.12-next.1",
48
48
  "clavarium-docket": "0.1.1",
49
49
  "clavarium-parley": "0.17.11-next.1",
50
- "clavarium-tether": "0.1.0-next.11",
50
+ "clavarium-tether": "0.1.0-next.23",
51
51
  "mermaid": "11.17.2",
52
52
  "node-pty": "^1.1.0",
53
53
  "pdfjs-dist": "6.4.299",
@@ -10,12 +10,11 @@
10
10
  * instead the keeper reveals it to the connector alone, host-side, and acts on
11
11
  * the agent's behalf within the level and rules the person set.
12
12
  *
13
- * ONE ACCOUNT, ONE TOKEN, SEVERAL TARGETS. A Google consent for mail+calendar+
14
- * contacts yields a single refresh token; this makes one host-only secret and a
15
- * Tether target per kind, each naming that secret. Microsoft's Thunderbird client
16
- * carries only the mail scope here, so a Microsoft consent makes the mail target
17
- * alone (calendar and files over Graph need a deployment's own OAuth app, added
18
- * later as config.clientId + an own client secret).
13
+ * ONE ACCOUNT, ONE TOKEN, SEVERAL TARGETS. A consent for mail+calendar+contacts
14
+ * yields a single refresh token; this makes one host-only secret and a Tether
15
+ * target per kind, each naming that secret. Both providers borrow Thunderbird's
16
+ * own open-source desktop client, verified for all three: Google over IMAP +
17
+ * CalDAV/CardDAV, Microsoft over Microsoft Graph (mail, calendar and contacts).
19
18
  *
20
19
  * A CREATED TARGET IS GIVEN TO NO ONE. The person grants it per conversation, at
21
20
  * its own level, from the page (Assets > Access) -- like git: one mailbox, many
@@ -23,14 +22,16 @@
23
22
  */
24
23
  import { Refusal } from './conversations.mjs';
25
24
  import { createHash } from 'node:crypto';
26
- import { consentUrl, exchangeCode, extractCode, thunderbird, scopeFor, pkcePair, newState, PROVIDERS } from './oauth.mjs';
25
+ import { consentUrl, exchangeCode, extractCode, thunderbird, scopeFor, kindsGranted, refreshAccess, pkcePair, newState, PROVIDERS } from './oauth.mjs';
27
26
 
28
27
  /* The loopback the provider sends the code back to; nothing listens there. The
29
28
  person's browser lands on a page that will not load, and they copy the whole
30
- address -- which carries the code -- back into Clavarium. Desktop OAuth clients
31
- accept any 127.0.0.1 port, and the same address trades the code, so it only has
32
- to stay constant. (Shared, on purpose, with the older file-copy mailbox.) */
29
+ address -- which carries the code -- back into Clavarium. The same address
30
+ trades the code, so it must match what the borrowed client registered. Both
31
+ borrowed Thunderbird clients (one for Google, one for Microsoft) registered the
32
+ loopback on any 127.0.0.1 port, so one address serves both. */
33
33
  const REDIRECT = 'http://127.0.0.1:47813/';
34
+ const redirectFor = () => REDIRECT;
34
35
  const PENDING_MS = 10 * 60_000;
35
36
  const PENDING_MAX = 20;
36
37
 
@@ -38,11 +39,11 @@ const PENDING_MAX = 20;
38
39
  Tether kind each becomes, and whether the target needs the email address. */
39
40
  const KIND = {
40
41
  mail: { connector: 'mail', kind: 'mail', title: 'Mail', needsUser: true },
41
- calendar: { connector: 'calendar', kind: 'calendar', title: 'Agenda', needsUser: false },
42
+ calendar: { connector: 'calendar', kind: 'calendar', title: 'Agenda', needsUser: true },
42
43
  contacts: { connector: 'contacts', kind: 'contacts', title: 'Contacts', needsUser: true },
43
44
  };
44
45
  /* What each provider's built-in (Thunderbird) client grants a refresh token for. */
45
- const SUPPORTED = { google: ['mail', 'calendar', 'contacts'], microsoft: ['mail'] };
46
+ const SUPPORTED = { google: ['mail', 'calendar', 'contacts'], microsoft: ['mail', 'calendar', 'contacts'] };
46
47
 
47
48
  const emailOk = (s) => /^[^\s@]{1,64}@[^\s@]{1,190}\.[^\s@]{2,}$/.test(s);
48
49
  /* A deterministic, valid secret name for an account's token: a short slug of the
@@ -85,7 +86,7 @@ export class Accounts {
85
86
  const { clientId } = thunderbird(prov);
86
87
  const state = newState();
87
88
  const { verifier, challenge } = pkcePair();
88
- const url = consentUrl(prov, { clientId, redirectUri: REDIRECT, scope: scopeFor(prov, chosen), state, codeChallenge: challenge, loginHint: address });
89
+ const url = consentUrl(prov, { clientId, redirectUri: redirectFor(prov), scope: scopeFor(prov, chosen), state, codeChallenge: challenge, loginHint: address });
89
90
  this.#pending.set(state, { provider: prov, user: address, kinds: chosen, verifier, at: Date.now() });
90
91
  return { url };
91
92
  }
@@ -102,19 +103,32 @@ export class Accounts {
102
103
  let code;
103
104
  try { code = extractCode(redirected, { state }); } catch (e) { throw new Refusal(400, e.message); }
104
105
  const { clientId, clientSecret } = thunderbird(p.provider);
105
- let refreshToken;
106
- try { ({ refreshToken } = await exchangeCode(p.provider, { clientId, clientSecret, redirectUri: REDIRECT, code, codeVerifier: p.verifier, fetch: this.#fetch })); }
106
+ let refreshToken, grantedScope;
107
+ try { ({ refreshToken, scope: grantedScope } = await exchangeCode(p.provider, { clientId, clientSecret, redirectUri: redirectFor(p.provider), code, codeVerifier: p.verifier, fetch: this.#fetch })); }
107
108
  catch (e) { throw new Refusal(502, `The connection could not be completed: ${e.message}`); }
108
109
  if (!refreshToken) throw new Refusal(502, 'The account returned no lasting token; allow offline access and try again.');
110
+ /* What was actually allowed. A provider may grant fewer kinds than asked
111
+ (the person unticks one); the token's scope says so, so we make a target
112
+ only for a kind that was really granted, and tell the caller which were
113
+ denied -- no guessing. If the scope is unreadable (matched nothing) we
114
+ trust what was asked, as before. */
115
+ const matched = kindsGranted(p.provider, grantedScope);
116
+ const useScope = matched.length > 0;
117
+ const authorized = useScope ? p.kinds.filter((k) => matched.includes(k)) : p.kinds;
118
+ const denied = useScope ? p.kinds.filter((k) => !matched.includes(k)) : [];
109
119
  /* The token is kept host-only: it can never be attached to a conversation,
110
120
  so it is never delivered to a machine -- the keeper reveals it by name. */
111
121
  const name = secretName(p.provider, p.user);
112
122
  this.#secrets.set({ name, value: refreshToken, hostOnly: true });
113
123
  const label = PROVIDERS[p.provider].label;
114
124
  const made = [];
115
- for (const k of p.kinds) {
125
+ for (const k of authorized) {
116
126
  const spec = KIND[k];
117
- const config = { provider: p.provider };
127
+ /* Pin the client that minted the token onto the target, so the keeper
128
+ refreshes with the same one -- a refresh token is bound to its client,
129
+ and this keeps a target working even if the built-in default later
130
+ moves (the connector prefers config.clientId over its own default). */
131
+ const config = { provider: p.provider, clientId, authorizedKinds: authorized };
118
132
  if (spec.needsUser) config.user = p.user;
119
133
  const target = this.#targets.put({
120
134
  id: targetId(k, p.provider, p.user),
@@ -123,7 +137,33 @@ export class Accounts {
123
137
  });
124
138
  made.push({ id: target?.id ?? targetId(k, p.provider, p.user), title: target?.title, kind: spec.kind });
125
139
  }
126
- return { provider: p.provider, user: p.user, targets: made };
140
+ return { provider: p.provider, user: p.user, targets: made, authorized, denied };
141
+ }
142
+
143
+ /* Check, live, what a connected account is really authorized for right now --
144
+ not only at connection. A refresh host-side (the token never leaves the
145
+ server) reads the token's current scopes, so the page can say "mail yes,
146
+ calendar no" at any time and reflect a permission removed since. Records the
147
+ result on every target of the account, so it shows without another check. */
148
+ async verify({ id } = {}) {
149
+ const all = this.#targets.all?.() ?? [];
150
+ const target = all.find((t) => t.id === id);
151
+ if (!target) throw new Refusal(404, 'No such connexion.');
152
+ const provider = target.config?.provider;
153
+ if (!PROVIDERS[provider]) throw new Refusal(400, 'This connexion is not an account.');
154
+ const secretRef = target.secrets?.refresh;
155
+ const refreshToken = secretRef && this.#secrets.reveal(secretRef);
156
+ if (!refreshToken) throw new Refusal(404, 'The account token is gone; connect it again.');
157
+ const def = thunderbird(provider);
158
+ const clientId = target.config?.clientId || def.clientId;
159
+ let scope, fresh;
160
+ try { ({ scope, refreshToken: fresh } = await refreshAccess(provider, { clientId, clientSecret: def.clientSecret, refreshToken, fetch: this.#fetch })); }
161
+ catch (e) { throw new Refusal(502, `The account could not be checked: ${e.message}`); }
162
+ /* Keep the token current if the provider rotated it on the refresh. */
163
+ if (fresh && fresh !== refreshToken) this.#secrets.set({ name: secretRef, value: fresh, hostOnly: true });
164
+ const authorized = kindsGranted(provider, scope);
165
+ for (const t of all.filter((x) => x.secrets?.refresh === secretRef)) this.#targets.put({ ...t, config: { ...t.config, authorizedKinds: authorized } });
166
+ return { id, provider, all: SUPPORTED[provider], authorized };
127
167
  }
128
168
 
129
169
  #sweep() { const now = Date.now(); for (const [k, v] of this.#pending) if (now - v.at > PENDING_MS) this.#pending.delete(k); }
package/server/api.mjs CHANGED
@@ -430,6 +430,7 @@ export async function handleApi(request, response, conversations, headers, resou
430
430
  kept host-only, a Tether target made): see accounts.mjs. */
431
431
  if (pathname === '/api/accounts/consent' && accounts) return send(200, accounts.consent(body)), true;
432
432
  if (pathname === '/api/accounts/connect' && accounts) { const made = await accounts.connect(body); return send(201, made), true; }
433
+ if (pathname === '/api/accounts/verify' && accounts) { const r = await accounts.verify(body); return send(200, r), true; }
433
434
  /* Assets > Access: the owner sets a conversation's level and rules on a
434
435
  target, decides a call that waited, or removes a target. Each is an op the
435
436
  keeper runs as the owner (person), never as an agent. */
@@ -49,6 +49,13 @@ export const RESERVE_DISK_MAX_MB = 1024 * 1024;
49
49
  export const RESERVE_MEMORY_MAX_MB = 256 * 1024;
50
50
  export const ROOM_MS = 10_000;
51
51
  export const USAGE_MS = 5 * 60_000;
52
+ /* A sleeping machine whose qemu still holds at least this much host memory is a
53
+ suspend that did not free it (see the host program's `vm suspend`); the watch
54
+ reclaims it. */
55
+ export const RECLAIM_MIN_MB = 128;
56
+ /* The same machine is not reclaimed again within this, so a stubborn one (rare,
57
+ needs a VM-manager restart) is reported once, not looped on. */
58
+ export const RECLAIM_EVERY_MS = 30 * 60_000;
52
59
  /* The page shows its small gauge when disk or memory is fuller than this, or
53
60
  when what is free is under this many times the reserve. */
54
61
  export const HIGH_PERCENT = 85;
@@ -92,7 +99,7 @@ const percent = (part, all) => (all > 0 ? Math.round((part / all) * 100) : 0);
92
99
  export class Capacity {
93
100
  /* What the machines take on their disk, as last measured (MB), or undefined. */
94
101
  machinesUsedMb() { const u = this.#usage; if (!u) return undefined; return Object.values(u.machines ?? {}).reduce((a, b) => a + b, 0) + (u.shelf ?? 0) + (u.images ?? 0); }
95
- #run; #store; #conversations; #shelf; #now; #roomMs; #sleep; #alert; #say; #short = { disk: false, memory: false }; #room = null; #roomAt = -Infinity; #usage = null; #usageAt = -Infinity; #going = null; #measuring = null;
102
+ #run; #store; #conversations; #shelf; #now; #roomMs; #sleep; #alert; #say; #reclaim; #reclaimEveryMs; #sweeping = false; #short = { disk: false, memory: false }; #room = null; #roomAt = -Infinity; #usage = null; #usageAt = -Infinity; #going = null; #measuring = null;
96
103
 
97
104
  /* `run(argv)`: the host program. `store`: where the reserve is kept.
98
105
  `conversations`: what each machine was given. `shelf`: how large a
@@ -100,8 +107,8 @@ export class Capacity {
100
107
  /* `roomMs`: how long what is free is taken as known (ROOM_MS). */
101
108
  /* `sleep(name)`, `alert(payload)`, `say(name, text)`: what watch() does
102
109
  when what is free falls under the reserve. */
103
- constructor({ run, store, conversations, shelf = null, now = () => Date.now(), roomMs = ROOM_MS, sleep = null, alert = null, say = null }) {
104
- this.#roomMs = roomMs; this.#sleep = sleep; this.#alert = alert; this.#say = say;
110
+ constructor({ run, store, conversations, shelf = null, now = () => Date.now(), roomMs = ROOM_MS, sleep = null, alert = null, say = null, reclaim = null, reclaimEveryMs = RECLAIM_EVERY_MS }) {
111
+ this.#roomMs = roomMs; this.#sleep = sleep; this.#alert = alert; this.#say = say; this.#reclaim = reclaim; this.#reclaimEveryMs = reclaimEveryMs;
105
112
  this.#run = run; this.#store = store; this.#conversations = conversations; this.#shelf = shelf; this.#now = now;
106
113
  }
107
114
 
@@ -288,9 +295,53 @@ export class Capacity {
288
295
  return done;
289
296
  }
290
297
 
298
+ /* WATCHED too, and on its own: machines that are ASLEEP (not awake) yet whose
299
+ qemu still holds the host RAM -- a suspend that did not end the process,
300
+ including ones left stuck before this ran. Each is freed through the host
301
+ program (`vm reclaim`: wake+resleep, then a clean stop if needed), the owner
302
+ told, and not tried again within reclaimEveryMs, so a stubborn one (rare,
303
+ the VM manager would need a restart) is reported once, not looped on. Only
304
+ asleep machines are touched; the others are never disturbed, and the VM
305
+ manager is never restarted. Resolves with what was reclaimed. */
306
+ async reclaimSleepers() {
307
+ if (!this.#reclaim || this.#sweeping) return [];
308
+ this.#sweeping = true;
309
+ try {
310
+ const f = this.#figures(await this.room({ fresh: true }).catch(() => null));
311
+ if (!f) return [];
312
+ const awake = new Set(this.#conversations.awake?.() ?? []);
313
+ const holding = f.machines.filter((m) => m.name && !m.shelf && !awake.has(m.name) && m.rssMb >= RECLAIM_MIN_MB);
314
+ if (!holding.length) return [];
315
+ const now = this.#now();
316
+ const at = this.#store.get('reclaim')?.at ?? {};
317
+ const done = [];
318
+ for (const m of holding) {
319
+ if (at[m.name] && now - at[m.name] < this.#reclaimEveryMs) continue;
320
+ at[m.name] = now;
321
+ this.#store.put({ name: 'reclaim', at });
322
+ const held = m.rssMb;
323
+ const how = await Promise.resolve(this.#reclaim(m.name)).then((x) => String(x || ''), () => '');
324
+ const by = how.includes('resleep') ? ' by waking it and putting it back to sleep'
325
+ : how.includes('stop') ? ' with a clean stop (it will boot when you open it)'
326
+ : '';
327
+ const after = this.#figures(await this.room({ fresh: true }).catch(() => null));
328
+ const freed = !after?.machines.some((x) => x.name === m.name && !awake.has(x.name) && x.rssMb >= RECLAIM_MIN_MB);
329
+ this.#alert?.(freed
330
+ ? { title: "Reclaimed a sleeping machine's memory", body: `${m.name} was asleep but still held ${gb(held)} (its sleep had not freed it); its memory was reclaimed${by}.`, url: '/?open=settings&at=resources' }
331
+ : { title: 'A sleeping machine still holds memory', body: `${m.name} was asleep but still held ${gb(held)} and could not be freed; the VM manager may need a restart.`, url: '/?open=settings&at=resources' });
332
+ this.#say?.(m.name, freed
333
+ ? `This machine was asleep but still held ${gb(held)} of memory (its sleep had not freed it). Its memory was reclaimed${by}; it still wakes when you open it.`
334
+ : `This machine was asleep but still held ${gb(held)} of memory, and it could not be freed automatically — the VM manager may need a restart.`);
335
+ done.push({ name: m.name, heldMb: held, freed });
336
+ }
337
+ return done;
338
+ } finally { this.#sweeping = false; }
339
+ }
340
+
291
341
  /* Watches every `everyMs`; returns what stops it. */
292
342
  start(everyMs = WATCH_MS) {
293
- const timer = setInterval(() => { void this.watch().catch(() => {}); }, everyMs);
343
+ const tick = () => { void this.watch().catch(() => {}).finally(() => { void this.reclaimSleepers().catch(() => {}); }); };
344
+ const timer = setInterval(tick, everyMs);
294
345
  timer.unref?.();
295
346
  return () => clearInterval(timer);
296
347
  }
@@ -211,9 +211,15 @@ const seeCommits = (name, head, base, n) => (short(head) && short(base) && Numbe
211
211
  long a finished run is kept for the request that asks again just after. */
212
212
  export const CHECK_WAIT_MS = 20_000;
213
213
  export const CHECK_KEEP_MS = 60_000;
214
+ /* A send (the push to the remote) runs in the background, like a check: one
215
+ request waits at most this long, then hears { status: 'sending' } and asks
216
+ again (join), so a long push never outruns the proxy. The push itself is
217
+ already bounded (PUSH_MS); a finished send is kept this long for the asking. */
218
+ export const SENDING_WAIT_MS = 20_000;
219
+ export const SENDING_KEEP_MS = 60_000;
214
220
 
215
221
  export class GitKeeper {
216
- #store; #review; #resources; #checks; #alerts; #now; #tellAgent; #thread; #last; #held = new Map(); #results = new Map(); #running = new Set(); #telling = new Map(); #inFlight = new Map();
222
+ #store; #review; #resources; #checks; #alerts; #now; #tellAgent; #thread; #last; #held = new Map(); #results = new Map(); #running = new Set(); #telling = new Map(); #inFlight = new Map(); #sending = new Map();
217
223
 
218
224
  /* `review`: GitReview (reads, the reference, Send). `checks`: GitChecks.
219
225
  `alerts`: what tells the owner's phone. `tellAgent(repository, line,
@@ -556,7 +562,30 @@ export class GitKeeper {
556
562
 
557
563
  /* Send, from the page: as GitReview.push, and refused when the owner
558
564
  requires passing checks and none passed for this commit and branch. */
565
+ /* The push runs in the background; the request waits at most SENDING_WAIT_MS,
566
+ then returns { status: 'sending' } and the page asks again with `join: true`
567
+ until it ends -- so a slow push never blocks the request past the proxy's
568
+ patience. The push itself is still bounded (PUSH_MS), so it cannot run on
569
+ for hours. A send already going is joined; one just ended is re-run only
570
+ on a fresh click (no `join`), and re-sending the same commit is a no-op. */
559
571
  async send(name, body) {
572
+ const r = this.#repository(name);
573
+ const key = `${r.name}\n${body?.head ?? ''}\n${body?.target ?? ''}`;
574
+ let entry = this.#sending.get(key);
575
+ if (!entry || (entry.done && body?.join !== true)) {
576
+ const made = { done: false, result: undefined, error: undefined };
577
+ made.run = this.#doSend(r.name, body)
578
+ .then((result) => { made.result = result; }, (error) => { made.error = error; })
579
+ .finally(() => { made.done = true; setTimeout(() => { if (this.#sending.get(key) === made) this.#sending.delete(key); }, SENDING_KEEP_MS).unref?.(); });
580
+ entry = made; this.#sending.set(key, made);
581
+ }
582
+ const ms = Number.isFinite(body?.wait) ? Math.max(0, Math.min(body.wait, SENDING_WAIT_MS)) : SENDING_WAIT_MS;
583
+ await Promise.race([entry.run, new Promise((res) => { setTimeout(res, ms).unref?.(); })]);
584
+ if (!entry.done) return { status: 'sending' };
585
+ if (entry.error) throw entry.error;
586
+ return entry.result;
587
+ }
588
+ async #doSend(name, body) {
560
589
  const r = this.#repository(name);
561
590
  if (this.settings(r.name).requireForSend) {
562
591
  const target = body?.target || undefined;
package/server/main.mjs CHANGED
@@ -411,7 +411,19 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
411
411
  /* Connecting a mailbox, calendar or address book by token: the consent happens
412
412
  in the owner's browser, the refresh token is kept host-only (never in a
413
413
  machine) and a Tether target is made for it: see accounts.mjs. */
414
- const accounts = new Accounts({ secrets, targets: { put: (spec) => tethers.store().putTarget(spec) } });
414
+ const accounts = new Accounts({ secrets, targets: { put: (spec) => tethers.store().putTarget(spec), all: () => tethers.store().targets() } });
415
+ /* A calendar target made before it needed the account address (Google CalDAV
416
+ puts it in the URL) carries none. The same account's mailbox or address book
417
+ has it -- they share the one refresh token -- so fill it in from a sibling,
418
+ once, with no reconnection asked of anyone. */
419
+ (() => {
420
+ const store = tethers.store();
421
+ for (const t of store.targets()) {
422
+ if (t.kind !== 'calendar' || t.config?.user || !t.secrets?.refresh) continue;
423
+ const sib = store.targets().find((o) => o.secrets?.refresh === t.secrets.refresh && o.config?.user);
424
+ if (sib) store.putTarget({ ...t, config: { ...t.config, user: sib.config.user } });
425
+ }
426
+ })();
415
427
  /* A repository's origin kept up to date, checks run in the machine, and
416
428
  automatic sending to the branches the owner listed: see gitkeeper.mjs. */
417
429
  /* What could not be read is told to the agents that write in the repository, where they can act. */
@@ -507,11 +519,13 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
507
519
  /* Settings, Updates: what the updater (deploy/updater.mjs, as root) wrote, and how to ask it. */
508
520
  const updates = new Updates({ host: asHost, version: platform.version, store: new Store(`${dataDir}/updates.json`), alerts, ...(updateState ? { stateFile: updateState } : {}), ...(updateConf ? { confFile: updateConf } : {}) });
509
521
  const stopUpdates = updates.watch();
510
- const setup = new Setup({ store: new Store(`${dataDir}/flows.json`), version: platform.version, conversations: all, resources: folders, secrets, devices, shortcuts, wakeups, answerer, talk, gitKeeper, gitAccess, mailboxes, signin, network, guide, tethers, ...(setupPollMs ? { pollMs: setupPollMs } : {}) });
522
+ const setup = new Setup({ store: new Store(`${dataDir}/flows.json`), version: platform.version, conversations: all, resources: folders, secrets, devices, shortcuts, wakeups, answerer, talk, gitKeeper, gitAccess, mailboxes, signin, network, guide, tethers, groups, ...(setupPollMs ? { pollMs: setupPollMs } : {}) });
511
523
  /* This server's disk and memory, and the reserve no machine may eat into: see capacity.mjs. */
512
524
  const capacity = new Capacity({ run: asHost, store: new Store(`${dataDir}/server.json`), conversations: all, shelf, ...(serverRoomMs === undefined ? {} : { roomMs: serverRoomMs }),
513
525
  /* Under the reserve: the machine that takes the most put to sleep, the owner told, and its chat. */
514
526
  sleep: (name) => { events.add({ kind: 'machine', text: `Machine of ${name} put to sleep: this server was short of room`, conversation: name }); return all.sleep(name); }, alert: (payload) => { events.add({ kind: 'server', text: `${payload.title}: ${payload.body ?? ''}`.trim() }); void alerts.tell(payload); },
527
+ /* A machine asleep but still holding its RAM (a suspend that did not free it): its memory reclaimed, only that machine touched. */
528
+ reclaim: (name) => { events.add({ kind: 'machine', text: `Machine of ${name}: memory reclaimed (it was asleep but still held RAM)`, conversation: name }); return vms.reclaim(name).then((r) => (r.stdout || '').trim()); },
515
529
  say: (name, text) => { try { talk.event(name, { kind: 'machine-problem', text, tone: 'warn', topic: 'Machine' }); } catch { /* its chat may be off */ } } });
516
530
  all.room = (ask) => capacity.check(ask);
517
531
  const stopWatch = capacity.start();
package/server/oauth.mjs CHANGED
@@ -37,14 +37,14 @@ const b64url = (buf) => Buffer.from(buf).toString('base64url');
37
37
 
38
38
  /* Per-provider endpoints, the scopes we may ask for by kind, and a built-in,
39
39
  already-verified open-source desktop client as the default (the `thunderbird`
40
- field, kept by that name for its callers). WHICH client matters: a client is
41
- only granted the scopes its app was verified for. For GOOGLE we borrow GNOME
42
- Online Accounts' client, verified for mail AND calendar AND contacts, so one
43
- consent gives all three. For MICROSOFT we use Thunderbird's client, verified
44
- for mail (IMAP) only; Microsoft calendar/contacts go over Graph and need a
45
- Graph-verified client -- see card #110. `consentExtra` is what a provider
46
- needs on the consent URL to return a refresh token; `offlineScope` is the same
47
- thing when it is a scope rather than a parameter (Microsoft). */
40
+ field). We borrow THUNDERBIRD's own client for BOTH providers: each registered
41
+ the loopback 127.0.0.1 redirect on any port, so the person always lands on the
42
+ same copy-pastable http://127.0.0.1 address, and each is cleared for the three
43
+ kinds -- Google's client carries the mail + CalDAV + CardDAV scopes; Microsoft's
44
+ takes mail, calendar and contacts over Graph (a multitenant public client, by
45
+ dynamic consent). `consentExtra` is what a provider needs on the consent URL to
46
+ return a refresh token; `offlineScope` is the same thing when it is a scope
47
+ rather than a parameter (Microsoft). */
48
48
  export const PROVIDERS = {
49
49
  google: {
50
50
  label: 'Google',
@@ -58,12 +58,16 @@ export const PROVIDERS = {
58
58
  calendar: 'https://www.googleapis.com/auth/calendar',
59
59
  contacts: 'https://www.googleapis.com/auth/carddav',
60
60
  },
61
- /* GNOME Online Accounts' built-in client (open source, embedded secret
62
- sanctioned by Google for an installed app). Verified for mail,
63
- calendar and contacts -- unlike Thunderbird's, which carries mail only. */
61
+ /* Thunderbird's own built-in Google client (open source, embedded secret
62
+ sanctioned by Google for an installed app; comm-central
63
+ OAuth2Providers.sys.mjs). Its GOOGLE_SCOPES carry mail AND CalDAV AND
64
+ CardDAV, so one consent gives all three -- the same loopback 127.0.0.1
65
+ redirect as before. Using Thunderbird for Google too means one borrowed
66
+ identity for both providers. (GNOME Online Accounts' client
67
+ 44438659992-... worked as well; we unified on Thunderbird.) */
64
68
  thunderbird: {
65
- clientId: '44438659992-7kgjeitenc16ssihbtdjbgguch7ju55s.apps.googleusercontent.com',
66
- clientSecret: '-gMLuQyDiI0XrQS_vx_mhuYF',
69
+ clientId: '406964657835-aq8lmia8j95dhl1a2bvharmfk3t1hgqj.apps.googleusercontent.com',
70
+ clientSecret: 'kSmqreRr0qwBWJgbf5Y-PjSU',
67
71
  },
68
72
  },
69
73
  microsoft: {
@@ -73,13 +77,21 @@ export const PROVIDERS = {
73
77
  pkce: true,
74
78
  consentExtra: {},
75
79
  offlineScope: 'offline_access',
76
- /* Mail (and SMTP) are outlook.office.com resources; calendar/files over
77
- Graph are a different resource and a separate token -- added when those
78
- connectors arrive, not mixed into one mail request. */
80
+ /* Microsoft over Graph: mail, calendar and contacts all go through
81
+ graph.microsoft.com (the mail connector uses its Graph path for
82
+ Microsoft). mail.send is needed to send. Thunderbird's public client
83
+ takes these delegated scopes by dynamic consent. */
79
84
  scopes: {
80
- mail: 'https://outlook.office.com/IMAP.AccessAsUser.All',
81
- smtp: 'https://outlook.office.com/SMTP.Send',
85
+ mail: 'mail.readwrite mail.send',
86
+ calendar: 'calendars.readwrite',
87
+ contacts: 'contacts.readwrite',
82
88
  },
89
+ /* Thunderbird's built-in Microsoft client (open source, public, no secret;
90
+ comm-central OAuth2Providers.sys.mjs). It registered the loopback
91
+ 127.0.0.1 redirect on ANY port, so we reuse the same http://127.0.0.1
92
+ address as Google -- the person copies it from the bar. (GNOME Online
93
+ Accounts' Graph client, b155a604-..., registered only a custom-scheme
94
+ goa-oauth2:// redirect a browser cannot surface, so we left it.) */
83
95
  thunderbird: {
84
96
  clientId: '9e5f94bc-e8a4-4e73-b8be-63364c29d753',
85
97
  clientSecret: null,
@@ -126,6 +138,22 @@ export function scopeFor(name, kinds = ['mail']) {
126
138
  return [...new Set(parts)].join(' ');
127
139
  }
128
140
 
141
+ /* Which kinds a granted scope string actually covers. A provider may grant fewer
142
+ scopes than asked (the person unticks one on the consent screen); the token's
143
+ `scope` field says what was allowed, so we never have to guess. A kind counts as
144
+ granted when the first (primary) scope token of its request appears in the
145
+ granted string, matched case-insensitively -- providers echo scopes back in
146
+ their own casing and URL form (Microsoft returns
147
+ `https://graph.microsoft.com/Calendars.ReadWrite` for a requested
148
+ `calendars.readwrite`). Returns [] when the scope is unknown, so a caller can
149
+ fall back to trusting what it asked for. */
150
+ export function kindsGranted(name, granted = '') {
151
+ const p = provider(name);
152
+ const g = String(granted).toLowerCase();
153
+ if (!g) return [];
154
+ return Object.keys(p.scopes).filter((k) => g.includes(p.scopes[k].split(/\s+/)[0].toLowerCase()));
155
+ }
156
+
129
157
  /* The URL the person's browser opens to sign in and allow. `redirectUri` is the
130
158
  loopback the provider sends the code back to (http://127.0.0.1:PORT). */
131
159
  export function consentUrl(name, { clientId, redirectUri, scope, state, codeChallenge, loginHint } = {}) {
package/server/setup.mjs CHANGED
@@ -338,6 +338,18 @@ export class Setup {
338
338
  if (!links.some((x) => x.from === l.from && x.to === to)) links.push({ from: l.from, to, rights: l.rights, pending: true, ...(l.autoSend ? { autoSend: l.autoSend } : {}) });
339
339
  }
340
340
  }
341
+ /* The owner's asset groups: one node per group, and each grouped asset
342
+ tagged with its group. The page can then FOLD a group to a single node
343
+ whose links are the union of its members' -- here we give the parts
344
+ (the members, their real links, the group nodes); the page does the
345
+ folding so the map declutters without losing the truth. */
346
+ const nodeById = new Map(nodes.map((n) => [n.id, n]));
347
+ for (const g of p.groups?.list?.() ?? []) {
348
+ const members = (g.members ?? []).filter((m) => nodeById.has(m));
349
+ if (members.length === 0) continue;
350
+ for (const m of members) nodeById.get(m).group = `group:${g.id}`;
351
+ nodes.push({ id: `group:${g.id}`, kind: 'group', name: g.label, sub: `${members.length} asset${members.length === 1 ? '' : 's'}`, members });
352
+ }
341
353
  const known = new Set(nodes.map((n) => n.id));
342
354
  return { nodes, links: links.filter((l) => known.has(l.from) && known.has(l.to)) };
343
355
  }
package/server/vm.mjs CHANGED
@@ -52,7 +52,7 @@ export function runner(prefix) {
52
52
  }
53
53
 
54
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']);
55
+ const CHANGES = new Set(['launch', 'clone', 'start', 'stop', 'suspend', 'kill', 'delete', 'purge', 'set', 'rename', 'restore', 'snapshot', 'revive', 'reclaim']);
56
56
  export const STATES_FRESH_MS = 3000;
57
57
  /* The VM manager did not say what a machine is in: not an answer about the machine. */
58
58
  export class VmUnknown extends Error {
@@ -181,5 +181,8 @@ export class Vms {
181
181
  return { memoryMb: mb === undefined ? undefined : Math.round(mb), diskGb: disk === undefined ? undefined : Math.round(disk / 1024), cpus };
182
182
  }
183
183
  suspend(conversation) { return this.run(['vm', 'suspend', vmName(conversation)], { timeoutMs: 300_000 }); }
184
+ /* Free the RAM of a machine that is asleep but whose qemu still holds it (a
185
+ suspend that did not end the process): wake+resleep, then a clean stop. */
186
+ reclaim(conversation) { return this.run(['vm', 'reclaim', vmName(conversation)], { timeoutMs: 300_000 }); }
184
187
  remove(conversation) { return this.run(['vm', 'delete', vmName(conversation)], { timeoutMs: 300_000 }); }
185
188
  }
package/web/app.js CHANGED
@@ -2007,7 +2007,7 @@
2007
2007
  }
2008
2008
  /* A chapter that holds something asking for the person -- a callout, or a state said as a warning or a
2009
2009
  fault -- wears a dot on its title, folded or not: one look at Settings says where to go. */
2010
- const asksForYou = (el2) => [...el2.querySelectorAll('.callout, .status-line[data-tone="warn"], .status-line[data-tone="bad"]')]
2010
+ const asksForYou = (el2) => [...el2.querySelectorAll('.callout:not([data-tone="ok"]), .status-line[data-tone="warn"], .status-line[data-tone="bad"]')]
2011
2011
  .some((x) => !x.closest('[hidden]') && x.textContent.trim());
2012
2012
  let marking;
2013
2013
  const markAttention = () => { clearTimeout(marking); marking = setTimeout(() => {
@@ -3815,7 +3815,16 @@
3815
3815
  for (const r of p) {
3816
3816
  r.sending = true; paint();
3817
3817
  try {
3818
- const sent = await post(`${API}/git/${r.name}/push`, { head: r.out.head, target: r.out.target, ...(r.out.guards?.confirm ? { sure: true } : {}) });
3818
+ /* The push runs in the background: the first request starts it, and
3819
+ while it says "sending" the page asks again (join) until it ends --
3820
+ a long push never looks like a failure or a restart. */
3821
+ let sent;
3822
+ for (let first = true; ; first = false) {
3823
+ sent = await post(`${API}/git/${r.name}/push`, first
3824
+ ? { head: r.out.head, target: r.out.target, ...(r.out.guards?.confirm ? { sure: true } : {}) }
3825
+ : { head: r.out.head, target: r.out.target, join: true });
3826
+ if (sent?.status !== 'sending') break;
3827
+ }
3819
3828
  r.sent = { ok: true, text: sent.already ? `✓ Already in ${sent.branch}` : sent.commits > 0 ? `✓ Sent to ${sent.branch}` : `✓ Made ${sent.branch}` };
3820
3829
  } catch (error) { r.sent = { ok: false, text: /^Not sent/.test(error.message) ? error.message : `Not sent: ${error.message}` }; }
3821
3830
  r.sending = false; paint();
@@ -4153,6 +4162,32 @@
4153
4162
  if (chosen.target) {
4154
4163
  const t = chosen.target;
4155
4164
  detail.append(el('p', 'hint', ['live', connexionSub(t.kind), t.config?.user].filter(Boolean).join(' · ')));
4165
+ /* The account's real permissions, read from the token (server-side) --
4166
+ shown here so they can be checked at any time, not only at connection.
4167
+ "Re-check" reads them live, to catch a permission removed since. */
4168
+ if (['google', 'microsoft'].includes(t.config?.provider)) {
4169
+ const KINDS3 = ['mail', 'calendar', 'contacts'];
4170
+ const perms = el('div', 'as-perms');
4171
+ detail.append(perms);
4172
+ const draw = (authorized) => {
4173
+ perms.replaceChildren();
4174
+ if (Array.isArray(authorized)) {
4175
+ const line = el('p', 'hint');
4176
+ line.append(el('b', '', 'Permissions: '));
4177
+ line.append(document.createTextNode(KINDS3.map((k) => `${k} ${authorized.includes(k) ? '✓' : '✗'}`).join(' ')));
4178
+ perms.append(line);
4179
+ } else { perms.append(el('p', 'hint', 'Permissions not checked yet.')); }
4180
+ const btn = el('button', '', Array.isArray(authorized) ? 'Re-check' : 'Check permissions');
4181
+ btn.type = 'button';
4182
+ btn.addEventListener('click', async () => {
4183
+ btn.disabled = true; btn.textContent = 'Checking…';
4184
+ try { const r = await post(`${API}/accounts/verify`, { id: t.id }); draw(r.authorized); }
4185
+ catch (e) { perms.append(el('p', 'error', e.message)); btn.disabled = false; btn.textContent = 'Re-check'; }
4186
+ });
4187
+ perms.append(btn);
4188
+ };
4189
+ draw(Array.isArray(t.config?.authorizedKinds) ? t.config.authorizedKinds : null);
4190
+ }
4156
4191
  if (chosen.siblings?.length) {
4157
4192
  const a = el('p', 'as-assoc hint');
4158
4193
  a.append(el('b', '', 'Linked'), document.createTextNode(` to the same account: ${chosen.siblings.join(', ')}. They share the account's token (kept on the server); rights are given separately.`));
@@ -5030,7 +5065,7 @@
5030
5065
  const backFailed = /did not come back either/.test(last?.why ?? '');
5031
5066
  const news = !running && last && last.result !== 'done' ? (last.result === 'rolled-back' ? (backFailed ? `${last.to} did not start on this server, and putting ${last.from} back did not work either: ${last.why}` : `${last.to} did not start on this server, so ${last.from} was put back. ${last.from} runs normally.`) : `${last.action === 'back' ? 'Going back to' : 'The update to'} ${last.to} failed: ${last.why ?? ''}`)
5032
5067
  : !running && u.refused && (!last || u.refused.at > last.at) && !/is not newer than/.test(u.refused.why ?? '') ? `Not done: ${u.refused.why}` : '';
5033
- $('updates-news').textContent = news.trim(); $('updates-news').hidden = !news;
5068
+ $('updates-news').textContent = news.trim(); $('updates-news').hidden = !news; $('updates-news').dataset.tone = news ? 'warn' : 'ok';
5034
5069
  if (![$('updates-mode'), $('updates-from'), $('updates-to'), $('updates-channel')].includes(document.activeElement)) {
5035
5070
  $('updates-mode').value = u.mode; $('updates-channel').value = u.channel;
5036
5071
  [$('updates-from').value, $('updates-to').value] = u.window.split('-');
@@ -5077,7 +5112,7 @@
5077
5112
  await paintUpdates();
5078
5113
  /* The answer to the click, said next to it. */
5079
5114
  const u = lastUpdates;
5080
- if (!failed && u && !u.checkError) { $('updates-news').textContent = u.available ? `${u.available} is out.` : `No new version: ${u.version} is the latest.`; $('updates-news').hidden = false; }
5115
+ if (!failed && u && !u.checkError) { $('updates-news').textContent = u.available ? `${u.available} is out.` : `No new version: ${u.version} is the latest.`; $('updates-news').hidden = false; $('updates-news').dataset.tone = u.available ? 'warn' : 'ok'; }
5081
5116
  });
5082
5117
  async function applyUpdate() {
5083
5118
  updatesError();
@@ -6166,24 +6201,27 @@
6166
6201
  a live Connexion (dynamic connector, token kept on the server): this jumps
6167
6202
  straight to adding one. */
6168
6203
  const MAILBOX_PROVIDER = { google: 'Google', microsoft: 'Microsoft' };
6204
+ /* Which kinds each provider can be connected for (from the server). */
6205
+ let accountSupported = { google: ['mail', 'calendar', 'contacts'], microsoft: ['mail'] };
6169
6206
  $('mailbox-to-connexion').addEventListener('click', () => { assetsAdding = 'connexion'; void paintAssets(); });
6170
6207
  /* CONNECT AN ACCOUNT (Connexions): a live link through Tether. The person signs
6171
6208
  in in their own browser; the token is kept on the server, never in a machine.
6172
- Google covers mail+calendar+contacts in one go; Microsoft, mail only here. */
6209
+ Both cover mail+calendar+contacts in one go, each landing on the same
6210
+ copy-pastable http://127.0.0.1 address. */
6173
6211
  const setConnexionProvider = (provider) => {
6174
6212
  const form = $('connexion-new');
6175
6213
  form.dataset.provider = provider;
6176
6214
  for (const b of $('connexion-provider').querySelectorAll('button')) b.setAttribute('aria-pressed', String(b.dataset.provider === provider));
6177
- const google = provider === 'google';
6178
- for (const id of ['connexion-calendar', 'connexion-contacts']) { const c = $(id); if (!google) c.checked = false; c.disabled = !google; }
6179
- $('connexion-calendar-label').classList.toggle('off', !google);
6180
- $('connexion-contacts-label').classList.toggle('off', !google);
6215
+ const kinds = accountSupported[provider] ?? ['mail'];
6216
+ for (const [id, k] of [['connexion-calendar', 'calendar'], ['connexion-contacts', 'contacts']]) { const c = $(id); const ok = kinds.includes(k); if (!ok) c.checked = false; c.disabled = !ok; $(`${id}-label`).classList.toggle('off', !ok); }
6181
6217
  $('connexion-paste').hidden = true;
6182
6218
  $('connexion-error').hidden = true;
6183
6219
  const who = MAILBOX_PROVIDER[provider];
6184
- $('connexion-notice').textContent = google
6185
- ? "Clavarium signs in with GNOME Online Accounts' app — that is what Google sees. Mail, calendar and contacts can be connected together."
6186
- : 'Clavarium signs in as Thunderbird — that is what Microsoft sees. Mail for now; calendar and contacts are coming.';
6220
+ const all = kinds.includes('calendar') && kinds.includes('contacts');
6221
+ /* Say plainly whose app Clavarium borrows (it is what the provider sees),
6222
+ and -- before anyone clicks -- that allowing lands on a page that will
6223
+ not load, which is expected: the address is what to copy back here. */
6224
+ $('connexion-notice').textContent = `Clavarium signs in as Thunderbird's app — that is what ${who} sees.${all ? ' Mail, calendar and contacts together.' : ''} After you allow, your browser lands on an error page — that is normal, nothing is running at that address. Copy the whole address from the bar and paste it below.`;
6187
6225
  $('connexion-open').textContent = `Open the ${who} sign-in page`;
6188
6226
  };
6189
6227
  for (const b of $('connexion-provider').querySelectorAll('button')) b.addEventListener('click', () => setConnexionProvider(b.dataset.provider));
@@ -6206,14 +6244,27 @@
6206
6244
  const btn = $('connexion-connect'); const was = btn.textContent; btn.disabled = true; btn.textContent = 'Connecting...';
6207
6245
  try {
6208
6246
  const made = await post(`${API}/accounts/connect`, { redirected: $('connexion-code').value.trim() });
6209
- if (made?.targets?.[0]) assetOpen = `connexion:${made.targets[0].id}`;
6210
- assetsAdding = '';
6211
- $('connexion-new').reset(); setConnexionProvider('google');
6247
+ const denied = Array.isArray(made?.denied) ? made.denied : [];
6248
+ if (denied.length) {
6249
+ /* A partial grant: say plainly what was allowed and what was not,
6250
+ from the token itself, and keep the form so they can allow the rest. */
6251
+ const word = (k) => ({ mail: 'mail', calendar: 'calendar', contacts: 'contacts' }[k] || k);
6252
+ const ok = (made.authorized || []).map(word);
6253
+ const no = denied.map(word);
6254
+ $('connexion-error').textContent = `${ok.length ? `Connected for ${ok.join(', ')}. ` : ''}Not allowed: ${no.join(', ')} — connect again and allow ${no.length > 1 ? 'them' : 'it'} on the provider's screen.`;
6255
+ $('connexion-error').hidden = false;
6256
+ $('connexion-code').value = ''; $('connexion-paste').hidden = true;
6257
+ } else {
6258
+ if (made?.targets?.[0]) assetOpen = `connexion:${made.targets[0].id}`;
6259
+ assetsAdding = '';
6260
+ $('connexion-new').reset(); setConnexionProvider('google');
6261
+ }
6212
6262
  } catch (error) { $('connexion-error').textContent = error.message; $('connexion-error').hidden = false; }
6213
6263
  btn.disabled = false; btn.textContent = was;
6214
6264
  await paintAssets();
6215
6265
  });
6216
6266
  setConnexionProvider('google');
6267
+ getJson('/accounts', null).then((d) => { if (d?.supported) { accountSupported = d.supported; setConnexionProvider($('connexion-new').dataset.provider || 'google'); } });
6217
6268
  $('list-new').addEventListener('submit', async (event) => {
6218
6269
  event.preventDefault();
6219
6270
  $('assets-error').hidden = true;
package/web/index.html CHANGED
@@ -548,7 +548,7 @@
548
548
  <div class="row"><button type="button" id="connexion-open" class="primary">Open the sign-in page</button></div>
549
549
  <div id="connexion-paste" hidden>
550
550
  <label for="connexion-code">After you allow, the page will not load — copy its full address and paste it here</label>
551
- <div class="row"><input id="connexion-code" spellcheck="false" autocapitalize="off" placeholder="http://127.0.0.1..."><button type="button" id="connexion-connect" class="primary">Connect</button></div>
551
+ <div class="row"><input id="connexion-code" spellcheck="false" autocapitalize="off" placeholder="Paste the whole address from the bar"><button type="button" id="connexion-connect" class="primary">Connect</button></div>
552
552
  </div>
553
553
  <p id="connexion-error" class="error" role="alert" hidden></p>
554
554
  </form>
package/web/links.js CHANGED
@@ -24,12 +24,12 @@
24
24
  (() => {
25
25
  const SVG = 'http://www.w3.org/2000/svg';
26
26
  /* Each kind's icon, from the set of the chat (Lucide, see icons.js): the same drawing on every screen, whatever its fonts. */
27
- const KIND_ICON = { device: 'smartphone', conversation: 'square-terminal', folder: 'folder', git: 'git-branch', mailbox: 'mail', agenda: 'calendar', contacts: 'users', secret: 'key-round' };
27
+ const KIND_ICON = { device: 'smartphone', conversation: 'square-terminal', folder: 'folder', git: 'git-branch', mailbox: 'mail', agenda: 'calendar', contacts: 'users', secret: 'key-round', group: 'layers' };
28
28
  /* An icon of that set, or, until it is there, nothing in its place. */
29
29
  const ic = (name, cls = 'lk-svg') => window.clavariumIcons?.icon(name, cls) ?? null;
30
30
  const kindIcon = (kind) => h('span', { class: 'lk-ic', 'aria-hidden': 'true' }, ic(KIND_ICON[kind]));
31
- const KIND_WORD = { device: 'device', conversation: 'conversation', folder: 'folder', git: 'repository', mailbox: 'mailbox', agenda: 'calendar', contacts: 'address book', secret: 'secret' };
32
- const COLUMN = { device: 'device', conversation: 'conversation', folder: 'asset', git: 'asset', mailbox: 'asset', agenda: 'asset', contacts: 'asset', secret: 'asset' };
31
+ const KIND_WORD = { device: 'device', conversation: 'conversation', folder: 'folder', git: 'repository', mailbox: 'mailbox', agenda: 'calendar', contacts: 'address book', secret: 'secret', group: 'group' };
32
+ const COLUMN = { device: 'device', conversation: 'conversation', folder: 'asset', git: 'asset', mailbox: 'asset', agenda: 'asset', contacts: 'asset', secret: 'asset', group: 'asset' };
33
33
  const TITLES = { device: 'Devices', conversation: 'Conversations', asset: 'Assets' };
34
34
  const VIEWS = {
35
35
  devices: { cols: [['device'], ['conversation', 'asset']], sources: ['device'] },
@@ -69,6 +69,12 @@
69
69
  let allLines = true;
70
70
  try { allLines = localStorage.getItem('clavarium-links-all') !== '0'; } catch { /* none kept */ }
71
71
  let picked = null; let pinned = null; let focus = null; let drag = null; let pop = null; let popLink = null; let drawnMany = false;
72
+ /* The graph as the server sends it; `graph` below is the folded view of it.
73
+ A group folds to one node by default; the owner opens the ones they want.
74
+ Which are open is kept per device. */
75
+ let rawGraph = { nodes: [], links: [], flows: [] };
76
+ const expanded = new Set((() => { try { const v = JSON.parse(localStorage.getItem('clavarium-links-open') ?? '[]'); return Array.isArray(v) ? v : []; } catch { return []; } })());
77
+ const keepExpanded = () => { try { localStorage.setItem('clavarium-links-open', JSON.stringify([...expanded])); } catch { /* none kept */ } };
72
78
  /* A box is shown only if its column's filter is empty or its name holds what was typed: so a
73
79
  crowded map (many assets) is narrowed to a few boxes, their links with them. The layout is
74
80
  kept while typing (no reorder), and a filter cleared brings everything back. */
@@ -95,13 +101,37 @@
95
101
  const inView = (n) => VIEWS[view].cols.flat().includes(COLUMN[n.kind]);
96
102
  const shown = (l) => VIEWS[view].sources.includes(node(l.from)?.kind) && inView(node(l.to));
97
103
 
98
- async function load() {
99
- const r = await fetch(`${env.API()}/flows`);
100
- graph = r.ok ? await r.json() : { nodes: [], links: [], flows: [] };
104
+ /* The graph as drawn: a folded group becomes a single node, and its members'
105
+ links move onto it (deduped, rights merged); an opened group shows its
106
+ members as before. The server gives the parts; the folding is here. */
107
+ const mergeRights = (a = '', b = '') => [...'rwx'].filter((c) => a.includes(c) || b.includes(c)).join('') || a || b;
108
+ function foldedGraph(raw) {
109
+ const toGroup = new Map();
110
+ for (const n of raw.nodes) if (n.kind === 'group' && !expanded.has(n.id)) for (const m of n.members ?? []) toGroup.set(m, n.id);
111
+ const nodes = raw.nodes.filter((n) => !toGroup.has(n.id));
112
+ const at = (id) => toGroup.get(id) ?? id;
113
+ const merged = new Map();
114
+ for (const l of raw.links) {
115
+ const from = at(l.from); const to = at(l.to);
116
+ if (from === to) continue;
117
+ const key = `${from}\u0000${to}`;
118
+ const prev = merged.get(key);
119
+ merged.set(key, prev ? { ...prev, rights: mergeRights(prev.rights, l.rights), pending: Boolean(prev.pending && l.pending) } : { ...l, from, to });
120
+ }
121
+ return { nodes, links: [...merged.values()], flows: raw.flows ?? [] };
122
+ }
123
+ function applyFold() {
124
+ graph = foldedGraph(rawGraph);
101
125
  byId = new Map(graph.nodes.map((n) => [n.id, n]));
102
126
  if (pinned && !byId.has(pinned)) pinned = null;
103
127
  if (picked && !byId.has(picked.id)) picked = null; else if (picked) picked = byId.get(picked.id);
104
128
  }
129
+ function toggleGroup(id) { if (expanded.has(id)) expanded.delete(id); else expanded.add(id); keepExpanded(); laidOut = null; applyFold(); paint(); }
130
+ async function load() {
131
+ const r = await fetch(`${env.API()}/flows`);
132
+ rawGraph = r.ok ? await r.json() : { nodes: [], links: [], flows: [] };
133
+ applyFold();
134
+ }
105
135
  const err = (text) => { const e = $('links-error'); e.textContent = text ?? ''; e.hidden = !text; };
106
136
 
107
137
  /* ---------- the requests: those of the other screens ---------- */
@@ -161,7 +191,7 @@
161
191
  times, puts each box at the average place of what it is linked to; the order
162
192
  that crossed least is kept. What is linked to nothing goes last, by name. */
163
193
  function layout() {
164
- const ASSETS = ['folder', 'git', 'mailbox', 'agenda', 'contacts', 'secret'];
194
+ const ASSETS = ['group', 'folder', 'git', 'mailbox', 'agenda', 'contacts', 'secret'];
165
195
  const base = (k) => graph.nodes.filter((n) => COLUMN[n.kind] === k).sort((a, b) => (ASSETS.indexOf(a.kind) - ASSETS.indexOf(b.kind)) || a.name.localeCompare(b.name));
166
196
  let cols = VIEWS[view].cols.map((ks) => ks.map(base));
167
197
  const colOf = new Map(); cols.forEach((gs, ci) => gs.flat().forEach((n) => colOf.set(n.id, ci)));
@@ -242,8 +272,9 @@
242
272
  const e = h('div', { class: `lk-node lk-c-${COLUMN[n.kind]}${n.pending ? ' pending' : ''}`, 'data-id': n.id, 'data-kind': n.kind, tabindex: 0, role: 'button', title: `${n.name} · ${n.sub}`, 'aria-label': `${n.name}, ${n.sub}, ${cnt} link${cnt === 1 ? '' : 's'}` },
243
273
  kindIcon(n.kind),
244
274
  h('span', { class: 'lk-tx' }, h('span', { class: 'lk-nm', text: n.name })),
275
+ n.kind === 'group' && h('span', { class: 'lk-fold', text: expanded.has(n.id) ? '▾' : '▸', 'aria-hidden': 'true' }),
245
276
  state && h('span', { class: 'lk-st', 'data-state': state, 'aria-hidden': 'true' }),
246
- h('span', { class: 'lk-cnt', text: String(cnt), title: `${cnt} link${cnt === 1 ? '' : 's'}` }));
277
+ n.kind !== 'group' && h('span', { class: 'lk-cnt', text: String(cnt), title: `${cnt} link${cnt === 1 ? '' : 's'}` }));
247
278
  if (VIEWS[view].sources.includes(n.kind) && !n.pending) {
248
279
  const dot = h('span', { class: 'lk-handle', title: 'Drag to what it gets', 'aria-hidden': 'true' });
249
280
  dot.addEventListener('pointerdown', (ev) => startDrag(ev, n));
@@ -372,6 +403,8 @@
372
403
  /* A tap shows only what concerns that box; tapped again, everything comes back.
373
404
  A box that gives is also ready to be linked: tap a dashed box to link it. */
374
405
  function tap(n) {
406
+ /* A group folds/unfolds on a tap -- it is not something to give or pair. */
407
+ if (n.kind === 'group') { toggleGroup(n.id); return; }
375
408
  if (picked && picked.id !== n.id && allowed(picked, n)) { void link(picked, n); return; }
376
409
  const again = pinned === n.id;
377
410
  pinned = again ? null : n.id;
package/web/style.css CHANGED
@@ -59,6 +59,8 @@ button:focus-visible, input:focus-visible { outline: 2px solid var(--brass); out
59
59
  .row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
60
60
  .hint { color: var(--ink2); font-size: .75rem; margin: 0; }
61
61
  .error { color: var(--danger); font-size: .8125rem; margin: 0; }
62
+ .as-perms { display: flex; flex-direction: column; align-items: flex-start; gap: 6px; margin: 8px 0; }
63
+ .as-perms button { font-size: .75rem; padding: 4px 10px; }
62
64
  #room { grid-column: 2; grid-row: 1 / span 2; min-width: 0; min-height: 0; display: flex; flex-direction: column; }
63
65
  /* The bar wraps onto a second line rather than squeeze the name away or break a button's label in two. */
64
66
  header { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 8px; padding: 6px 10px; background: var(--bar); border-bottom: 1px solid var(--line); min-height: 44px; }
@@ -604,6 +606,10 @@ footer button[data-keys="backspace"] { display: none; }
604
606
  .lk-node { position: relative; flex: none; display: flex; align-items: center; gap: 8px; border: 1.5px solid var(--line); border-radius: 10px; padding: 5px 10px 5px 6px; background: var(--panel); cursor: pointer; user-select: none; min-width: 0; }
605
607
  .lk-node .lk-tx { flex: 1; }
606
608
  .lk-node .lk-nm { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
609
+ /* A group folds to one node: a brass accent and a chevron say it opens. */
610
+ .lk-node[data-kind="group"] { border-color: color-mix(in srgb, var(--brass) 55%, var(--line)); border-style: solid; }
611
+ .lk-node[data-kind="group"] .lk-ic { background: rgba(210, 169, 78, .18); color: var(--brass-ink); }
612
+ .lk-node[data-kind="group"] .lk-fold { color: var(--ink2); font-size: .72rem; margin-left: 2px; flex: none; }
607
613
  /* What the icon cannot say: a conversation's chat on, or one not ready. */
608
614
  .lk-st { width: 8px; height: 8px; border-radius: 50%; flex: none; margin-right: 6px; }
609
615
  .lk-st[data-state="chat"] { background: var(--k-chat); }
@@ -1043,7 +1049,10 @@ button.inline:hover { color: var(--brass-ink); }
1043
1049
  #updates { display: grid; gap: 10px; outline: none; }
1044
1050
  .updates-head { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 12px; }
1045
1051
  #updates-state { color: var(--ink2); font-size: .8125rem; flex: 1 1 10rem; min-width: 0; overflow-wrap: anywhere; }
1046
- .updates-news { margin: 0; font-size: .8125rem; padding: 8px 10px; border-radius: 8px; border: 1px solid var(--warn); background: var(--bar); overflow-wrap: anywhere; }
1052
+ .updates-news { margin: 0; font-size: .8125rem; padding: 8px 10px; border-radius: 8px; border: 1px solid var(--line); background: var(--bar); overflow-wrap: anywhere; }
1053
+ /* Amber only when something asks for a look (an update is out, one failed); up to date is neutral. */
1054
+ .updates-news[data-tone="warn"] { border-color: var(--warn); }
1055
+ .updates-news[data-tone="bad"] { border-color: var(--danger); }
1047
1056
  .updates-grid { display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: center; gap: 8px 14px; max-width: 30rem; }
1048
1057
  .updates-grid select, .updates-window input { min-height: 40px; font: .875rem var(--sans); color: var(--ink); background-color: var(--bg); border: 1px solid var(--line); border-radius: 7px; padding: 6px 8px; max-width: 100%; }
1049
1058
  .updates-window { display: inline-flex; align-items: center; flex-wrap: wrap; gap: 6px; color: var(--ink2); font-size: .8125rem; }
@@ -1122,8 +1131,10 @@ header .ic, #folders .ic { width: 18px; height: 18px; fill: none; stroke: curren
1122
1131
  .as-group-name { display: flex; align-items: center; gap: 6px; flex: 1 1 auto; justify-content: flex-start; text-align: left; background: transparent; border: 1px solid transparent; border-radius: 8px; padding: 3px 6px; }
1123
1132
  .as-group-name:hover { border-color: var(--line); }
1124
1133
  .as-group-name[aria-current="true"] { background: var(--panel); border-color: var(--line); }
1125
- .as-gear { flex: 0 0 auto; width: 30px; height: 30px; min-width: 0 !important; min-height: 0 !important; padding: 0; border-radius: 7px; border: 1px solid transparent; background: transparent; color: var(--ink2); font-size: 1rem; opacity: 0; }
1126
- .as-group-head:hover .as-gear, .as-group-name[aria-current="true"] + .as-gear { opacity: 1; }
1134
+ .as-gear { flex: 0 0 auto; width: 30px; height: 30px; min-width: 0 !important; min-height: 0 !important; padding: 0; border-radius: 7px; border: 1px solid transparent; background: transparent; color: var(--ink2); font-size: 1rem; opacity: 1; }
1135
+ /* On a mouse, keep it quiet until the group is hovered or open; on touch (no
1136
+ hover) it must stay visible, or it can never be reached. */
1137
+ @media (hover: hover) { .as-gear { opacity: 0; } .as-group-head:hover .as-gear, .as-group-name[aria-current="true"] + .as-gear { opacity: 1; } }
1127
1138
  .as-gear:hover { border-color: var(--line); color: var(--ink); }
1128
1139
  .as-group-members { display: flex; flex-direction: column; gap: 2px; }
1129
1140
  /* Give the group: a block per conversation, a row per asset at its own level. */