sigelo-contact 0.1.21 → 0.1.22

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.
Files changed (69) hide show
  1. package/GROUPS-REFERENCE.md +165 -0
  2. package/GROUPS.md +53 -0
  3. package/LICENSE +235 -21
  4. package/README.md +4 -5
  5. package/call.mjs +89 -28
  6. package/carrier.mjs +230 -51
  7. package/control.mjs +2 -2
  8. package/create.mjs +2 -2
  9. package/device.mjs +2 -2
  10. package/enrol.mjs +2 -2
  11. package/envelope.mjs +6 -6
  12. package/file.mjs +2 -2
  13. package/fixtures/carrier-v0.json +1 -1
  14. package/fixtures/envelope-v0.json +1 -1
  15. package/fixtures/group-v2.json +2999 -0
  16. package/gen-carrier.mjs +2 -2
  17. package/gen-device.mjs +1 -1
  18. package/gen-envelope.mjs +2 -2
  19. package/gen-group2.mjs +291 -0
  20. package/gen-invite.mjs +2 -2
  21. package/gen-short.mjs +1 -1
  22. package/group.mjs +116 -17
  23. package/group2.mjs +1534 -0
  24. package/home-wire.mjs +812 -0
  25. package/invite.mjs +3 -3
  26. package/kdf.mjs +2 -2
  27. package/kin.mjs +62 -0
  28. package/link.mjs +6 -6
  29. package/package.json +25 -8
  30. package/page.mjs +507 -57
  31. package/photo.mjs +2 -2
  32. package/platform-node.mjs +6 -6
  33. package/prekeys.mjs +3 -3
  34. package/public.mjs +2 -2
  35. package/qr-decode.mjs +1 -1
  36. package/qr.mjs +2 -2
  37. package/relays.mjs +2 -2
  38. package/restore.mjs +2 -2
  39. package/rtc-web.mjs +3 -3
  40. package/short.mjs +2 -2
  41. package/store.mjs +22 -9
  42. package/test-carrier.mjs +32 -11
  43. package/test-device.mjs +3 -3
  44. package/test-enrol.mjs +9 -4
  45. package/test-envelope.mjs +2 -2
  46. package/test-file.mjs +2 -2
  47. package/test-group-move.mjs +225 -0
  48. package/test-group.mjs +1 -1
  49. package/test-group2.mjs +202 -0
  50. package/test-home.mjs +225 -0
  51. package/test-invite.mjs +1 -1
  52. package/test-link.mjs +3 -3
  53. package/test-platform.mjs +2 -2
  54. package/test-presence.mjs +2 -2
  55. package/test-push.mjs +5 -5
  56. package/test-relay-lane.mjs +3 -3
  57. package/test-short.mjs +1 -1
  58. package/test-tier.mjs +8 -2
  59. package/test-transfer-web.mjs +7 -7
  60. package/test-transfer.mjs +6 -6
  61. package/test-voice.mjs +2 -2
  62. package/test-ws.mjs +1 -1
  63. package/transfer-engine.mjs +6 -6
  64. package/transfer-node.mjs +5 -5
  65. package/transfer-web.mjs +3 -3
  66. package/transfer.mjs +8 -8
  67. package/voice-web.mjs +2 -2
  68. package/voice.mjs +7 -3
  69. package/words-lock.mjs +2 -2
package/page.mjs CHANGED
@@ -1,4 +1,4 @@
1
- // SPDX-License-Identifier: MIT
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
2
  // The page's routes over one carrier (apps/agent/UI-API.md), shared by `sigelo-agent ui`
3
3
  // (apps/agent/sigelo-agent-ui.ts: HTTP on 127.0.0.1) and the self-contained app (apps/web/router.mjs:
4
4
  // in the page). One route table, one JSON: what is the same everywhere is here; what one host has
@@ -22,15 +22,20 @@
22
22
  // ([] where there is none), seat() → the seat or null, deviceRound() → { gave? } after each drain
23
23
  // (or none), note(line), defer(fn) (setImmediate on Node), every(fn, ms) → a timer, hidden({ did, name })
24
24
  // → true for what the page never shows nor names (the computer's relay controls: their contacts, their
25
- // pairing, their codes waiting; design/apps.md §6.3), controls: { pending() → [{name, scope, words}],
25
+ // pairing, their codes waiting; apps/agent/UI-API.md "Remote"), controls: { pending() → [{name, scope, words}],
26
26
  // confirm(name, match) → whether one was pending } (relay controls whose four words wait: the
27
27
  // Controls card; routes in no remote scope, so never asked over the relay or the LAN).
28
28
  //
29
- // Groups (apps/agent/GROUPS.md, design/groups.md §5): groups: group.mjs (the module) and groupsFile
29
+ // Groups (apps/agent/GROUPS.md): groups: group.mjs (the module) and groupsFile
30
30
  // (groupsPath of the identity). Each drain hands the carrier's group messages to group.mjs handle(), here
31
31
  // in code: without it the page never takes a roster, carries a copy on or files a message. The page's
32
32
  // own marks in data: gread (gid → the newest item shown: {mid, at}), gnotices (a stranger added, the
33
33
  // creator gone, a refusal: until dismissed). /api/groups/* (UI-API.md "Groups").
34
+ // Home groups (design/groups-build.md step 5): groups2: group2.mjs and groups2File (groups2Path of the identity). The
35
+ // carrier stays at their home relays (setHomes: push registered there too) and says `home` when it connects there or a
36
+ // row comes; the page then syncs them (group2.mjs sync, one at a time; a join waiting: every 5 s). Step 6: GET /api/groups
37
+ // lists them beside the groups (v: 2), the chat reads the groups file's history, and the shared routes (create without
38
+ // members, join by a code, any route naming a home group's gid) go to group2.mjs (UI-API.md "Home groups").
34
39
  //
35
40
  // Agents (ENROL.md, the app's main list): hooks.keeper, where the host has the operator's keeper root:
36
41
  // { read() → the keeper file as JSON (workers, …) | null, root(k) → { K, recovery } (K zeroed after use),
@@ -47,7 +52,7 @@
47
52
  // { name() → its name, call(method, path, body?) → { status, body } }. /api/keeper* go there; a limit is a
48
53
  // policy-change signed here with this identity (the computer relays it, POST /api/keeper/policy). None: elsewhere.
49
54
  //
50
- // Transfers (apps/agent/TRANSFER.md, design/transfer.md §10): hooks.transfers, where the host moves big
55
+ // Transfers (apps/agent/TRANSFER.md): hooks.transfers, where the host moves big
51
56
  // files ({ lib, identity, make(carrier, onEvent, { compared }) → its Engine; lib: transfer-node.mjs on a
52
57
  // computer (a file by its path), transfer-web.mjs's in the phone app (a file picked: doc), which also gives
53
58
  // pick(), photo({ keepLocation }), open(saved) and url(doc) }): the page owns the session, so its engine
@@ -58,18 +63,22 @@
58
63
  // voice.mjs) goes the same way, its fields as the message and the recording as the file, where the host records
59
64
  // (hooks.transfers.rec: write(rec, offset, bytes), keep(rec, name) → { doc } | { path }, read(saved) → bytes).
60
65
  //
61
- // Calls (UI-API.md "Calls", design/calls.md, call.mjs): one Line over this carrier, always; the media is the page's (ui.js's
66
+ // Calls (UI-API.md "Calls", call.mjs): one Line over this carrier, always; the media is the page's (ui.js's
62
67
  // Phone), which reaches it by /api/calls*. hooks.calls, where the host has a shell: { alert({on, id, did, name}) the ring
63
- // (the phone app: ringtone, vibration, a heads-up; the seam the push build wires to a full-screen ring), audio({on, id,
64
- // name}) the call's audio mode (CallService), speaker(on), mic(), micSettings() }. "Can call me" (decision 2026-11-17):
65
- // data.calls[did] true | false, else the default: off for a quiet contact, else data.settings.calls (default on).
68
+ // (the phone app: ringtone, vibration, a heads-up; the seam the push build wires to a full-screen ring; it may answer
69
+ // { busy }: another app's call, the Line answers busy), audio({on, id, name}) the call's audio mode (CallService),
70
+ // speaker(on), route(to?) the audio output (→ { current, available, held }), missed({did, name}) a missed call's
71
+ // notification at once (tag chat:<did>, as the page's poll raises it, which then replaces it: a page started by a push
72
+ // wake tells nothing at its first look), mic(), micSettings() }. "Can call me" (decision 2026-11-17):
73
+ // data.calls[did] true, else off (2026-11-27, the Owner: calls are switched on per contact, by hand; no default for all,
74
+ // and an old data.settings.calls is ignored).
66
75
  // A call's chat line is a history record { kind: in | out, label CALL_LABEL, text "Call · 3:12" | "Missed call" | …,
67
76
  // call: { id, state, secs } }; only a missed one counts as unread (a call taken or made here was seen).
68
- // "Always relay my media" (design/calls.md §6, UI-API.md "Settings"): data.settings.relay_media, per profile (default
77
+ // "Always relay my media" (UI-API.md "Settings"): data.settings.relay_media, per profile (default
69
78
  // off); SIGELO_ICE_POLICY=relay in the host's environment says the same. On: GET /api/calls/turn answers policy
70
79
  // "relay" and the transfer engine is given it (relayMedia): every WebRTC lane only through the relay's TURN.
71
80
  //
72
- // Proof of work (design/profiles.md §6): what the human starts here (the page's start, a code, an
81
+ // Proof of work: what the human starts here (the page's start, a code, an
73
82
  // answer, "Try now") passes the carrier's `started: 'user'`; past the day's three the route answers
74
83
  // 409 pow_confirm, and the same call with `pow_confirmed: true` goes on. The carrier's automatic
75
84
  // retries stay capped: state's me.pow_capped {relay, next} says when the next one is.
@@ -80,15 +89,18 @@
80
89
  // them), or a first one to a contact not known to (an earlier version takes it as a message once, then hears no more;
81
90
  // never to my own agents, which read none);
82
91
  // the first receipt from a contact is answered once (a 0 when receipts are off), so both sides know. data.seen: each
83
- // contact's {sent, told}. Chat defaults (data.settings): new_tier and new_presence, given to a contact at its pairing;
84
- // notify (all chats) and data.notify (a chat: contact DID or gid → false) for the notifications.
92
+ // contact's {sent, told}. Chat defaults (data.settings): new_tier and new_presence, given to a contact at its pairing.
93
+ // Alerts (Settings → Notifications, "Alert me about", 2026-11-27): data.settings.alerts all | people | none, read by the
94
+ // page's notifications and its banner alike; an older data.settings.notify maps (false → none, else all). A chat's
95
+ // Mute: data.notify (a contact DID or gid → false). A person is normal or muted: quiet is an agent's tier (trust); a
96
+ // person on quiet before is muted and filed friend, once (settlePeople, data.settings.people).
85
97
  //
86
- // The Wallet settings (UI-API.md "Wallet", design/ux1/notes.md "Decided"): per profile, in data.settings: wallet (the
98
+ // The Wallet settings (UI-API.md "Wallet"): per profile, in data.settings: wallet (the
87
99
  // switch, default off), prices (a local price, opt-in, default off) and currency (one of CURRENCIES). Read in state's
88
100
  // me.wallet by every form of the page. This page holds no wallet: GET /api/wallet answers where: "none", its other
89
101
  // wallet routes 409 wallet_none ("This phone has no wallet yet"); `sigelo-agent ui` answers them with the computer's.
90
102
  //
91
- // Pictures (UI-API.md "Pictures", design/ux1/notes.md "Decided"): store.readPicture(name) → bytes | null and
103
+ // Pictures (UI-API.md "Pictures"): store.readPicture(name) → bytes | null and
92
104
  // store.writePicture(name, bytes | null), the host's (beside the page's data, 0600, on a computer; the profile's storage
93
105
  // on the phone). data.pics: key → {type, rev, at} for 'me' (this identity's own), 'l:<did or gid>' (a local one for a
94
106
  // contact or a group: wins) and 't:<did>' (the one a contact sent). Mine travels as one more body inside the
@@ -110,9 +122,15 @@
110
122
  //
111
123
  // A hosted agent's settings (UI-API.md "Agent settings"; sigelo-agent-host.ts): HOST_CAPS_LABEL {fields: [{key, value,
112
124
  // options: [{value, label}], off?, next?}], note?}, sent only to a page whose receipts said host: true (carrier.mjs
113
- // host_peer); checked (capsOf: keys model, effort, permissionMode; others dropped), kept as data.host[did], never in the
125
+ // host_peer); checked (capsOf: keys model, effort, permissionMode; others dropped; commands [{name, args?, help}], the chat
126
+ // commands it takes, a malformed row dropped), kept as data.host[did], never in the
114
127
  // history; the contact's `host`. POST /api/host/set sends HOST_SET_LABEL {key, value} (a choice it offered) and marks it
115
128
  // next until the agent says again. A HOST_SET_LABEL that reaches a page: dropped (a page hosts nothing).
129
+ // The Session card (2026-11-28): the caps' `session` {folder, home, root, started, resumed, login: {state, account?, here},
130
+ // waits?} (sessionOf; malformed: dropped, the fields kept). POST /api/host/dirs, /api/host/session, /api/host/login send
131
+ // HOST_DIRS_LABEL {path, into?, id}, HOST_SESSION_LABEL {do, path?}, HOST_LOGIN_LABEL {do, code?}; the agent's answers on the
132
+ // same labels are kept beside its caps (host.dirs, host.session_ev, host.login_ev; checked by dirsOf, sessionEvOf,
133
+ // loginEvOf), never in the history; the code a person pastes is sent, never kept.
116
134
  //
117
135
  // The public invite (UI-API.md "Public invite"): a public code (sigelo-public/0, carrier.mjs invitePublic), PUB-…
118
136
  // with the four words and a link, for 1, 6 or 12 months, Pro only, kept in the contact store; each use a request to
@@ -197,7 +215,41 @@ export function promptOf(label, c) {
197
215
  return null;
198
216
  }
199
217
  export const HOST_CAPS_LABEL = 'sigelo-host-caps/0', HOST_SET_LABEL = 'sigelo-host-set/0';
218
+ export const HOST_DIRS_LABEL = 'sigelo-host-dirs/0', HOST_SESSION_LABEL = 'sigelo-host-session/0', HOST_LOGIN_LABEL = 'sigelo-host-login/0';
200
219
  const HOST_KEYS = new Set(['model', 'effort', 'permissionMode']);
220
+ const LOGIN_STATES = new Set(['signed_in', 'signed_out', 'unknown', 'signing_in']);
221
+ const isStr = (v, max) => typeof v === 'string' && v.length <= max;
222
+ const isObj = (c) => typeof c === 'object' && c !== null && !Array.isArray(c);
223
+ /** The caps' session (the Session card) → it, or null (malformed). */
224
+ export function sessionOf(s) {
225
+ if (!isObj(s) || !isStr(s.folder, 4096) || !isStr(s.home, 4096) || !isStr(s.root, 4096) || !Number.isSafeInteger(s.started) || s.started < 0 || typeof s.resumed !== 'boolean') return null;
226
+ const l = s.login;
227
+ if (!isObj(l) || !LOGIN_STATES.has(l.state) || typeof l.here !== 'boolean' || (l.account !== undefined && !isStr(l.account, 120)) || (s.waits !== undefined && s.waits !== 'new' && s.waits !== 'folder')) return null;
228
+ return { folder: s.folder, home: s.home, root: s.root, started: s.started, resumed: s.resumed, login: { state: l.state, ...(l.account !== undefined && { account: l.account }), here: l.here }, ...(s.waits !== undefined && { waits: s.waits }) };
229
+ }
230
+ /** A folder listing (HOST_DIRS_LABEL from the agent) → it, or null. */
231
+ export function dirsOf(c) {
232
+ if (!isObj(c) || (c.id !== undefined && !(isStr(c.id, 32) && /^[\w-]+$/.test(c.id))) || !isStr(c.root, 4096)) return null;
233
+ const id = c.id !== undefined ? { id: c.id } : {};
234
+ if (c.error !== undefined) return isStr(c.error, 40) && isStr(c.detail, 200) ? { ...id, root: c.root, error: c.error, detail: c.detail } : null;
235
+ if (!isStr(c.path, 4096) || !isStr(c.parent, 4096) || !Array.isArray(c.dirs) || c.dirs.length > 200 || !c.dirs.every((d) => isStr(d, 255) && d !== '' && !/[\\/]/.test(d))
236
+ || !Number.isSafeInteger(c.hidden) || c.hidden < 0 || !Number.isSafeInteger(c.more) || c.more < 0) return null;
237
+ return { ...id, path: c.path, parent: c.parent, root: c.root, dirs: [...c.dirs], hidden: c.hidden, more: c.more };
238
+ }
239
+ /** A session event (HOST_SESSION_LABEL from the agent: new, waiting, set, refused) → it, or null. */
240
+ export function sessionEvOf(c) {
241
+ if (!isObj(c) || !['new', 'waiting', 'set', 'refused'].includes(c.event) || (c.why !== undefined && !isStr(c.why, 16)) || (c.folder !== undefined && !isStr(c.folder, 4096))
242
+ || (c.started !== undefined && !(Number.isSafeInteger(c.started) && c.started >= 0)) || (c.reason !== undefined && !isStr(c.reason, 40)) || (c.detail !== undefined && !isStr(c.detail, 200))) return null;
243
+ return Object.fromEntries(['event', 'why', 'folder', 'started', 'reason', 'detail'].filter((k) => c[k] !== undefined).map((k) => [k, c[k]]));
244
+ }
245
+ /** A login event (HOST_LOGIN_LABEL from the agent: link {url}, code_sent, bad_code, done {account?}, failed {reason}, cancelled) → it, or null. */
246
+ export function loginEvOf(c) {
247
+ if (!isObj(c) || !['link', 'code_sent', 'bad_code', 'done', 'failed', 'cancelled'].includes(c.state) || (c.state === 'link' && !(isStr(c.url, 4096) && /^https:\/\/\S+$/.test(c.url)))
248
+ || (c.account !== undefined && !isStr(c.account, 120)) || (c.reason !== undefined && !isStr(c.reason, 200))) return null;
249
+ return Object.fromEntries(['state', 'url', 'account', 'reason'].filter((k) => c[k] !== undefined && (k !== 'url' || c.state === 'link')).map((k) => [k, c[k]]));
250
+ }
251
+ /** The login code the sign-in page shows (sigelo-agent-host.ts LOGIN_CODE), spaces taken out. */
252
+ export const HOST_LOGIN_CODE = /^[A-Za-z0-9._~-]{8,1000}#[A-Za-z0-9._~-]{8,1000}$/;
201
253
  /** A hosted agent's settings as it announced them → {fields, note?} (a key not known here dropped), or null (malformed). */
202
254
  export function capsOf(c) {
203
255
  if (typeof c !== 'object' || c === null || Array.isArray(c) || !Array.isArray(c.fields) || c.fields.length > 16) return null;
@@ -210,7 +262,11 @@ export function capsOf(c) {
210
262
  fields.push({ key: f.key, value: f.value, options: f.options.map((o) => ({ value: o.value, label: o.label })), ...(f.off !== undefined && { off: f.off }), ...(f.next !== undefined && { next: f.next }) });
211
263
  }
212
264
  if (c.note !== undefined && !str(c.note, 120)) return null;
213
- return { fields, ...(c.note !== undefined && { note: c.note }) };
265
+ if (c.commands !== undefined && (!Array.isArray(c.commands) || c.commands.length > 32)) return null;
266
+ const commands = (c.commands ?? []).filter((x) => typeof x === 'object' && x !== null && typeof x.name === 'string' && /^[a-z][a-z0-9_-]{0,31}$/.test(x.name) && str(x.help, 120)
267
+ && (x.args === undefined || str(x.args, 40))).map((x) => ({ name: x.name, ...(x.args !== undefined && { args: x.args }), help: x.help }));
268
+ const session = c.session === undefined ? null : sessionOf(c.session);
269
+ return { fields, ...(c.note !== undefined && { note: c.note }), ...(commands.length > 0 && { commands }), ...(session !== null && { session }) };
214
270
  }
215
271
  const chainOnly = (b) => ({ v: 'sigelo/0', typ: 'bundle', genesis: b.genesis, rotations: b.rotations ?? [], bindings: [], attestations: [], issuers: [] });
216
272
  const SIGNED_LINE = /\n-- Signed with sigelo by [a-z]+ [a-z]+ [a-z]+ [a-z]+\. Check it in the sigelo app\.\s*$/;
@@ -284,7 +340,7 @@ export function matchIn(t, want) {
284
340
  return { snippet: pre + body + (to < t.length ? '…' : ''), mark: [s - from + pre.length, Math.min(e, to) - from + pre.length] };
285
341
  }
286
342
 
287
- export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, groupsFile = null, enrolFile = null, codeKind, unlogged, store, hooks = {}, relayFixed = null }) {
343
+ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, groupsFile = null, groups2: G2 = null, groups2File = null, enrolFile = null, codeKind, unlogged, store, hooks = {}, relayFixed = null }) {
288
344
  const defer = hooks.defer ?? ((f) => setTimeout(f, 0));
289
345
  const every = hooks.every ?? ((f, ms) => { const t = setInterval(f, ms); t.unref?.(); return t; });
290
346
  const watchers = new Set();
@@ -357,8 +413,30 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
357
413
  // A contact's own picture (the header's "Pictures"): kept apart, never in the history.
358
414
  if (m['label'] === PICTURE_LABEL) { takePicture(m); continue; }
359
415
  // A hosted agent's settings (the header's): kept apart, never in the history; a setting sent here, dropped.
360
- if (m['label'] === HOST_CAPS_LABEL) { const h = capsOf(m['content']); if (h) { data.host[String(m['from'])] = { ...h, at: nowS() }; saveData(); changed(); } continue; }
416
+ if (m['label'] === HOST_CAPS_LABEL) {
417
+ const h = capsOf(m['content']), was = data.host[String(m['from'])];
418
+ // The Session card's answers stay beside the caps that replace these.
419
+ if (h) { data.host[String(m['from'])] = { ...h, at: nowS(), ...Object.fromEntries(['dirs', 'dirs_ask', 'session_ev', 'login_ev'].filter((k) => was?.[k] !== undefined).map((k) => [k, was[k]])) }; saveData(); changed(); }
420
+ continue;
421
+ }
361
422
  if (m['label'] === HOST_SET_LABEL) continue;
423
+ // The Session card's answers (the header's): beside the agent's caps (none: dropped), never in the history.
424
+ if (m['label'] === HOST_DIRS_LABEL || m['label'] === HOST_SESSION_LABEL || m['label'] === HOST_LOGIN_LABEL) {
425
+ const h = data.host[String(m['from'])], l = m['label'];
426
+ const v = l === HOST_DIRS_LABEL ? dirsOf(m['content']) : l === HOST_SESSION_LABEL ? sessionEvOf(m['content']) : loginEvOf(m['content']);
427
+ if (!h || !v) continue;
428
+ if (l === HOST_DIRS_LABEL) h.dirs = { ...v, at: nowS() };
429
+ else if (l === HOST_SESSION_LABEL) {
430
+ h.session_ev = { ...v, at: nowS() };
431
+ if (h.session && (v.event === 'new' || v.event === 'set')) { if (v.folder !== undefined) h.session.folder = v.folder; if (v.started !== undefined) h.session.started = v.started; h.session.resumed = false; delete h.session.waits; }
432
+ if (h.session && v.event === 'refused') delete h.session.waits;
433
+ } else {
434
+ h.login_ev = { ...v, at: nowS() };
435
+ if (h.session && v.state === 'done') h.session.login = { state: 'signed_in', ...(v.account !== undefined && { account: v.account }), here: true };
436
+ }
437
+ saveData(); changed();
438
+ continue;
439
+ }
362
440
  // A photo's preview (photo.mjs): into the chat at once, the full file by its transfer.
363
441
  if (m['label'] === PHOTO_LABEL) {
364
442
  let ph = null;
@@ -480,6 +558,7 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
480
558
  if (e['check'] === 'pow_confirm') live.powConfirm = { relay: String(e['relay']), detail: String(e['detail']).replace(/^pow_confirm: /, '') };
481
559
  keepOffline();
482
560
  break;
561
+ case 'home': defer(homeRound); break;
483
562
  case 'notice': case 'presence': case 'group_tier': case 'busy': break; // presence, the group tier, a busy mark: the state says it, nothing to take
484
563
  case 'seen': defer(() => { receipt(String(e['from']), true); picturesDue(); }); break;
485
564
  // A new contact told its name (carrier.mjs "Names"): my groups that list it under the made-up one are sent again.
@@ -491,6 +570,19 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
491
570
  };
492
571
  const kept = () => (typeof data.settings.relay === 'string' && goodRelay(data.settings.relay) ? data.settings.relay : null);
493
572
  const carrier = makeCarrier(onEvent, kept() !== null ? { relay: kept() } : {});
573
+ // Home groups: the carrier's sessions at their home relays, and a sync at each `home` it says (the header's "Home groups").
574
+ let homing = null, homeAgain = false;
575
+ function homeRound() {
576
+ if (!G2 || !groups2File) return;
577
+ if (homing) { homeAgain = true; return; }
578
+ homing = (async () => {
579
+ // The items are taken (the page reads the chat from the groups file's history, step 6): nothing piles up in the file.
580
+ do { homeAgain = false; try { await serial(() => G2.sync({ carrier, file: groups2File, take: true })); } catch (err) { live.error = `home groups: ${err.message}`; } } while (homeAgain);
581
+ homing = null;
582
+ changed();
583
+ })();
584
+ }
585
+ if (G2 && groups2File && typeof carrier.setHomes === 'function') carrier.setHomes(() => G2.homes({ carrier, file: groups2File }));
494
586
  // The engine's events: a file offered, done, failed (into the history as events; the view reads GET /api/transfers).
495
587
  const onTransfer = (e) => {
496
588
  if (['asked', 'done', 'failed', 'declined', 'cancelled'].includes(e.what)) {
@@ -506,8 +598,8 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
506
598
  // ---- calls (the header's): the Line, its messages taken from the carrier at each `call` event and each drain.
507
599
  data.calls ??= {};
508
600
  const liveContact = (d) => carrier.contacts().contacts.find((c) => c.did === d && !c.revoked) ?? null;
509
- const canCall = (c) => (typeof data.calls[c.did] === 'boolean' ? data.calls[c.did] : c.tier === 'quiet' ? false : data.settings.calls !== false);
510
- // Calls are between people (design/calls.md §1): a contact this page takes for an agent (its kind, as the chat list
601
+ const canCall = (c) => data.calls[c.did] === true;
602
+ // Calls are between people: a contact this page takes for an agent (its kind, as the chat list
511
603
  // shows it: the human's choice, else my agent, a worker, a group's agent) is never rung from here and never rings here.
512
604
  const personOf = (c) => {
513
605
  const agent = (hooks.agents?.() ?? []).find((a) => a.did !== undefined && c.chain?.includes(a.did));
@@ -519,11 +611,18 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
519
611
  contact: liveContact, allowed: canCall, person: personOf,
520
612
  refused: ({ did, check }) => record({ kind: 'event', type: 'dropped', did, name: liveContact(did)?.name ?? null, code: check, detail: 'a call from an agent: refused (calls are between people)' }),
521
613
  shares: (c) => c.presence === 'allow' || c.presence === 'own', me: () => hooks.me().original,
522
- line: ({ did, dir, text, call }) => { record({ kind: dir, did, name: liveContact(did)?.name ?? null, text, label: CALL_LABEL, call }); },
523
- alert: (x) => { try { CH.alert?.(x); } catch {} },
614
+ line: ({ did, dir, text, call }) => { record({ kind: dir, did, name: liveContact(did)?.name ?? null, text, label: CALL_LABEL, call }); if (call?.state === 'missed') missedNote(did); },
615
+ alert: (x) => { try { return CH.alert?.(x); } catch { return undefined; } },
524
616
  audio: (x) => { try { void Promise.resolve(CH.audio?.(x)).catch(() => {}); } catch {} },
525
617
  changed: () => changed(),
526
618
  });
619
+ // A missed call told at once (CH.missed), not only by the page's poll: as the poll would (alerts for people, the chat
620
+ // not muted, not a quiet contact); the poll's own notification has the same tag (chat:<did>) and replaces it.
621
+ function missedNote(did) {
622
+ const c = liveContact(did);
623
+ if (typeof CH.missed !== 'function' || !c || alertsOf() === 'none' || data.notify?.[did] === false || c.tier === 'quiet') return;
624
+ try { void Promise.resolve(CH.missed({ did, name: c.name })).catch(() => {}); } catch {}
625
+ }
527
626
  const callRound = () => { try { for (const m of carrier.takeCalls()) line.receive(m); } catch (err) { live.error = `calls: ${err.message}`; } };
528
627
  // The relay new codes name, as the precedence says.
529
628
  const newCodes = () => relayFixed ?? kept() ?? DEFAULT_RELAY;
@@ -569,11 +668,14 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
569
668
  }
570
669
  }
571
670
  const notifyOf = (chat) => data.notify[chat] !== false;
671
+ const ALERTS = ['all', 'people', 'none'];
672
+ const alertsOf = () => (ALERTS.includes(data.settings.alerts) ? data.settings.alerts : data.settings.notify === false ? 'none' : 'all');
572
673
  // The public invite as the state shows it (carrier.mjs publicView): the first public code of mine, or null.
573
674
  const publicInvite = (c) => c.publics?.[0] ?? null;
574
675
  const walletSet = () => ({ wallet: data.settings.wallet === true, prices: data.settings.prices === true, currency: CURRENCIES.includes(data.settings.currency) ? data.settings.currency : null });
575
- const settingsAll = () => ({ ...settings(), seen_receipts: receiptsOn(), notify: data.settings.notify !== false,
576
- new_tier: TIER_NEW.has(data.settings.new_tier) ? data.settings.new_tier : 'friend', new_presence: data.settings.new_presence === true, calls: data.settings.calls !== false,
676
+ // notify: alerts not none, for a page from before "Alert me about".
677
+ const settingsAll = () => ({ ...settings(), seen_receipts: receiptsOn(), alerts: alertsOf(), notify: alertsOf() !== 'none',
678
+ new_tier: TIER_NEW.has(data.settings.new_tier) ? data.settings.new_tier : 'friend', new_presence: data.settings.new_presence === true,
577
679
  relay_media: relayMedia() === 'relay', ...walletSet() });
578
680
 
579
681
  // ---- pictures (the header's): mine to the contacts that read them, theirs kept, a local one beside
@@ -613,18 +715,45 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
613
715
  } catch (e) { record({ kind: 'event', type: 'dropped', did: d, name: m['name'], code: 'picture', detail: e.message }); }
614
716
  }
615
717
 
616
- let timers = [];
718
+ let timers = [], homeTicks = 0;
617
719
  async function start() {
618
720
  void checkClock();
619
- timers = [every(() => void checkClock(), 600_000), every(() => void drain().then(() => linkRound()), 60_000)];
721
+ timers = [every(() => void checkClock(), 600_000), every(() => void drain().then(() => linkRound()), 60_000),
722
+ // A join of mine waiting: its answer comes on a reply topic no row announces, so the home is read again: every 5 s for
723
+ // the first 2 minutes of the newest join, then every minute for an hour, then every 10 minutes (a refused one waits on).
724
+ every(() => {
725
+ if (!G2 || !groups2File) return;
726
+ const js = homeList().filter((g) => g.status === 'joining');
727
+ if (!js.length) return;
728
+ const age = nowS() - Math.max(...js.map((g) => g.joining?.at ?? 0)), step = age < 120 ? 1 : age < 3600 ? 12 : 120;
729
+ if (++homeTicks % step === 0) homeRound();
730
+ }, 5000)];
620
731
  // The enrolments from before this start (the pending file): their requests held, a failed identity sent again.
621
732
  try { await look(); } catch {}
733
+ await settlePeople();
622
734
  await carrier.start({ started: 'user' });
623
735
  await drain();
624
736
  void linkRound();
625
737
  picturesDue();
626
738
  void transfers?.engine.kick();
627
739
  }
740
+ // A person is normal or muted (the header's): one on quiet from before is muted and filed friend, once a profile. Its kind
741
+ // as the chat list takes it (the human's, the contact's word, my agent, a worker, a group's agent): an agent keeps quiet.
742
+ async function settlePeople() {
743
+ if (data.settings.people === 1) return;
744
+ try {
745
+ if (K) await workers().catch(() => null);
746
+ const local = hooks.agents?.() ?? [], roles = rosterAgents();
747
+ for (const x of carrier.contacts().contacts) {
748
+ if (x.revoked || x.tier !== 'quiet') continue;
749
+ const agent = local.find((a) => a.did !== undefined && x.chain.includes(a.did));
750
+ if (kindOf(x, agent?.mine ?? null, roles).kind !== 'person') continue;
751
+ data.notify[x.did] = false;
752
+ carrier.setTier(x.did, 'friend');
753
+ }
754
+ data.settings.people = 1; saveData();
755
+ } catch {}
756
+ }
628
757
  async function halt() {
629
758
  for (const t of timers) clearInterval(t);
630
759
  await linking.catch(() => {});
@@ -635,7 +764,7 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
635
764
 
636
765
  // ---- agents: the operator's workers (keeper `workers`), enrolled by a one-time code from this page
637
766
  const K = hooks.keeper ?? null;
638
- // The computer this profile is paired to, for the keeper (design/agent-wallet-page.md §4): { name() → its name,
767
+ // The computer this profile is paired to, for the keeper (UI-API.md "Computers"): { name() → its name,
639
768
  // call(method, path, body?) → { status, body } } (its page over the control, scope all), or none.
640
769
  const PC = hooks.computer ?? null;
641
770
  const viaPc = async (method, path, body) => {
@@ -810,7 +939,8 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
810
939
  const queued = msgs.filter((r) => r.kind === 'out' && r.status === 'queued');
811
940
  return {
812
941
  did: x.did, name: x.name, name_from: x.name_from ?? null, current_did: x.current_did, relay: x.relay, re_pair: x.re_pair, words: x.fingerprint, pair,
813
- words_checked: pair !== null && data.checked[x.did] === pair, tags: data.tags[x.did] ?? [],
942
+ // A sibling proven by its operator attestation and my commitment (kin.mjs) needs no words, as an enrolled worker does not.
943
+ words_checked: pair !== null && (data.checked[x.did] === pair || Boolean(x.kin)), kin: x.kin ?? null, tags: data.tags[x.did] ?? [],
814
944
  // Came by a public code (carrier.mjs via): mine ({public: id}, nobody compared) or theirs ({public: true, words}).
815
945
  via: x.via ?? null,
816
946
  local: agent?.name ?? null, mine, unread: msgs.filter((r) => r.kind === 'in' && r.n > read && (!r.call || r.call.state === 'missed')).length,
@@ -901,7 +1031,7 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
901
1031
  async function groupRound() {
902
1032
  if (!G || !groupsFile) return;
903
1033
  try {
904
- const r = await G.handle({ carrier, file: groupsFile });
1034
+ const r = await G.handle({ carrier, file: groupsFile, ...(groups2File && { file2: groups2File }) });
905
1035
  let noted = false;
906
1036
  for (const n of r.notices) if (n.why !== 'invited') { gnote(n); noted = true; }
907
1037
  const by = new Map();
@@ -926,7 +1056,7 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
926
1056
  const items = ['member', 'frozen'].includes(g.status) ? G.history({ carrier, file: groupsFile, group: g.gid }) : [];
927
1057
  const last = items.at(-1);
928
1058
  return { ...g, unread: unreadIn(g.gid, items), quiet: brakeQuiet(g), notify: notifyOf(g.gid), picture: picRev(`l:${g.gid}`),
929
- last: last ? { name: last.mine ? null : last.name, text: textOf(last.content).slice(0, 200), at: last.received ?? last.iat, mine: last.mine === true } : null };
1059
+ last: last ? { name: last.mine ? null : last.name, role: last.role ?? null, text: textOf(last.content).slice(0, 200), at: last.received ?? last.iat, mine: last.mine === true } : null };
930
1060
  });
931
1061
  }
932
1062
  function groupTier() {
@@ -935,12 +1065,14 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
935
1065
  }
936
1066
  // /api/state's chats: the badge (unread in all), invitations waiting, notices. Never fails the state.
937
1067
  function chatsState() {
938
- if (!G || !groupsFile || carrier.platform.files.read(groupsFile) === null) return { unread: 0, invited: 0, notices: data.gnotices.length, rev: `0.${data.gnotices.length}` };
1068
+ const g1 = Boolean(G && groupsFile && carrier.platform.files.read(groupsFile) !== null);
1069
+ if (!g1 && !(G2 && groups2File && carrier.platform.files.read(groups2File) !== null)) return { unread: 0, invited: 0, notices: data.gnotices.length, rev: `0.${data.gnotices.length}` };
939
1070
  try {
940
- const gs = groupsList();
1071
+ // Home groups too (design/groups-build.md step 6): a sync that brought a row changes rev, so the page reads the list again.
1072
+ const gs = [...(g1 ? groupsList() : []), ...homeList()];
941
1073
  // rev: changes with any group's roster, status, run or newest item (the page fetches a chat again on it).
942
1074
  const rev = gs.map((g) => `${g.gid.slice(0, 8)}.${g.ver}.${g.status}.${g.run}.${g.last?.at ?? 0}.${g.unread}`).join(' ');
943
- return { unread: gs.reduce((a, g) => a + g.unread, 0), invited: gs.filter((g) => g.status === 'pending').length, notices: data.gnotices.length, rev: `${hashOf(rev)}.${data.gnotices.length}` };
1075
+ return { unread: gs.reduce((a, g) => a + g.unread, 0), invited: gs.filter((g) => g.status === 'pending' || g.status === 'invited').length, notices: data.gnotices.length, rev: `${hashOf(rev)}.${data.gnotices.length}` };
944
1076
  } catch { return { unread: 0, invited: 0, notices: data.gnotices.length, rev: '' }; }
945
1077
  }
946
1078
  // group.mjs refusals by check: unknown → 404, usage → 400, any other (group_*, not_contact, name) → 409.
@@ -952,7 +1084,7 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
952
1084
  }
953
1085
  }
954
1086
  const gid = (b) => (typeof b['group'] === 'string' && b['group'] !== '' ? b['group'] : refuse(400, 'body', 'group: its gid'));
955
- const isGroup = (x) => { try { return typeof x === 'string' && /^[0-9a-f]{32}$/.test(x) && Boolean(G && groupsFile && carrier.platform.files.read(groupsFile) !== null && G.list({ carrier, file: groupsFile }).some((g) => g.gid === x)); } catch { return false; } };
1087
+ const isGroup = (x) => { try { return typeof x === 'string' && /^[0-9a-f]{32}$/.test(x) && (Boolean(G && groupsFile && carrier.platform.files.read(groupsFile) !== null && G.list({ carrier, file: groupsFile }).some((g) => g.gid === x)) || isHome(x)); } catch { return false; } };
956
1088
  const dids = (v, what, need = true) => {
957
1089
  if (v === undefined && !need) return [];
958
1090
  if (!Array.isArray(v) || (need && v.length === 0) || v.length > 64 || v.some((x) => typeof x !== 'string' || x === '')) refuse(400, 'body', `${what}: a list of contact DIDs`);
@@ -965,16 +1097,21 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
965
1097
  'GET /api/groups/history': (_, q) => groupCall(() => {
966
1098
  const g = q.get('group') ?? refuse(400, 'body', 'group: its gid'), one = groupsList().find((x) => x.gid === g) ?? refuse(404, 'group_unknown', `no group ${g} here`);
967
1099
  const items = G.history({ carrier, file: groupsFile, group: g }), last = items.at(-1);
1100
+ // The first item new to this look (as unreadIn counts: after the newest shown, not mine), before the mark moves.
1101
+ const m0 = data.gread[g], at0 = m0 ? items.findIndex((i) => i.mid === m0.mid) : -1;
1102
+ const unreadFrom = (!m0 ? items : at0 >= 0 ? items.slice(at0 + 1) : items.filter((i) => (i.received ?? 0) > m0.at)).find((i) => !i.mine)?.mid ?? null;
968
1103
  // Read: the page has shown them.
969
1104
  if (last && data.gread[g]?.mid !== last.mid) { data.gread[g] = { mid: last.mid, at: last.received ?? last.iat }; saveData(); }
970
- return { group: { ...one, unread: 0 }, messages: items.slice(-200).map((i) => ({ mid: i.mid, re: i.re ?? null, from: i.from, name: i.name, role: i.role, tier: i.tier ?? null, mine: i.mine === true,
1105
+ return { group: { ...one, unread: 0 }, unread_from: unreadFrom, messages: items.slice(-200).map((i) => ({ mid: i.mid, re: i.re ?? null, from: i.from, name: i.name, role: i.role, tier: i.tier ?? null, mine: i.mine === true,
971
1106
  operator: i.operator === true, note: i.note ?? null, text: textOf(i.content), mentions: i.mentions ?? [], mentioned: i.mentioned === true, via: i.via ?? null, photo: i.photo ?? null, ...(i.voice && { voice: i.voice }), at: i.received ?? i.iat })) };
972
1107
  }),
973
- 'POST /api/groups/create': (b) => serial(() => groupCall(async () => {
974
- const brake = b['brake'];
975
- return gout(await G.create({ carrier, file: groupsFile, name: b['name'], members: dids(b['members'], 'members'), humans: dids(b['humans'], 'humans', false), ...(brake !== undefined && brake !== null && { brake }),
976
- ...(carrier.selfName() !== null && { selfName: carrier.selfName() }),
977
- ...(typeof b['role'] === 'string' && { role: b['role'] }) }));
1108
+ // A group of contacts of mine to a home group (design/groups-build.md §5): its members invited over the pairings.
1109
+ 'POST /api/groups/move': (b) => serial(() => groupCall(async () => {
1110
+ const home = b['home'] === undefined || b['home'] === null || b['home'] === '' ? undefined : String(b['home']).trim().toLowerCase();
1111
+ if (home !== undefined) checkRelay(home);
1112
+ const r = await G.move({ carrier, file: groupsFile, file2: groups2File, group: gid(b), ...(home && { home }) });
1113
+ carrier.wake?.({ now: true });
1114
+ return { ...gout({ ...r, copies: [...r.invited, ...r.line] }), home: homeOne(r.home.gid) ?? r.home, unreached: r.unreached };
978
1115
  })),
979
1116
  'POST /api/groups/add': (b) => serial(() => groupCall(async () => gout(await G.add({ carrier, file: groupsFile, group: gid(b), members: dids(b['members'], 'members'), humans: dids(b['humans'], 'humans', false) })))),
980
1117
  'POST /api/groups/remove': (b) => serial(() => groupCall(async () => gout(await G.remove({ carrier, file: groupsFile, group: gid(b), members: dids(b['members'], 'members') })))),
@@ -1001,11 +1138,269 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1001
1138
  }),
1002
1139
  };
1003
1140
 
1141
+ // ---- home groups (design/groups-build.md step 6; UI-API.md "Home groups"): group2.mjs over groups2File. The list and
1142
+ // the chat read the file only, never the relay; every action is a session at the group's home relay, one at a time
1143
+ // (serial). The page's own marks in data: gread as for groups; gjoin (gid → {approve, at}: a join of mine waiting);
1144
+ // gnames (DID → the name a member had when removed here: the Banned list names it).
1145
+ const JOIN_LINK = 'https://sigelo.io/join#';
1146
+ const HOME_KEYS = ['name', 'about', 'channel', 'join', 'history', 'agents', 'brake'];
1147
+ let homeMemo = null;
1148
+ // The groups file's view (G2.list, local, show), kept while the file is the same and for 30 s at most (links run out).
1149
+ function homeBase() {
1150
+ const raw = carrier.platform.files.read(groups2File);
1151
+ if (raw === null) return [];
1152
+ const t = new TextDecoder().decode(raw), key = `${t.length}.${hashOf(t)}`;
1153
+ if (homeMemo?.key === key && nowS() - homeMemo.at < 30) return homeMemo.base;
1154
+ const gs = G2.list({ carrier, file: groups2File }), facts = G2.local({ carrier, file: groups2File });
1155
+ const base = gs.map((g) => ({ g, f: facts[g.gid] ?? {}, msgs: g.status === 'joining' ? [] : G2.show({ carrier, file: groups2File, group: g.gid }).messages }));
1156
+ homeMemo = { key, at: nowS(), base };
1157
+ return base;
1158
+ }
1159
+ // A message of the log as the chat and the unread count read it (a poll by its question; a deleted one by its mark).
1160
+ const homeText = (m) => (m.deleted ? '' : m.text ?? (m.poll ? `Poll: ${m.poll.question}` : m.file ? `File: ${m.file.name}` : ''));
1161
+ const homeItems = (msgs) => msgs.map((m) => ({ mid: m.mid, mine: m.mine === true, received: m.iat }));
1162
+ function homeList() {
1163
+ if (!G2 || !groups2File) return [];
1164
+ let base;
1165
+ try { base = homeBase(); } catch (e) { live.error = `home groups: ${e.message}`; return []; }
1166
+ const cs = new Map(carrier.contacts().contacts.filter((c) => !c.revoked && !hidden(c)).map((c) => [c.did, c])), me = hooks.me().original;
1167
+ const nameOf = (d, n) => cs.get(d)?.name ?? n;
1168
+ return base.map(({ g, f, msgs }) => {
1169
+ const items = homeItems(msgs), lastM = msgs.at(-1);
1170
+ const members = g.members.map((m) => ({ did: m.did, name: m.me ? m.name : nameOf(m.did, m.name), kind: m.kind, role: m.role, me: m.me, contact: !m.me && cs.has(m.did) }));
1171
+ const owner = members.find((m) => m.role === 'owner');
1172
+ return { gid: g.gid, name: g.name, v: 2, home: g.home, home_own: g.home === carrier.relay, status: g.status,
1173
+ ended: g.status === 'closed' ? f.closed ?? 'end' : null, banned: g.status === 'removed' && (f.barred ?? []).includes(me),
1174
+ role: g.role, mine: g.role === 'owner', owner: f.owner ?? null, owner_words: f.owner ? didWords(f.owner) : null, owner_name: owner ? (owner.me ? null : owner.name) : f.owner ? nameOf(f.owner, null) : null,
1175
+ settings: g.settings ?? {}, brake: g.settings?.brake ?? 20, pins: g.pins ?? [], requests: g.requests,
1176
+ links: (g.links ?? []).map((l) => ({ id: l.id, exp: l.exp, approve: l.approve, code: l.code ?? null, link: l.code ? JOIN_LINK + l.code : null })),
1177
+ members, barred: (f.barred ?? []).map((d) => ({ did: d, name: nameOf(d, data.gnames?.[d] ?? null), words: didWords(d) })),
1178
+ joining: g.status === 'joining' ? { at: f.joining?.at ?? null, approve: data.gjoin?.[g.gid]?.approve ?? null } : null,
1179
+ // An invitation over a pairing, waiting (design/groups-build.md §1.6): who sent it, until when; a move names the old group.
1180
+ invited: g.status === 'invited' && f.invited ? { by: f.invited.by, name: nameOf(f.invited.by, f.invited.name), at: f.invited.at, exp: f.invited.exp } : null, moved_from: f.moved_from ?? null,
1181
+ run: 0, quiet: false, ver: `${f.seq ?? 0}.${g.requests}.${g.role}.${members.length}.${g.epoch}.${(g.links ?? []).length}`,
1182
+ // The picture: one set on this device, else the group's (an admin's, in the log: step 7).
1183
+ unread: unreadIn(g.gid, items), notify: notifyOf(g.gid), picture: picRev(`l:${g.gid}`) ?? (g.settings?.avatar ? `a${g.settings.avatar.sha256.slice(0, 16)}` : null),
1184
+ last: lastM ? { name: lastM.mine ? null : nameOf(lastM.from, lastM.name), role: lastM.role, kind: lastM.kind, text: homeText(lastM).slice(0, 200), at: lastM.iat, mine: lastM.mine === true } : null };
1185
+ });
1186
+ }
1187
+ const homeOne = (gid) => homeList().find((g) => g.gid === gid) ?? null;
1188
+ const isHome = (x) => typeof x === 'string' && /^[0-9a-f]{32}$/.test(x) && homeOne(x) !== null;
1189
+ // group2.mjs refusals by check: unknown → 404; a code, a link's terms, a setting or a text that is wrong → 400; the rest (a role
1190
+ // missing, a member, the relay's home_*) → 409.
1191
+ // read: a read of the file only (events), which changes nothing to push.
1192
+ async function homeCall(fn, read = false) {
1193
+ if (!G2 || !groups2File) refuse(404, 'route', 'no home groups here');
1194
+ try { const r = await fn(); if (!read) changed(); return r; } catch (e) {
1195
+ if (e.check !== undefined && e.status === undefined) e.status = ['group_unknown', 'group_name', 'group_file_gone'].includes(e.check) ? 404 : ['group_code', 'group_link', 'group_settings', 'group_text', 'group_message', 'group_file', 'group_file_size', 'group_events', 'code_relay', 'body'].includes(e.check) ? 400 : 409;
1196
+ throw e;
1197
+ }
1198
+ }
1199
+ const hgid = (b) => { const g = gid(b); if (!isHome(g)) refuse(404, 'group_unknown', `no home group ${g} here`); return g; };
1200
+ const hfile = () => ({ carrier, file: groups2File });
1201
+ // A write's answer: what group2.mjs said, and the group as the list shows it now.
1202
+ const homeOut = (r, g) => ({ ...r, group: homeOne(g) ?? r?.group ?? null });
1203
+ const memberArg = (b) => (typeof b['member'] === 'string' && b['member'] !== '' ? b['member'] : refuse(400, 'body', 'member: a member\'s DID'));
1204
+ const homeRoutes = {
1205
+ 'POST /api/groups/create': (b) => serial(() => homeCall(async () => {
1206
+ const name = typeof b['name'] === 'string' ? b['name'].trim() : refuse(400, 'body', 'name: the group\'s name');
1207
+ const home = b['home'] === undefined || b['home'] === null || b['home'] === '' ? carrier.relay : String(b['home']).trim().toLowerCase();
1208
+ checkRelay(home);
1209
+ // Contacts picked (New group): invited over the pairings once it is made.
1210
+ const members = dids(b['members'], 'members', false);
1211
+ const r = await G2.create({ ...hfile(), name, home, kind: 'human', selfName: carrier.selfName() ?? 'owner', ...(members.length && { members }) });
1212
+ carrier.wake?.({ now: true });
1213
+ return { group: homeOne(r.group.gid) ?? r.group, copies: r.invited?.copies ?? [] };
1214
+ })),
1215
+ 'POST /api/groups/add': (b) => serial(() => homeCall(async () => {
1216
+ const r = await G2.add({ ...hfile(), group: hgid(b), members: dids(b['members'], 'members') });
1217
+ return { group: homeOne(r.gid), copies: r.copies, ...(r.offline !== undefined && { offline: r.offline }) };
1218
+ })),
1219
+ 'POST /api/groups/preview': (b) => homeCall(async () => {
1220
+ const code = typeof b['code'] === 'string' && b['code'].trim() !== '' ? b['code'] : refuse(400, 'body', 'code: a GRP code or its link');
1221
+ // A supergroup's address (name@relay, design/groups-build.md §3.7): its card, checked offline; private: join needs `with`.
1222
+ const at = G2.parseAddress(code), c = at ? await G2.card({ carrier, address: code }) : null;
1223
+ const p = c ? { gid: c.gid, name: c.name, home: c.relay, owner: c.owner, words: c.words, approve: c.approve, exp: c.link_exp ?? c.slot.exp,
1224
+ supergroup: { address: c.address, public: c.public, about: c.about, pinned: c.pinned, operator_words: c.operator_words } } : await G2.peek({ carrier, code });
1225
+ return { ...p, owner_name: carrier.contacts().contacts.find((c) => c.did === p.owner && !c.revoked)?.name ?? null, status: homeOne(p.gid)?.status ?? null };
1226
+ }),
1227
+ 'POST /api/groups/join': (b) => serial(() => homeCall(async () => {
1228
+ // An invitation over a pairing joins by its group's gid (one tap); else a code, a link or a name.
1229
+ const r = await G2.join({ ...hfile(), code: b['code'] ?? hgid(b), ...(typeof b['with'] === 'string' && b['with'].trim() !== '' && { with: b['with'] }), name: carrier.selfName() ?? 'member', kind: 'human' });
1230
+ (data.gjoin ??= {})[r.group.gid] = { approve: r.approve, at: nowS() };
1231
+ saveData();
1232
+ carrier.wake?.({ now: true });
1233
+ return { group: homeOne(r.group.gid) ?? r.group, status: 'waiting', approve: r.approve, words: r.words };
1234
+ })),
1235
+ 'POST /api/groups/drop': (b) => serial(() => homeCall(async () => {
1236
+ const r = G2.drop({ ...hfile(), group: hgid(b) });
1237
+ delete data.gjoin?.[r.dropped]; delete data.gread[r.dropped]; delete data.notify[r.dropped];
1238
+ saveData();
1239
+ return r;
1240
+ })),
1241
+ 'POST /api/groups/sync': (b) => serial(() => homeCall(async () => {
1242
+ const r = await G2.sync({ ...hfile(), ...(b['group'] !== undefined && { group: hgid(b) }), take: true });
1243
+ return { groups: r.groups.map((g) => homeOne(g.gid) ?? g) };
1244
+ })),
1245
+ 'POST /api/groups/link': (b) => serial(() => homeCall(async () => {
1246
+ const ttl = b['ttl'] === undefined ? undefined : Number(b['ttl']), approve = b['approve'];
1247
+ if (approve !== undefined && approve !== 'auto' && approve !== 'admin') refuse(400, 'body', 'approve: auto or admin');
1248
+ const r = await G2.link({ ...hfile(), group: hgid(b), ...(ttl !== undefined && { ttl }), ...(approve !== undefined && { approve }) });
1249
+ // The long invite stays out: what a person sees and shares is the GRP code and its link.
1250
+ return { id: r.id, code: r.code, link: r.link ?? null, words: r.words, exp: r.exp, approve: r.approve, cap: r.cap, home: r.home, ...(r.park_error && { park_error: r.park_error }) };
1251
+ })),
1252
+ 'POST /api/groups/unlink': (b) => serial(() => homeCall(async () => homeOut(await G2.unlink({ ...hfile(), group: hgid(b), id: String(b['id'] ?? '') }), b['group']))),
1253
+ 'GET /api/groups/requests': (_, q) => homeCall(async () => {
1254
+ const g = q.get('group') ?? refuse(400, 'body', 'group: its gid');
1255
+ if (!isHome(g)) refuse(404, 'group_unknown', `no home group ${g} here`);
1256
+ const cs = new Map(carrier.contacts().contacts.filter((c) => !c.revoked).map((c) => [c.did, c]));
1257
+ return { requests: (G2.local(hfile())[g]?.requests ?? []).map((x) => ({ ...x, contact: cs.has(x.did), ...(cs.has(x.did) && { name: cs.get(x.did).name }) })) };
1258
+ }),
1259
+ // The event history (owner and admins: all; moderators: kicks, bans, deletes, pins; a member: 409 group_role), from this
1260
+ // device's file: names as the list shows them (a contact's name, You), a deleted message's text never (not kept).
1261
+ 'POST /api/groups/events': (b) => homeCall(async () => {
1262
+ const g = hgid(b), one = homeOne(g), me = hooks.me().original;
1263
+ const num = (k, lo, hi) => (b[k] === undefined || b[k] === null ? undefined : Number.isSafeInteger(b[k]) && b[k] >= lo && b[k] <= hi ? b[k] : refuse(400, 'body', `${k}: a whole number, ${lo} to ${hi}`));
1264
+ const r = G2.events({ ...hfile(), group: g, since: num('since', 0, Number.MAX_SAFE_INTEGER), limit: num('limit', 1, 500) });
1265
+ const names = new Map((one?.members ?? []).map((m) => [m.did, m.name])), who = (x) => (x ? { did: x.did, name: x.did === me ? 'You' : names.get(x.did) ?? x.name ?? data.gnames?.[x.did] ?? null, me: x.did === me } : null);
1266
+ return { group: one, role: r.role, full: r.full, more: r.more, events: r.events.map((e) => ({ ...e, by: who(e.by), ...(e.target && { target: who(e.target) }) })) };
1267
+ }, true),
1268
+ 'POST /api/groups/approve': (b) => serial(() => homeCall(async () => homeOut(await G2.approve({ ...hfile(), group: hgid(b), id: String(b['id'] ?? '') }), b['group']))),
1269
+ 'POST /api/groups/refuse': (b) => serial(() => homeCall(async () => ({ ...(await G2.refuse({ ...hfile(), group: hgid(b), id: String(b['id'] ?? '') })), group: homeOne(b['group']) }))),
1270
+ 'POST /api/groups/kick': (b) => serial(() => homeCall(async () => {
1271
+ const g = hgid(b), m = memberArg(b), who = homeOne(g)?.members.find((x) => x.did === m);
1272
+ if (who) { (data.gnames ??= {})[m] = who.name; saveData(); }
1273
+ return homeOut(await G2.kick({ ...hfile(), group: g, member: m, bar: b['bar'] === true }), g);
1274
+ })),
1275
+ 'POST /api/groups/unbar': (b) => serial(() => homeCall(async () => homeOut(await G2.unbar({ ...hfile(), group: hgid(b), member: memberArg(b) }), b['group']))),
1276
+ 'POST /api/groups/role': (b) => serial(() => homeCall(async () => {
1277
+ if (!['admin', 'moderator', 'member'].includes(b['role'])) refuse(400, 'body', 'role: admin, moderator or member');
1278
+ return homeOut(await G2.role({ ...hfile(), group: hgid(b), member: memberArg(b), role: b['role'] }), b['group']);
1279
+ })),
1280
+ 'POST /api/groups/set': (b) => serial(() => homeCall(async () => {
1281
+ if (!HOME_KEYS.includes(b['key'])) refuse(400, 'body', `key: one of ${HOME_KEYS.join(', ')}`);
1282
+ return homeOut(await G2.set({ ...hfile(), group: hgid(b), key: b['key'], value: b['value'] }), b['group']);
1283
+ })),
1284
+ 'POST /api/groups/rename': (b) => serial(() => homeCall(async () => homeOut(await G2.set({ ...hfile(), group: hgid(b), key: 'name', value: typeof b['name'] === 'string' ? b['name'].trim() : b['name'] }), b['group']))),
1285
+ 'POST /api/groups/brake': (b) => serial(() => homeCall(async () => homeOut(await G2.set({ ...hfile(), group: hgid(b), key: 'brake', value: b['brake'] }), b['group']))),
1286
+ 'POST /api/groups/handover': (b) => serial(() => homeCall(async () => homeOut(await G2.handover({ ...hfile(), group: hgid(b), member: memberArg(b) }), b['group']))),
1287
+ 'POST /api/groups/end': (b) => serial(() => homeCall(async () => homeOut(await G2.end({ ...hfile(), group: hgid(b) }), b['group']))),
1288
+ 'POST /api/groups/leave': (b) => serial(() => homeCall(async () => ({ ...homeOut(await G2.leave({ ...hfile(), group: hgid(b) }), b['group']), copies: [], told: true }))),
1289
+ 'POST /api/groups/history': (b) => serial(() => homeCall(async () => homeOut(await G2.historyAsk({ ...hfile(), group: hgid(b) }), b['group']))),
1290
+ 'POST /api/groups/send': (b) => serial(() => homeCall(async () => {
1291
+ const g = hgid(b), text = b['text'], re = b['re'];
1292
+ if (typeof text !== 'string' || text.trim() === '') refuse(400, 'body', 'text: the message');
1293
+ // @name in the text mentions that member, as in a group of contacts.
1294
+ const esc = (t) => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1295
+ const at = (homeOne(g)?.members ?? []).filter((m) => !m.me && new RegExp(`(^|\\s)@${esc(m.name)}(?=$|[\\s.,!?:;])`).test(text)).map((m) => m.did);
1296
+ const given = Array.isArray(b['mentions']) ? b['mentions'].filter((x) => typeof x === 'string') : [];
1297
+ const r = await G2.send({ ...hfile(), group: g, text, ...(typeof re === 'string' && re !== '' && { re }), mentions: [...new Set([...given, ...at])] });
1298
+ return { gid: g, mid: r.mid, seq: r.seq ?? null, copies: [], via_creator: [], unreached: [] };
1299
+ })),
1300
+ 'GET /api/groups/history': (_, q) => homeCall(async () => {
1301
+ const g = q.get('group'), one = homeOne(g) ?? refuse(404, 'group_unknown', `no home group ${g} here`), me = hooks.me().original;
1302
+ const msgs = one.status === 'joining' ? [] : G2.show({ ...hfile(), group: g }).messages, items = homeItems(msgs), last = items.at(-1);
1303
+ const m0 = data.gread[g], at0 = m0 ? items.findIndex((i) => i.mid === m0.mid) : -1;
1304
+ const unreadFrom = (!m0 ? items : at0 >= 0 ? items.slice(at0 + 1) : items.filter((i) => (i.received ?? 0) > m0.at)).find((i) => !i.mine)?.mid ?? null;
1305
+ if (last && data.gread[g]?.mid !== last.mid) { data.gread[g] = { mid: last.mid, at: last.received }; saveData(); }
1306
+ const names = new Map(one.members.map((m) => [m.did, m.name])), nameOf = (d) => (d === me ? 'You' : names.get(d) ?? 'A former member');
1307
+ // Step 7: reactions (each emoji: count, mine, who), the poll's view (tallies, my choices), a file's manifest, pins with a line each.
1308
+ const reactions = (r) => Object.entries(r ?? {}).map(([emoji, ds]) => ({ emoji, n: ds.length, mine: ds.includes(me), who: ds.map(nameOf) })).filter((x) => x.n);
1309
+ const pollOf = (p) => ({ question: p.question, options: p.options, multi: p.multi, closed: p.closed, tallies: p.options.map((_, i) => Object.values(p.votes).filter((c) => c.includes(i)).length),
1310
+ voters: Object.keys(p.votes).length, mine: p.votes[me] ?? [] });
1311
+ const byMid = new Map(msgs.map((m) => [m.mid, m]));
1312
+ return { group: { ...one, unread: 0 }, unread_from: unreadFrom,
1313
+ pins: [...one.pins].reverse().map((mid) => byMid.get(mid)).filter((m) => m && !m.deleted).map((m) => ({ mid: m.mid, name: nameOf(m.from), text: homeText(m).split('\n')[0].slice(0, 120), at: m.iat })),
1314
+ messages: msgs.slice(-200).map((m) => ({ mid: m.mid, seq: m.seq, re: m.re ?? null, from: m.from, name: names.get(m.from) ?? m.name, role: m.role, kind: m.kind,
1315
+ tier: null, mine: m.mine === true, operator: false, note: null, text: homeText(m), ...(m.deleted && { deleted: true, ...(m.deleted_by && { deleted_by: m.deleted_by }) }), ...(m.edited && { edited: true }),
1316
+ ...(m.poll && { poll: pollOf(m.poll) }), ...(m.file && !m.deleted && { file: { name: m.file.name, size: m.file.size, type: m.file.type, sha256: m.file.sha256, ...(m.text === undefined && { only: true }) } }),
1317
+ reactions: reactions(m.reactions), pinned: m.pinned === true,
1318
+ mentions: m.mentions ?? [], mentioned: (m.mentions ?? []).includes(me), via: null, photo: null, at: m.iat })) };
1319
+ }),
1320
+ };
1321
+ // ---- step 7 (design/groups-build.md; UI-API.md "Home groups: in the chat"): reactions, edit, delete, pins, polls, files up
1322
+ // to 8 MiB in the log, the group's picture. A file comes up in chunks (the ui server takes 256 KiB a request): POST
1323
+ // /api/groups/file {group, upload, name, type, size, offset, data} until offset + its bytes = size, then it goes.
1324
+ const midArg = (b, k = 'mid') => (typeof b[k] === 'string' && /^[0-9a-f]{16}$/.test(b[k]) ? b[k] : refuse(400, 'body', `${k}: a message's mid (16 hex)`));
1325
+ const FILE_LOG = 8 * 2 ** 20, UPLOAD_CHUNK = 128 * 1024, UPLOADS = new Map();
1326
+ const sweepUploads = () => { for (const [k, u] of UPLOADS) if (nowS() - u.at > 600) UPLOADS.delete(k); };
1327
+ Object.assign(homeRoutes, {
1328
+ 'POST /api/groups/react': (b) => serial(() => homeCall(async () => {
1329
+ const g = hgid(b);
1330
+ if (typeof b['emoji'] !== 'string' || b['emoji'] === '') refuse(400, 'body', 'emoji: one emoji');
1331
+ return homeOut(await G2.react({ ...hfile(), group: g, re: midArg(b), emoji: b['emoji'], on: b['on'] !== false }), g);
1332
+ })),
1333
+ 'POST /api/groups/edit': (b) => serial(() => homeCall(async () => {
1334
+ const g = hgid(b);
1335
+ if (typeof b['text'] !== 'string' || b['text'].trim() === '') refuse(400, 'body', 'text: the new text');
1336
+ return homeOut(await G2.edit({ ...hfile(), group: g, re: midArg(b), text: b['text'] }), g);
1337
+ })),
1338
+ 'POST /api/groups/delete': (b) => serial(() => homeCall(async () => homeOut(await G2.remove({ ...hfile(), group: hgid(b), re: midArg(b) }), b['group']))),
1339
+ 'POST /api/groups/pin': (b) => serial(() => homeCall(async () => homeOut(await G2.pin({ ...hfile(), group: hgid(b), re: midArg(b), on: b['on'] !== false }), b['group']))),
1340
+ 'POST /api/groups/poll': (b) => serial(() => homeCall(async () => {
1341
+ hgid(b);
1342
+ const options = Array.isArray(b['options']) ? b['options'].map((o) => (typeof o === 'string' ? o.trim() : o)).filter((o) => o !== '') : refuse(400, 'body', 'options: 2 to 10 answers');
1343
+ return homeOut(await G2.poll({ ...hfile(), group: hgid(b), question: typeof b['question'] === 'string' ? b['question'].trim() : b['question'], options, multi: b['multi'] === true }), b['group']);
1344
+ })),
1345
+ 'POST /api/groups/vote': (b) => serial(() => homeCall(async () => {
1346
+ hgid(b);
1347
+ const choices = Array.isArray(b['choices']) && b['choices'].every((c) => Number.isSafeInteger(c)) ? b['choices'] : refuse(400, 'body', 'choices: the answers\' numbers, from 0 ([] takes the vote back)');
1348
+ return homeOut(await G2.vote({ ...hfile(), group: hgid(b), re: midArg(b), choices }), b['group']);
1349
+ })),
1350
+ 'POST /api/groups/poll_end': (b) => serial(() => homeCall(async () => homeOut(await G2.pollEnd({ ...hfile(), group: hgid(b), re: midArg(b) }), b['group']))),
1351
+ 'POST /api/groups/file': (b) => homeCall(async () => {
1352
+ sweepUploads();
1353
+ const g = hgid(b), id = typeof b['upload'] === 'string' && /^[0-9a-f]{16,32}$/.test(b['upload']) ? b['upload'] : refuse(400, 'body', 'upload: 16 to 32 hex, the same for every chunk of one file');
1354
+ const size = b['size'], off = b['offset'];
1355
+ if (!Number.isSafeInteger(size) || size < 1) refuse(400, 'body', 'size: the file\'s bytes');
1356
+ if (size > FILE_LOG) refuse(400, 'group_file_size', `a file in a group is at most 8 MiB; this one is ${(size / 2 ** 20).toFixed(1)} MiB`);
1357
+ if (typeof b['data'] !== 'string' || !/^[A-Za-z0-9+/]*={0,2}$/.test(b['data'])) refuse(400, 'body', 'data: base64 of the next chunk');
1358
+ const chunk = unb64(b['data']);
1359
+ if (chunk.length === 0 || chunk.length > UPLOAD_CHUNK) refuse(400, 'body', `data: a chunk of 1 to ${UPLOAD_CHUNK / 1024} KiB`);
1360
+ let u = UPLOADS.get(id);
1361
+ if (off === 0) {
1362
+ if (!u && UPLOADS.size >= 4) refuse(409, 'busy', 'four files are coming up already: wait for one');
1363
+ const name = typeof b['name'] === 'string' ? b['name'] : refuse(400, 'body', 'name: the file\'s name');
1364
+ u = { group: g, name, type: typeof b['type'] === 'string' && b['type'] !== '' ? b['type'].toLowerCase() : 'application/octet-stream', bytes: new Uint8Array(size), got: 0, at: nowS(),
1365
+ text: typeof b['text'] === 'string' && b['text'].trim() !== '' ? b['text'] : undefined, re: typeof b['re'] === 'string' && b['re'] !== '' ? b['re'] : undefined };
1366
+ UPLOADS.set(id, u);
1367
+ }
1368
+ if (!u || u.group !== g || off !== u.got || u.bytes.length !== size || u.got + chunk.length > size) { UPLOADS.delete(id); refuse(409, 'upload', 'not the next chunk of this upload: start again from offset 0'); }
1369
+ u.bytes.set(chunk, u.got); u.got += chunk.length; u.at = nowS();
1370
+ if (u.got < size) return { upload: id, got: u.got, size };
1371
+ UPLOADS.delete(id);
1372
+ const r = await serial(() => G2.sendFile({ ...hfile(), group: g, name: u.name, type: u.type, bytes: u.bytes, text: u.text, re: u.re }));
1373
+ return { upload: id, got: size, size, gid: g, mid: r.mid, seq: r.seq ?? null };
1374
+ }),
1375
+ 'GET /api/groups/file': (_, q) => homeCall(async () => {
1376
+ const g = q.get('group');
1377
+ if (!isHome(g)) refuse(404, 'group_unknown', `no home group ${g} here`);
1378
+ const f = G2.fileOf({ ...hfile(), group: g, mid: midArg({ mid: q.get('mid') }) });
1379
+ return { name: f.name, type: f.type, size: f.size, sha256: f.sha256, data: b64(f.bytes) };
1380
+ }),
1381
+ // The group's picture for everyone (an admin): a picture as POST /api/picture takes one, w and h its pixels; remove: none.
1382
+ 'POST /api/groups/avatar': (b) => serial(() => homeCall(async () => {
1383
+ const g = hgid(b);
1384
+ if (b['remove'] === true) return homeOut(await G2.avatar({ ...hfile(), group: g, bytes: null }), g);
1385
+ const bytes = pictureBytes(b['type'], b['data']), side = (k) => (Number.isSafeInteger(b[k]) && b[k] >= 1 && b[k] <= 1024 ? b[k] : refuse(400, 'body', `${k}: the picture's pixels, 1 to 1024`));
1386
+ return homeOut(await G2.avatar({ ...hfile(), group: g, type: b['type'], bytes, w: side('w'), h: side('h') }), g);
1387
+ })),
1388
+ });
1389
+ // Which side a shared route takes: create with no members, join by a code, and a group that is a home group go to group2.mjs.
1390
+ const homeAsked = (key, b, q) => {
1391
+ if (key === 'POST /api/groups/create') return true; // step 8: every new group is a home group
1392
+ if (key === 'POST /api/groups/join') return b['code'] !== undefined || isHome(b['group']);
1393
+ if (key === 'GET /api/groups/history' || key === 'GET /api/groups/file') return isHome(q.get('group'));
1394
+ return isHome(b['group']);
1395
+ };
1396
+
1004
1397
  // ---- writes
1005
1398
  const contactOf = (d) => {
1006
1399
  if (typeof d !== 'string') refuse(400, 'body', 'contact: a DID');
1007
1400
  return carrier.contacts().contacts.find((x) => !x.revoked && x.did === d && !hidden(x)) ?? refuse(404, 'not_contact', `${String(d)} is not a contact`);
1008
1401
  };
1402
+ // The agent's caps with the Session card (its session), else refused: it has not said it takes these.
1403
+ const hostSession = (c) => { const h = data.host[c.did]; if (!h?.session) refuse(409, 'host_none', 'This agent has not said it takes these (an older host?)'); return h; };
1009
1404
  const cleanName = (v, what) => {
1010
1405
  if (typeof v !== 'string' || v.trim() === '' || [...v.trim()].length > NAME_MAX || /[\u0000-\u001f\u007f-\u009f]/.test(v)) refuse(400, 'body', `${what}: 1 to ${NAME_MAX} characters, no controls`);
1011
1406
  return v.trim();
@@ -1029,7 +1424,7 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1029
1424
  const m = hooks.me();
1030
1425
  if (v.original === m.original && m.chain.includes(v.did)) return { kind: 'me', did: m.original, name: null, words_checked: true };
1031
1426
  const c = carrier.contacts().contacts.find((x) => !x.revoked && !hidden(x) && x.did === v.original && x.chain.includes(v.did));
1032
- return c ? { kind: 'contact', did: c.did, name: c.name, words_checked: c.pair !== null && data.checked[c.did] === c.pair } : { kind: 'unknown', did: v.original, name: null, words_checked: false };
1427
+ return c ? { kind: 'contact', did: c.did, name: c.name, words_checked: c.pair !== null && (data.checked[c.did] === c.pair || Boolean(c.kin)) } : { kind: 'unknown', did: v.original, name: null, words_checked: false };
1033
1428
  }
1034
1429
  const checked = (v) => (v.valid ? { ...v, words: didWords(v.original), by: signerOf(v) } : v);
1035
1430
  // A statement in a chat (the bubble's "Signed by … · check"): checked once per message, kept for the page's life.
@@ -1074,12 +1469,19 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1074
1469
  }
1075
1470
  if (one === null) {
1076
1471
  const gs = G && groupsFile && carrier.platform.files.read(groupsFile) !== null ? G.list({ carrier, file: groupsFile }).filter((g) => grp === null || g.gid === grp) : [];
1077
- if (grp !== null && !gs.length) refuse(404, 'group_unknown', `no group ${grp} here`);
1472
+ if (grp !== null && !gs.length && !isHome(grp)) refuse(404, 'group_unknown', `no group ${grp} here`);
1078
1473
  for (const g of gs) {
1079
1474
  let items = [];
1080
1475
  try { items = G.history({ carrier, file: groupsFile, group: g.gid }); } catch {}
1081
1476
  for (const i of items) if (!i.photo && !i.voice) hit({ chat: g.gid, kind: 'group', name: g.name, n: i.mid, dir: i.mine ? 'out' : 'in', at: i.received ?? i.iat }, textOf(i.content));
1082
1477
  }
1478
+ // Home groups' chats (the groups file's history).
1479
+ const hs = homeList().filter((g) => g.status !== 'joining' && (grp === null || g.gid === grp));
1480
+ for (const g of hs) {
1481
+ let msgs = [];
1482
+ try { msgs = G2.show({ carrier, file: groups2File, group: g.gid }).messages; } catch {}
1483
+ for (const m of msgs) if (typeof m.text === 'string' && !m.deleted) hit({ chat: g.gid, kind: 'group', name: g.name, n: m.mid, dir: m.mine ? 'out' : 'in', at: m.iat }, m.text);
1484
+ }
1083
1485
  }
1084
1486
  return { hits: hits.reverse().sort((a, b) => b.at - a.at).slice(0, lim) };
1085
1487
  }
@@ -1095,6 +1497,11 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1095
1497
  const of = q.get('of') ?? '';
1096
1498
  if (of !== 'me' && !isGroup(of)) contactOf(of);
1097
1499
  const key = picOf(of), bytes = key && data.pics[key] ? store.readPicture?.(picFile(key)) ?? null : null;
1500
+ // A home group's own picture (its admins', in the log: design/groups-build.md step 7) when none is set on this device.
1501
+ if (!bytes && G2 && groups2File && isHome(of)) {
1502
+ const a = G2.avatarOf({ carrier, file: groups2File, group: of });
1503
+ if (a) return { of, type: a.type, data: b64(a.bytes), rev: `a${a.sha256.slice(0, 16)}`, local: false };
1504
+ }
1098
1505
  if (!bytes) refuse(404, 'picture_none', 'no picture: the initial or the mark shows');
1099
1506
  return { of, type: data.pics[key].type, data: b64(bytes), rev: data.pics[key].rev, local: key.startsWith('l:') };
1100
1507
  },
@@ -1253,6 +1660,36 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1253
1660
  saveData(); changed();
1254
1661
  return { did: c.did, host: h, status: r.status };
1255
1662
  }),
1663
+ // The Session card (the header's): a folder listing, a new session (or in another folder), the login; the agent answers on the
1664
+ // same label. Only to an agent whose caps carry the session.
1665
+ 'POST /api/host/dirs': (b) => serial(async () => {
1666
+ const c = contactOf(b['contact']), h = hostSession(c), path = b['path'] ?? '', into = b['into'] ?? '';
1667
+ if (!isStr(path, 4096) || !isStr(into, 255) || /[\\/]/.test(into)) refuse(400, 'body', 'path: a folder of its computer; into: one folder name');
1668
+ const id = hexOf(6), r = await carrier.send(c.did, { path, ...(into !== '' && { into }), id }, { label: HOST_DIRS_LABEL });
1669
+ h.dirs_ask = { id, path, into, at: nowS() };
1670
+ saveData(); changed();
1671
+ return { did: c.did, id, status: r.status };
1672
+ }),
1673
+ 'POST /api/host/session': (b) => serial(async () => {
1674
+ const c = contactOf(b['contact']), h = hostSession(c), d = b['do'];
1675
+ if (d !== 'new' && d !== 'folder') refuse(400, 'body', 'do: new or folder');
1676
+ if (d === 'folder' && !(isStr(b['path'], 4096) && b['path'] !== '')) refuse(400, 'body', 'path: a folder of its computer');
1677
+ const r = await carrier.send(c.did, d === 'folder' ? { do: d, path: b['path'] } : { do: d }, { label: HOST_SESSION_LABEL });
1678
+ delete h.session_ev;
1679
+ saveData(); changed();
1680
+ return { did: c.did, host: h, status: r.status };
1681
+ }),
1682
+ 'POST /api/host/login': (b) => serial(async () => {
1683
+ const c = contactOf(b['contact']), h = hostSession(c), d = b['do'];
1684
+ if (d !== 'start' && d !== 'code' && d !== 'cancel') refuse(400, 'body', 'do: start, code or cancel');
1685
+ if (h.session.login.here === false) refuse(409, 'host_off', 'It signs in on its own computer');
1686
+ const code = d === 'code' ? String(b['code'] ?? '').replace(/\s+/g, '') : '';
1687
+ if (d === 'code' && !HOST_LOGIN_CODE.test(code)) refuse(400, 'body', 'That is not the code the sign-in page shows: one piece with a # in it');
1688
+ const r = await carrier.send(c.did, d === 'code' ? { do: d, code } : { do: d }, { label: HOST_LOGIN_LABEL });
1689
+ if (d === 'start') { delete h.login_ev; h.session.login = { ...h.session.login, state: 'signing_in' }; }
1690
+ saveData(); changed();
1691
+ return { did: c.did, host: h, status: r.status };
1692
+ }),
1256
1693
  // A contact's kind, the human's choice (Chat settings → "This is"): person, agent, desk, or null (the page decides again).
1257
1694
  'POST /api/kind': (b) => serial(async () => {
1258
1695
  const c = contactOf(b['contact']), k = b['kind'];
@@ -1263,7 +1700,7 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1263
1700
  }),
1264
1701
  // The keeper's settings and payment requests (UI-API.md "Keeper"): `sigelo-agent ui` answers them where the
1265
1702
  // keeper runs. Here, with hooks.computer (a computer of this operator paired to this profile, scope all;
1266
- // design/agent-wallet-page.md §4), they go to that computer, and a limit is changed by a policy-change this
1703
+ // UI-API.md "Computers"), they go to that computer, and a limit is changed by a policy-change this
1267
1704
  // page signs with its own identity: the computer carries it to its keeper and cannot alter it. Without one:
1268
1705
  // elsewhere, and the writes are refused keeper_elsewhere.
1269
1706
  'GET /api/keeper': async () => {
@@ -1330,10 +1767,13 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1330
1767
  const q = all.filter((x) => x.n < r.n && x.kind === kind && typeof x.text === 'string' && quoteHash(x.text) === m[1]).at(-1);
1331
1768
  return { n: q?.n ?? null, dir: kind, text: q ? q.text.split('\n')[0].slice(0, 120) : null };
1332
1769
  };
1770
+ // The first message new to this look (unread as state counts it: theirs, past the read mark, a call only missed),
1771
+ // read before the mark moves: the page opens the chat there ("New messages"). null: nothing was unread.
1772
+ const read = data.read[d] ?? 0, unreadFrom = all.find((r) => r.kind === 'in' && r.n > read && (!r.call || r.call.state === 'missed'))?.n ?? null;
1333
1773
  // Read: the page has shown them; a seen receipt when one is due (the header's).
1334
- if ((data.read[d] ?? 0) < seq) { data.read[d] = seq; saveData(); }
1774
+ if (read < seq) { data.read[d] = seq; saveData(); }
1335
1775
  receipt(d);
1336
- return { seq, messages: msgs.map((r) => ({ n: r.n, dir: r.kind, at: r.at, iat: r.iat ?? null, text: textOf(r.text), label: r.label ?? '', status: statusOf(r, x.seen_upto), code: r.code ?? null, detail: r.detail ?? null, link: r.link ?? null,
1776
+ return { seq, unread_from: unreadFrom, messages: msgs.map((r) => ({ n: r.n, dir: r.kind, at: r.at, iat: r.iat ?? null, text: textOf(r.text), label: r.label ?? '', status: statusOf(r, x.seen_upto), code: r.code ?? null, detail: r.detail ?? null, link: r.link ?? null,
1337
1777
  ...(RE_LABEL.test(r.label ?? '') && { re: reOf(r) }),
1338
1778
  ...(r.label === STATEMENT_LABEL && { statement: statementOf(r) }), ...(r.photo && { photo: r.photo }), ...(r.voice && { voice: r.voice }), ...(r.file && { file: r.file }), ...(r.call && { call: r.call }),
1339
1779
  ...(r.approval && { approval: r.approval }), ...(r.question && { question: r.question }) })) };
@@ -1358,7 +1798,7 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1358
1798
  'POST /api/notify': (b) => serial(async () => {
1359
1799
  const chat = b['chat'], on = b['on'];
1360
1800
  if (typeof on !== 'boolean') refuse(400, 'body', 'on: true or false');
1361
- const isGroup = typeof chat === 'string' && G && groupsFile && G.list({ carrier, file: groupsFile }).some((g) => g.gid === chat);
1801
+ const isGroup = typeof chat === 'string' && ((G && groupsFile && G.list({ carrier, file: groupsFile }).some((g) => g.gid === chat)) || isHome(chat));
1362
1802
  const id = isGroup ? chat : contactOf(chat).did;
1363
1803
  if (on) delete data.notify[id]; else data.notify[id] = false;
1364
1804
  saveData(); changed();
@@ -1366,11 +1806,13 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1366
1806
  }),
1367
1807
  // Settings: the relay new codes name (above). relay: a host[:port], or "" / null for relay.sigelo.ai.
1368
1808
  'GET /api/settings': () => settingsAll(),
1369
- // Any of: relay, seen_receipts, notify, new_tier, new_presence (Settings → Chats); wallet, prices, currency (Settings → Wallet); each checked before any is kept.
1809
+ // Any of: relay, seen_receipts, new_tier, new_presence (Settings → Chats); alerts (Settings → Notifications; notify, an
1810
+ // older page's switch: true → all, false → none); wallet, prices, currency (Settings → Wallet); each checked before any is kept.
1370
1811
  'POST /api/settings': (b) => serial(async () => {
1371
- const v = b['relay'], flags = ['seen_receipts', 'notify', 'new_presence', 'wallet', 'prices', 'calls', 'relay_media'].filter((k) => b[k] !== undefined), t = b['new_tier'], cur = b['currency'];
1372
- if (v === undefined && flags.length === 0 && t === undefined && cur === undefined) refuse(400, 'body', 'relay: a host[:port], or "" for the default (or seen_receipts, notify, new_tier, new_presence, wallet, prices, currency, calls, relay_media)');
1812
+ const v = b['relay'], flags = ['seen_receipts', 'notify', 'new_presence', 'wallet', 'prices', 'relay_media'].filter((k) => b[k] !== undefined), t = b['new_tier'], cur = b['currency'], al = b['alerts'];
1813
+ if (v === undefined && flags.length === 0 && t === undefined && cur === undefined && al === undefined) refuse(400, 'body', 'relay: a host[:port], or "" for the default (or seen_receipts, alerts, new_tier, new_presence, wallet, prices, currency, relay_media)');
1373
1814
  for (const k of flags) if (typeof b[k] !== 'boolean') refuse(400, 'body', `${k}: true or false`);
1815
+ if (al !== undefined && !ALERTS.includes(al)) refuse(400, 'body', 'alerts: all, people or none');
1374
1816
  if (t !== undefined && !TIER_NEW.has(t)) refuse(400, 'body', 'new_tier: own, friend or quiet');
1375
1817
  if (cur !== undefined && cur !== null && !CURRENCIES.includes(cur)) refuse(400, 'body', `currency: one of ${CURRENCIES.join(', ')}`);
1376
1818
  if (v === undefined) {} else if (v === null || v === '' || v === DEFAULT_RELAY) delete data.settings.relay;
@@ -1380,9 +1822,8 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1380
1822
  }
1381
1823
  else refuse(400, 'body', `relay: a host name, as relay.example.org (a port after a colon if not the usual)`);
1382
1824
  if (b['seen_receipts'] !== undefined) data.settings.seen = b['seen_receipts'];
1383
- if (b['notify'] !== undefined) data.settings.notify = b['notify'];
1825
+ if (al !== undefined || b['notify'] !== undefined) { data.settings.alerts = al ?? (b['notify'] ? 'all' : 'none'); delete data.settings.notify; }
1384
1826
  if (b['new_presence'] !== undefined) data.settings.new_presence = b['new_presence'];
1385
- if (b['calls'] !== undefined) data.settings.calls = b['calls'];
1386
1827
  if (b['relay_media'] !== undefined) data.settings.relay_media = b['relay_media'];
1387
1828
  if (t !== undefined) data.settings.new_tier = t;
1388
1829
  if (b['wallet'] !== undefined) data.settings.wallet = b['wallet'];
@@ -1451,7 +1892,7 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1451
1892
  changed();
1452
1893
  return pub(e);
1453
1894
  }),
1454
- // "Try now" (design/profiles.md §6): the automatic tries paused for the day; the human's goes now.
1895
+ // "Try now": the automatic tries paused for the day; the human's goes now.
1455
1896
  'POST /api/pow/try': (b) => serial(async () => {
1456
1897
  const r = await carrier.tryNow({ confirmed: b['pow_confirmed'] === true });
1457
1898
  live.powCapped = null; live.powConfirm = null; keepOffline(); changed();
@@ -1594,8 +2035,8 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1594
2035
  stun: (c) => stunOf(carrier.relay, c?.relay),
1595
2036
  turn: () => (globalThis.process?.env?.SIGELO_TURN === 'off' ? null : carrier.turnServer?.() ?? null), // SIGELO_TURN=off: STUN alone (the transfer engine reads it too)
1596
2037
  policy: relayMedia,
1597
- can: { speaker: typeof CH.speaker === 'function', mic: typeof CH.mic === 'function', ring: typeof CH.alert === 'function' },
1598
- hooks: { speaker: CH.speaker, mic: CH.mic, micSettings: CH.micSettings },
2038
+ can: { speaker: typeof CH.speaker === 'function', mic: typeof CH.mic === 'function', ring: typeof CH.alert === 'function', route: typeof CH.route === 'function' },
2039
+ hooks: { speaker: CH.speaker, mic: CH.mic, micSettings: CH.micSettings, route: CH.route },
1599
2040
  allow: (c, on) => { if (on === null) delete data.calls[c.did]; else data.calls[c.did] = on; saveData(); changed(); },
1600
2041
  allowOf: (c) => canCall(c),
1601
2042
  });
@@ -1627,6 +2068,15 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1627
2068
  };
1628
2069
  if (transfers) Object.assign(routes, transferRoutes({ X: transfers.lib, engine: transfers.engine, host: hooks.transfers, carrier, identity: hooks.transfers.identity, serial, contactOf, changed, record, groups: G && groupsFile ? { G, file: groupsFile, list: groupsList } : null }));
1629
2070
  if (G) Object.assign(routes, groupRoutes);
2071
+ // Home groups beside them: the list adds them; a shared route goes where homeAsked says.
2072
+ if (G2 && groups2File) {
2073
+ for (const [k, f] of Object.entries(homeRoutes)) { const g1 = routes[k]; routes[k] = g1 ? (b, q) => (homeAsked(k, b, q) ? f(b, q) : g1(b, q)) : f; }
2074
+ const g1List = routes['GET /api/groups'];
2075
+ routes['GET /api/groups'] = async (b, q) => {
2076
+ const r = g1List ? await g1List(b, q) : { tier: null, groups: [], notices: data.gnotices.slice() };
2077
+ return { ...r, groups: [...r.groups, ...homeList()], home: { relay: carrier.relay } };
2078
+ };
2079
+ }
1630
2080
  // One handler for every listener: the route's answer as [status, JSON value].
1631
2081
  async function dispatch(method, url, b) {
1632
2082
  const route = routes[`${method} ${url.pathname}`];
@@ -1689,7 +2139,7 @@ function transferRoutes({ X, engine, host, carrier, identity, serial, contactOf,
1689
2139
  'POST /api/transfers/send': (b) => serial(() => call(async () => {
1690
2140
  const vo = voiceOf(b), src = vo ? await host.rec.keep(recOf(b), vo.name) : sourceOf(b), d = directOf(b), via = viaOf(b), shot = shotOf(b);
1691
2141
  if (shot) { const p = { ...shot, sha256: '0'.repeat(64), size: 0, name: 'x' }; try { checkPhoto(p); } catch (e) { e.status = 400; throw e; } }
1692
- // A group (design §10.3): one transfer per member paired with; the preview (or a line naming the file) as one group message.
2142
+ // A group: one transfer per member paired with; the preview (or a line naming the file) as one group message.
1693
2143
  if (b['group'] !== undefined) {
1694
2144
  if (!groups) refuse(404, 'route', 'no groups here');
1695
2145
  const g = groups.list().find((x) => x.gid === b['group']) ?? refuse(404, 'group_unknown', `no group ${String(b['group'])} here`);
@@ -1724,8 +2174,8 @@ function transferRoutes({ X, engine, host, carrier, identity, serial, contactOf,
1724
2174
  }
1725
2175
  return strip(r);
1726
2176
  })),
1727
- // The phone's own: a file picked (the system's picker), a photo taken (the system's camera), a file that landed opened.
1728
- // images: the picker shows pictures only (the composer's Photo). multiple (2026-11-25): several at once → { docs: [...] },
2177
+ // From the phone itself: a file picked (the system's picker), a photo taken (the system's camera), a file that landed opened.
2178
+ // images: the picker shows pictures only (the composer's Photo). multiple: several at once → { docs: [...] },
1729
2179
  // each then sent as its own transfer (POST /api/transfers/send per doc, in order).
1730
2180
  ...(docs && { 'POST /api/transfers/pick': (b) => serial(async () => {
1731
2181
  const multiple = b?.['multiple'] === true, x = await host.pick({ images: b?.['images'] === true, ...(multiple && { multiple: true }) });