samagotchi 0.119.0 → 0.120.0

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 (65) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +66 -1
  3. data/bin/chi +6 -1
  4. data/docs/architecture.md +35 -5
  5. data/docs/cli.md +33 -8
  6. data/docs/configuration.md +45 -10
  7. data/docs/internals/participants.md +109 -12
  8. data/docs/internals/remote-sessions.md +6 -1
  9. data/docs/internals/web-push.md +4 -2
  10. data/docs/sessions.md +4 -3
  11. data/docs/testing.md +10 -1
  12. data/lib/samagotchi/answer_command.rb +2 -0
  13. data/lib/samagotchi/bridge.rb +56 -13
  14. data/lib/samagotchi/bridge_client/event_stream.rb +34 -3
  15. data/lib/samagotchi/bridge_client.rb +58 -19
  16. data/lib/samagotchi/bridge_secret.rb +35 -0
  17. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  18. data/lib/samagotchi/config.rb +3 -0
  19. data/lib/samagotchi/participant_messages.rb +5 -0
  20. data/lib/samagotchi/participants.rb +16 -6
  21. data/lib/samagotchi/review_command.rb +3 -1
  22. data/lib/samagotchi/run_options.rb +3 -1
  23. data/lib/samagotchi/session_access/contract.rb +4 -1
  24. data/lib/samagotchi/session_access/local.rb +15 -4
  25. data/lib/samagotchi/session_access/remote.rb +43 -7
  26. data/lib/samagotchi/session_access.rb +11 -1
  27. data/lib/samagotchi/session_manager.rb +1 -1
  28. data/lib/samagotchi/sessions_command.rb +1 -2
  29. data/lib/samagotchi/share_command.rb +29 -8
  30. data/lib/samagotchi/terminal_ui/attached_loop.rb +3 -0
  31. data/lib/samagotchi/terminal_ui/local_link.rb +18 -3
  32. data/lib/samagotchi/tools/delegate_relay.rb +4 -0
  33. data/lib/samagotchi/version.rb +1 -1
  34. data/lib/samagotchi/web/app.rb +117 -43
  35. data/lib/samagotchi/web/grants.rb +127 -16
  36. data/lib/samagotchi/web/link_codes.rb +24 -15
  37. data/lib/samagotchi/web/participant_access.rb +69 -13
  38. data/lib/samagotchi/web/participant_exposure.rb +44 -0
  39. data/lib/samagotchi/web/participant_review.rb +66 -8
  40. data/lib/samagotchi/web/participants_admin.rb +12 -6
  41. data/lib/samagotchi/web/proxy_gate.rb +18 -3
  42. data/lib/samagotchi/web/public/annotate_bar.css +18 -0
  43. data/lib/samagotchi/web/public/annotate_bar.js +10 -3
  44. data/lib/samagotchi/web/public/app.js +66 -155
  45. data/lib/samagotchi/web/public/composer.css +73 -0
  46. data/lib/samagotchi/web/public/composer_grip.js +21 -15
  47. data/lib/samagotchi/web/public/composer_mount.js +196 -0
  48. data/lib/samagotchi/web/public/index.html +7 -83
  49. data/lib/samagotchi/web/public/notifications.js +58 -8
  50. data/lib/samagotchi/web/public/participant.html +45 -10
  51. data/lib/samagotchi/web/public/participant.js +92 -18
  52. data/lib/samagotchi/web/public/participant_annotate.js +75 -0
  53. data/lib/samagotchi/web/public/participant_model.js +53 -1
  54. data/lib/samagotchi/web/public/participants_panel.js +34 -10
  55. data/lib/samagotchi/web/public/review_history.js +52 -0
  56. data/lib/samagotchi/web/public/scope.js +12 -8
  57. data/lib/samagotchi/web/public/stage_frame.js +9 -4
  58. data/lib/samagotchi/web/public/stage_view.js +4 -4
  59. data/lib/samagotchi/web/push/notifier.rb +17 -3
  60. data/lib/samagotchi/web/running.rb +7 -4
  61. data/lib/samagotchi/web/server.rb +34 -11
  62. data/lib/samagotchi/web/session_create.rb +7 -7
  63. data/lib/samagotchi/web/start_dir.rb +26 -0
  64. data/lib/samagotchi/worker_sidecar.rb +22 -11
  65. metadata +9 -1
@@ -4,14 +4,27 @@
4
4
  // GET /api/sessions/:id/review (the data) and the filtered stream; the
5
5
  // page re-reads its data at every turn boundary and draws the turn in
6
6
  // progress from the stream in between. A participant's comment is
7
- // POST …/turn (text only); their queued ones come back with Dequeue.
7
+ // POST …/turn (text only, always queued: a participant never steers); their
8
+ // queued ones come back with Dequeue. The comment box is the owner's
9
+ // composer (composer_mount.js) with a subset on: its height, grip and fold,
10
+ // ↑/↓ over this grant's own comments (review_history.js); no `/` list, no
11
+ // delivery choices, no images yet. Under it, the participant's own usage
12
+ // (spend vs cap, queue, link expiry, model). The owner's participant view
13
+ // mounts none.
8
14
  import {
9
15
  authorColor, participantAuthor, authorLabel, toolLine, toolsSummary, refusalText, dequeueText, endedText, streamURL, reloads, endsLiveTurn, liveFrom, applyLive,
10
- liveText, withToolSteps, pickSubject, subjectBody, subjectsKey, narrowView, retryDelay, retries, threadGaps,
16
+ liveText, withToolSteps, pickSubject, subjectBody, subjectsKey, narrowView, retryDelay, retries, threadGaps, usageItems,
11
17
  } from "./participant_model.js";
12
18
  import { fullTime } from "./format.js";
13
19
  import { createAuthLost, lostAnswer } from "./auth_lost.js";
14
20
  import { REPLACE_SESSION_TEXT, fragmentCode, tradeFragmentCode } from "./token_fragment.js";
21
+ import { createAnnotateBar } from "./annotate_bar.js";
22
+ import { parsePresets } from "./annotate_presets.js";
23
+ import { appendQuote } from "./annotations.js";
24
+ import { messageAuthorData, participantQuote, participantSource } from "./participant_annotate.js";
25
+ import { mountComposer } from "./composer_mount.js";
26
+ import { PROMPT_LINE_PX } from "./composer_size.js";
27
+ import { forgetReviewHistory, readReviewHistory, recordReviewComment } from "./review_history.js";
15
28
 
16
29
  // A link's #code= opened in a browser that already has a cookie: traded
17
30
  // first, the page reloads without it.
@@ -80,6 +93,8 @@ function showEnded(json) {
80
93
  if (ended) return;
81
94
  ended = true;
82
95
  source?.close();
96
+ // The link is over: its comments' ↑/↓ list goes with it.
97
+ forgetReviewHistory(data?.viewer?.id);
83
98
  for (const id of ["head", "main", "dock", "plan"]) $(id).hidden = true;
84
99
  $("endedText").textContent = endedText(json);
85
100
  $("ended").hidden = false;
@@ -218,6 +233,8 @@ function renderPlan() {
218
233
  }));
219
234
  $("planPath").textContent = subject.path;
220
235
  const doc = $("planDoc");
236
+ // An annotation's label names it (participant_annotate.js).
237
+ doc.dataset.path = subject.path;
221
238
  const shown = subjectBody(subject);
222
239
  doc.className = `p-doc${shown.kind === "html" ? "" : " plain"}`;
223
240
  // The server's rendered markdown (MarkdownRenderer: raw HTML escaped,
@@ -247,6 +264,8 @@ function messageNode(message) {
247
264
  if (when) node.title = when;
248
265
  if (user) {
249
266
  node.style.setProperty("--author-color", authorColor(message.author));
267
+ // Whose it is, for an annotation's label (participant_annotate.js).
268
+ Object.assign(node.dataset, messageAuthorData(message));
250
269
  const who = el("div", "p-who");
251
270
  who.append(el("b", "", authorLabel(message)));
252
271
  if (message.merged) who.append(el("span", "p-tag", "added mid-turn"));
@@ -403,8 +422,24 @@ function renderDock() {
403
422
  const send = $("send");
404
423
  const comment = $("comment");
405
424
  comment.disabled = !viewer.can_comment;
406
- send.disabled = !viewer.can_comment;
425
+ send.disabled = !viewer.can_comment || sending;
407
426
  comment.placeholder = viewer.cap_reached ? "Your spending cap is reached: ask the owner to raise it" : "Comment or ask";
427
+ renderUsage(viewer.usage);
428
+ }
429
+
430
+ // The participant's own usage, one line under the comment box (only what
431
+ // their grant's exposure shows; the server sends nothing else). Redrawn at
432
+ // every re-read: a turn's end, a queued or taken-back comment.
433
+ function renderUsage(usage) {
434
+ const items = usageItems(usage);
435
+ const row = $("usage");
436
+ row.hidden = items.length === 0;
437
+ row.replaceChildren(...items.map((item) => {
438
+ const span = el("span", [item.key === "model" ? "model" : "", item.level].filter(Boolean).join(" "), item.text);
439
+ span.dataset.key = item.key;
440
+ span.title = item.title;
441
+ return span;
442
+ }));
408
443
  }
409
444
 
410
445
  function showError(text) {
@@ -417,9 +452,8 @@ function showError(text) {
417
452
  // disabled Send button alone doesn't stop a second Enter.
418
453
  let sending = false;
419
454
 
420
- async function sendComment(event) {
421
- event.preventDefault();
422
- if (sending) return;
455
+ async function sendComment() {
456
+ if (sending || !data?.viewer?.can_comment) return;
423
457
  const comment = $("comment");
424
458
  const prompt = comment.value.trim();
425
459
  if (!prompt) return;
@@ -437,8 +471,11 @@ async function sendComment(event) {
437
471
  const { ok, status, body: json } = reply;
438
472
  if (ended) return;
439
473
  if (ok) {
474
+ recordReviewComment(data?.viewer?.id, prompt);
440
475
  comment.value = "";
441
- autosize();
476
+ composer.fit();
477
+ composer.drawFoldControls();
478
+ composer.refreshHistory();
442
479
  showError("");
443
480
  await load();
444
481
  } else {
@@ -460,25 +497,62 @@ async function dequeue(enqueuedId, button) {
460
497
  load();
461
498
  }
462
499
 
463
- function autosize() {
464
- const comment = $("comment");
465
- comment.style.height = "auto";
466
- comment.style.height = `${comment.scrollHeight + 2}px`;
500
+ // The comment box (composer_mount.js), a participant's only: the owner's
501
+ // participant view mounts none (its dock stays hidden). Enter or Send posts
502
+ // the comment: always a queued review turn, so Alt+Enter is Enter here.
503
+ const composer = ownerView ? null : mountComposer({
504
+ els: {
505
+ composer: $("composer"), prompt: $("comment"), button: $("send"), chips: $("chips"),
506
+ attachBtn: $("attachBtn"), attachInput: $("attachInput"), grip: $("composeGrip"),
507
+ },
508
+ minPx: () => PROMPT_LINE_PX,
509
+ toast: showError,
510
+ loadHistory: () => Promise.resolve(readReviewHistory(data?.viewer?.id)),
511
+ send: () => sendComment(),
512
+ imagesOff: "Images can't go in a review comment yet: describe what it shows, or ask the owner.",
513
+ fold: { session: () => sessionId || null },
514
+ });
515
+ if (composer) {
516
+ // The session composer's layout (composer.css), and the fold saved in this browser.
517
+ document.body.classList.add("has-session");
518
+ composer.newVisit();
467
519
  }
468
520
 
469
- $("compose").addEventListener("submit", sendComment);
470
521
  for (const button of $("viewSeg").querySelectorAll("button")) {
471
522
  button.addEventListener("click", () => {
472
523
  setView(button.dataset.view);
473
524
  if (button.dataset.view === "thread") $("main").scrollTop = $("main").scrollHeight;
474
525
  });
475
526
  }
476
- $("comment").addEventListener("input", autosize);
477
- $("comment").addEventListener("keydown", (event) => {
478
- if (event.key === "Enter" && !event.shiftKey && !event.isComposing) {
479
- event.preventDefault();
480
- $("compose").requestSubmit();
481
- }
527
+
528
+ // Annotate (annotate_bar.js, participant_annotate.js): a selection in the
529
+ // Plan or the thread offers "Annotate" and the presets
530
+ // (web.annotate_presets), which append a quote to the comment box; nothing
531
+ // is sent. No plugin pills: a review turn refuses `/` lines. Not in the
532
+ // owner's participant view, nor while this participant can't comment.
533
+ const annotateBar = createAnnotateBar({
534
+ presets: parsePresets(body.annotatePresets),
535
+ canAnnotate: () => !ownerView && !ended && !!data?.viewer?.can_comment,
536
+ roots: () => [$("planDoc"), $("thread")],
537
+ isLive: (root) => !!root.closest?.(".p-msg.live"),
538
+ onQuote: quoteIntoComment,
539
+ source: participantSource,
540
+ quote: participantQuote,
541
+ dock: () => $("dock"),
482
542
  });
543
+ $("main").addEventListener("scroll", annotateBar.schedule);
544
+ $("planScroll").addEventListener("scroll", annotateBar.schedule);
545
+
546
+ function quoteIntoComment(text) {
547
+ const comment = $("comment");
548
+ // A folded box opens for this visit (nothing saved).
549
+ composer.openForVisit();
550
+ comment.value = appendQuote(comment.value, text);
551
+ composer.fit();
552
+ composer.drawFoldControls();
553
+ comment.focus();
554
+ comment.setSelectionRange(comment.value.length, comment.value.length);
555
+ comment.scrollTop = comment.scrollHeight;
556
+ }
483
557
 
484
558
  load();
@@ -0,0 +1,75 @@
1
+ // Annotate on the participant page (participant.js): a selection in the
2
+ // Plan (the review's subject) or in the thread quotes it into the comment
3
+ // box, with where it came from, the way the owner's page does
4
+ // (annotations.js, annotate_bar.js):
5
+ //
6
+ // From docs/plan.md:
7
+ // > step 3
8
+ //
9
+ // Is step 3 safe?
10
+ //
11
+ // A model reply carries no label (the owner's answers carry none); a
12
+ // comment names its author ("From Alex's comment:", "From my earlier
13
+ // comment:"). Not annotatable: the reply still streaming, tool rows,
14
+ // status lines, time gaps, the header. The bar's source and quote options
15
+ // (createAnnotateBar); no DOM state beyond Element#closest, so it runs
16
+ // under `node --test` with stand-ins. A module of its own: static JS is
17
+ // cached at unversioned URLs, and a new export on an old module would
18
+ // blank the page.
19
+
20
+ import { quoteBlock } from "./annotations.js";
21
+
22
+ // Where a node on the participant page came from: { kind, root, … } where
23
+ // root is the element a selection is clipped to, or null.
24
+ // plan: { path } the subject shown (#planDoc's data-path)
25
+ // reply: a model reply's bubble
26
+ // comment: { by, name } a prompt's bubble; by is "me", "participant",
27
+ // "owner" or "automatic" (its .p-msg's data-by), name the
28
+ // participant's (data-name)
29
+ export function participantSource(node) {
30
+ const el = node && node.nodeType === 3 ? node.parentElement : node;
31
+ if (!el?.closest) return null;
32
+ const plan = el.closest("#planDoc");
33
+ if (plan) {
34
+ // The "only the first part is shown" note isn't the subject's text.
35
+ if (el.closest(".p-plan-note")) return null;
36
+ return { kind: "plan", path: plan.dataset?.path || "", root: plan };
37
+ }
38
+ const bubble = el.closest(".p-bubble");
39
+ const msg = bubble?.closest(".p-msg");
40
+ if (!msg || msg.classList.contains("live")) return null;
41
+ if (msg.classList.contains("reply")) return { kind: "reply", root: bubble };
42
+ if (msg.classList.contains("user")) {
43
+ return { kind: "comment", by: msg.dataset?.by || "owner", name: msg.dataset?.name || "", root: bubble };
44
+ }
45
+ return null;
46
+ }
47
+
48
+ // The line naming +source+ above the quote, or null (a reply).
49
+ export function participantLabel(source) {
50
+ if (source?.kind === "plan") return source.path ? `From ${source.path}:` : "From the plan:";
51
+ if (source?.kind !== "comment") return null;
52
+ if (source.by === "me") return "From my earlier comment:";
53
+ if (source.by === "participant") return `From ${source.name || "a participant"}'s comment:`;
54
+ if (source.by === "automatic") return "From the automatic turn:";
55
+ return "From the owner's message:";
56
+ }
57
+
58
+ // The quote block for the selected +text+ (annotations.js quoteBlock's
59
+ // lines) under +source+'s label; null when it holds no text.
60
+ export function participantQuote(text, source) {
61
+ const block = quoteBlock(text, { kind: "answer" });
62
+ if (!block) return null;
63
+ const label = participantLabel(source);
64
+ return label ? `${label}\n${block}` : block;
65
+ }
66
+
67
+ // What a message's .p-msg carries for participantSource: data-by and, for
68
+ // another participant, data-name. +message+ is a review message (the
69
+ // participant route's: mine, author, author_name, automatic).
70
+ export function messageAuthorData(message) {
71
+ if (message?.mine) return { by: "me" };
72
+ if (message?.author) return { by: "participant", name: message.author_name || "" };
73
+ if (message?.automatic) return { by: "automatic" };
74
+ return { by: "owner" };
75
+ }
@@ -3,7 +3,7 @@
3
3
  // refusal in words, the stream's URL, and the live turn as filtered events
4
4
  // build it (ParticipantView on the server decides what arrives at all).
5
5
 
6
- import { gapText } from "./format.js";
6
+ import { fullTime, gapText } from "./format.js";
7
7
 
8
8
  // A participant's author: "p:" and its grant id, as the server writes it
9
9
  // (Steer.author_for / PARTICIPANT_PREFIX): the one place the web spells it.
@@ -246,3 +246,55 @@ export function subjectsKey(subjects) {
246
246
  export function narrowView(wanted, subjects) {
247
247
  return wanted === "plan" && (subjects || []).length ? "plan" : "thread";
248
248
  }
249
+
250
+ // A participant's usage row (the review data's viewer.usage: the fields
251
+ // their grant's exposure shows, ParticipantExposure): one short item per
252
+ // field it has, each {key, text, title, level}; level "" / "warn" (most of
253
+ // the cap spent, the queue full) / "over" (the cap reached). Only the
254
+ // participant's own figures ever arrive; a field the level doesn't show is
255
+ // absent and draws nothing. [] with no usage (the owner's view).
256
+ export const USAGE_WARN = 0.8;
257
+ const MINUTE_MS = 60 * 1000;
258
+ const HOUR_MS = 60 * MINUTE_MS;
259
+ const DAY_MS = 24 * HOUR_MS;
260
+ const dollars = (n) => `$${(Number(n) || 0).toFixed(2)}`;
261
+ const isNum = (n) => typeof n === "number" && Number.isFinite(n);
262
+
263
+ // "6 d left", "5 h left", "12 min left", "ended"; "" for no or bad input.
264
+ export function leftText(iso, now = Date.now()) {
265
+ const at = Date.parse(iso || "");
266
+ if (!Number.isFinite(at)) return "";
267
+ const left = at - now;
268
+ if (left <= 0) return "ended";
269
+ if (left >= 2 * DAY_MS) return `${Math.round(left / DAY_MS)} d left`;
270
+ if (left >= 2 * HOUR_MS) return `${Math.floor(left / HOUR_MS)} h left`;
271
+ return `${Math.max(1, Math.floor(left / MINUTE_MS))} min left`;
272
+ }
273
+
274
+ export function usageItems(usage, now = Date.now()) {
275
+ if (!usage || typeof usage !== "object") return [];
276
+ const items = [];
277
+ if (isNum(usage.spent)) {
278
+ const cap = isNum(usage.cap) ? usage.cap : null;
279
+ const share = cap ? usage.spent / cap : 0;
280
+ const level = cap === null ? "" : usage.spent >= cap ? "over" : share >= USAGE_WARN ? "warn" : "";
281
+ items.push({ key: "spent", text: cap === null ? `${dollars(usage.spent)} spent` : `${dollars(usage.spent)} of ${dollars(cap)} cap`,
282
+ title: cap === null ? "What your comments have cost the owner so far"
283
+ : `What your comments have cost the owner so far, of the ${dollars(cap)} cap they set`, level });
284
+ }
285
+ if (isNum(usage.queued) && isNum(usage.queue_limit)) {
286
+ items.push({ key: "queued", text: `${usage.queued}/${usage.queue_limit} queued`,
287
+ title: `Your comments waiting for their turn: up to ${usage.queue_limit} can wait behind a running one`,
288
+ level: usage.queued >= usage.queue_limit ? "warn" : "" });
289
+ }
290
+ const left = leftText(usage.expires_at, now);
291
+ if (left) {
292
+ const day = Date.parse(usage.expires_at) - now < DAY_MS;
293
+ items.push({ key: "expires_at", text: left === "ended" ? "link ended" : `link: ${left}`,
294
+ title: `Your link ends ${fullTime(usage.expires_at)}`, level: day ? "warn" : "" });
295
+ }
296
+ if (typeof usage.model === "string" && usage.model) {
297
+ items.push({ key: "model", text: usage.model, title: "The model answering in this session", level: "" });
298
+ }
299
+ return items;
300
+ }
@@ -2,7 +2,9 @@
2
2
  // bar's chip (how many, someone here now) and its popover, the panel: each
3
3
  // participant's state, expiry, spend against their cap, turns and when they
4
4
  // were last seen, with Revoke and a new cap; Invite (name, person or agent,
5
- // expiry, cap) gives the link once, to copy, share (a phone's share sheet)
5
+ // expiry, cap, and behind an auth proxy that names the signed-in user their
6
+ // email, which binds the link to that account) gives the link once, to
7
+ // copy, share (a phone's share sheet)
6
8
  // or scan (its QR); and the participant view, the participant page as a
7
9
  // participant sees this session (through the server's filter), in a new
8
10
  // tab. The panel reads GET /api/sessions/:id/participants, again after
@@ -61,6 +63,7 @@ export function rowModel(grant, now) {
61
63
  id: grant.id,
62
64
  name: grant.name,
63
65
  kind: grant.kind,
66
+ identity: typeof grant.identity === "string" ? grant.identity : null,
64
67
  active,
65
68
  present,
66
69
  color: authorColor(participantAuthor(grant.id)),
@@ -98,12 +101,21 @@ export function chipTemplate(chip) {
98
101
  title=${chip.title} aria-label=${chip.title} aria-haspopup="dialog"><span class="pc-dot" aria-hidden="true"></span>${chip.text}</button>`;
99
102
  }
100
103
 
101
- // What POST …/participants gets from the Invite form's values.
104
+ // An email as chi binds a link to it (Grants.clean_identity, which has the
105
+ // last word): one @, no spaces, commas, quotes or angle brackets.
106
+ const EMAIL_RE = /^[^@\s,<>"\\]+@[^@\s,<>"\\]+$/;
107
+
108
+ // What POST …/participants gets from the Invite form's values. +identity+
109
+ // (behind a proxy that names the user): their email, which binds the link;
110
+ // the name defaults to its local part.
102
111
  // @return {{body}|{error}}
103
- export function inviteBody({ name, kind, days, cap }) {
104
- const clean = String(name || "").trim();
112
+ export function inviteBody({ name, kind, days, cap, identity }) {
113
+ const email = String(identity || "").trim().toLowerCase();
114
+ if (email && !EMAIL_RE.test(email)) return { error: "An email is one address: name@domain." };
115
+ const clean = String(name || "").trim() || email.split("@")[0];
105
116
  if (!clean) return { error: "Give them a name: it is what the model and the thread show." };
106
117
  const body = { name: clean, kind: kind === "agent" ? "agent" : "human" };
118
+ if (email) body.identity = email;
107
119
  const d = Number(days);
108
120
  body.ttl = Math.round((EXPIRY_DAYS.includes(d) ? d : DEFAULT_EXPIRY_DAYS) * 24 * 60 * 60);
109
121
  const capText = String(cap ?? "").trim();
@@ -138,13 +150,14 @@ function rowTemplate(row, { capFor }) {
138
150
  <div class="pp-who"><span class=${`pp-dot${row.present ? " present" : ""}`} aria-hidden="true"></span><b>${row.name}</b>${
139
151
  row.kind === "agent" ? html`<span class="pp-tag">agent</span>` : nothing}<span class="pp-state">${row.state}</span></div>
140
152
  <div class="pp-meta"><span class=${row.capReached ? "pp-capped" : ""}>${row.spend}</span> · ${row.turns}${
141
- row.expires ? html` · ${row.expires}` : nothing}</div>${actions}</li>`;
153
+ row.expires ? html` · ${row.expires}` : nothing}${row.identity ? html` · <span class="pp-bound">bound to ${row.identity}</span>` : nothing}</div>${actions}</li>`;
142
154
  }
143
155
 
144
156
  function inviteTemplate(invite, { canShare }) {
145
157
  if (!invite) return nothing;
146
158
  return html`<div class="pp-invite-done">
147
- <div class="ctx-pop-meta">${invite.name}'s link: shown once (chi keeps only its digest). It opens this session only.${
159
+ <div class="ctx-pop-meta">${invite.name}'s link: shown once (chi keeps only its digest). It opens this session only${
160
+ invite.identity ? `, for ${invite.identity} only` : ""}.${
148
161
  invite.lan ? nothing : " This chi web has no LAN address: the link opens on this machine only."}</div>
149
162
  ${invite.warning ? html`<div class="pp-warning" role="note">${invite.warning}</div>` : nothing}
150
163
  <div class="pp-link"><input readonly .value=${invite.link} aria-label="The review link" @focus=${(e) => e.target.select()}><button
@@ -157,8 +170,11 @@ function inviteTemplate(invite, { canShare }) {
157
170
  // gave), the participant view.
158
171
  // +working+: the server's warning for a session that isn't a review session
159
172
  // (shown before the Invite, with Start a review of it), null for one.
173
+ // +identityHeader+: the header chi web's auth proxy names the signed-in
174
+ // user in (the list's identity_header), null without one: then the Invite
175
+ // has no email field (a bound link could never open).
160
176
  export function panelTemplate(grants, { now, sessionId, invite = null, error = null, capFor = null, canShare = false,
161
- busy = false, working = null, reviewing = false } = {}) {
177
+ busy = false, working = null, reviewing = false, identityHeader = null } = {}) {
162
178
  const rows = (grants || []).map((g) => rowModel(g, now));
163
179
  const active = rows.filter((row) => row.active);
164
180
  const ended = rows.filter((row) => !row.active);
@@ -174,6 +190,10 @@ export function panelTemplate(grants, { now, sessionId, invite = null, error = n
174
190
  ${invite ? inviteTemplate(invite, { canShare }) : html`<form class="pp-invite">
175
191
  <div class="pp-invite-row"><input name="name" type="text" placeholder="Name (Alex)" autocomplete="off" aria-label="Their name" maxlength="64"
176
192
  ><select name="kind" aria-label="A person or an agent"><option value="human">person</option><option value="agent">agent</option></select></div>
193
+ ${identityHeader ? html`<div class="pp-invite-row"><input name="identity" type="email" placeholder="Their email (alex@example.com)"
194
+ autocomplete="off" aria-label="Their email: the link opens only for that account"></div>
195
+ <div class="ctx-pop-meta pp-bind-note">With their email the link opens only for them, signed in through the proxy.
196
+ Without one, anyone the proxy lets in who gets the link can open it.</div>` : nothing}
177
197
  <div class="pp-invite-row"><label>Expires <select name="days">${EXPIRY_DAYS.map((d) => html`<option value=${d}
178
198
  ?selected=${d === DEFAULT_EXPIRY_DAYS}>${d === 1 ? "1 day" : `${d} days`}</option>`)}</select></label
179
199
  ><label>Cap $<input name="cap" type="text" inputmode="decimal" placeholder="2" autocomplete="off" aria-label="Spending cap, dollars"></label
@@ -198,6 +218,9 @@ export function createParticipantsControl({ el, session, api, onChange = () => {
198
218
  // The open session's share warning (GET …/participants), null for a
199
219
  // review session.
200
220
  let working = null;
221
+ // The header chi web's proxy names the user in (GET …/participants), null
222
+ // without one: the Invite's email field.
223
+ let identityHeader = null;
201
224
  let loadedFor = null;
202
225
  let invite = null;
203
226
  let error = null;
@@ -230,7 +253,7 @@ export function createParticipantsControl({ el, session, api, onChange = () => {
230
253
 
231
254
  function draw() {
232
255
  render(panelTemplate(grants, { now: clock(), sessionId: session(), invite, error, capFor, busy,
233
- working: startReview ? working : null, reviewing: reviewing(),
256
+ working: startReview ? working : null, reviewing: reviewing(), identityHeader,
234
257
  canShare: typeof win.navigator?.share === "function" }), shell.pop);
235
258
  shell.replace();
236
259
  }
@@ -249,6 +272,7 @@ export function createParticipantsControl({ el, session, api, onChange = () => {
249
272
  if (id !== session()) return;
250
273
  grants = Array.isArray(body.participants) ? body.participants : [];
251
274
  working = typeof body.warning === "string" ? body.warning : null;
275
+ identityHeader = typeof body.identity_header === "string" && body.identity_header ? body.identity_header : null;
252
276
  loadedFor = id;
253
277
  if (setParticipantNames(grants)) onNames();
254
278
  } catch {
@@ -265,7 +289,7 @@ export function createParticipantsControl({ el, session, api, onChange = () => {
265
289
  }
266
290
 
267
291
  async function submitInvite(form) {
268
- const values = Object.fromEntries(["name", "kind", "days", "cap"].map((k) => [k, form.elements[k]?.value]));
292
+ const values = Object.fromEntries(["name", "kind", "days", "cap", "identity"].map((k) => [k, form.elements[k]?.value]));
269
293
  const { body, error: problem } = inviteBody(values);
270
294
  if (problem) {
271
295
  error = problem;
@@ -278,7 +302,7 @@ export function createParticipantsControl({ el, session, api, onChange = () => {
278
302
  const answer = await api.invite(asked.id, body);
279
303
  if (!stillOpen(asked)) return dropped(asked);
280
304
  invite = { name: answer.participant?.name || body.name, link: answer.link, qr_svg: answer.qr_svg, lan: answer.lan,
281
- warning: answer.warning || null, copied: false };
305
+ warning: answer.warning || null, identity: answer.participant?.identity || null, copied: false };
282
306
  error = null;
283
307
  } catch (err) {
284
308
  if (!stillOpen(asked)) return dropped(asked);
@@ -0,0 +1,52 @@
1
+ // A participant's ↑/↓ in the comment box (participant.js over
2
+ // prompt_history.js): their own comments sent from this browser, newest
3
+ // last, in localStorage under one key per grant, never the owner's GET
4
+ // /api/history (the owner may open a link in the same browser, on the same
5
+ // origin: each grant's list and the owner's stay apart). Read and written
6
+ // through storage.js (guarded): a list that can't be read or written is just
7
+ // not there. A link that ends forgets its list.
8
+ import { readStored, removeStored, writeStored } from "./storage.js";
9
+
10
+ export const REVIEW_HISTORY_PREFIX = "chi_review_history:";
11
+ // How many comments a grant's list keeps (the oldest go first).
12
+ export const REVIEW_HISTORY_MAX = 50;
13
+
14
+ // The key for grant +grantId+'s list; null without one (an older server's
15
+ // review data): no history then.
16
+ export function reviewHistoryKey(grantId) {
17
+ return grantId ? `${REVIEW_HISTORY_PREFIX}${grantId}` : null;
18
+ }
19
+
20
+ // The grant's comments, oldest first; [] when there are none or they can't
21
+ // be read.
22
+ export function readReviewHistory(grantId) {
23
+ const key = reviewHistoryKey(grantId);
24
+ if (!key) return [];
25
+ try {
26
+ const list = JSON.parse(readStored(key, "[]"));
27
+ return Array.isArray(list) ? list.filter((entry) => typeof entry === "string") : [];
28
+ } catch (_) {
29
+ return [];
30
+ }
31
+ }
32
+
33
+ // The list with +text+ added at the end (not twice in a row), at most
34
+ // REVIEW_HISTORY_MAX long. Pure.
35
+ export function withComment(list, text) {
36
+ const entry = String(text || "").trim();
37
+ if (!entry) return list;
38
+ const next = list.at(-1) === entry ? list : [...list, entry];
39
+ return next.slice(-REVIEW_HISTORY_MAX);
40
+ }
41
+
42
+ // A comment the server took: saved at the end of the grant's list.
43
+ export function recordReviewComment(grantId, text) {
44
+ const key = reviewHistoryKey(grantId);
45
+ if (!key) return;
46
+ writeStored(key, JSON.stringify(withComment(readReviewHistory(grantId), text)));
47
+ }
48
+
49
+ export function forgetReviewHistory(grantId) {
50
+ const key = reviewHistoryKey(grantId);
51
+ if (key) removeStored(key);
52
+ }
@@ -1,6 +1,9 @@
1
1
  // The page's scope: ?dir=<folder> shows that folder's project (`chi web` in
2
- // a repo opens it so); no dir shows every session. The hash routes
3
- // (#/s/<id>, #/sessions) work in either.
2
+ // a repo opens it so); ?scope=all shows every session. A bare page is chi
3
+ // web's start folder's project when that folder is in a repo (the server
4
+ // names it in data-scope-dir; web.start_dir, --start-dir), else every
5
+ // session. ?dir= beats ?scope=all. The hash routes (#/s/<id>, #/sessions)
6
+ // work in each.
4
7
  import { html, nothing } from "./vendor/lit-html.js";
5
8
 
6
9
  // The ?dir= folder in a location.search string, or null.
@@ -9,13 +12,14 @@ export function scopeDir(search) {
9
12
  return dir && dir.trim() ? dir : null;
10
13
  }
11
14
 
12
- // The same place in the all view: the page without ?dir, keeping the hash.
13
- // +fromDir+ (the project view's folder) rides along as ?from=, so the all
14
- // view can link back to it. +search+ (the page's location.search) keeps
15
- // its ?view= (VIEW_PARAM) on the new page.
15
+ // The same place in the all view: ?scope=all without ?dir (a bare page
16
+ // may be the start folder's project), keeping the hash. +fromDir+ (the
17
+ // project view's folder) rides along as ?from=, so the all view can link
18
+ // back to it. +search+ (the page's location.search) keeps its ?view=
19
+ // (VIEW_PARAM) on the new page.
16
20
  export function allScopeHref(hash, fromDir = null, search = "") {
17
- const params = [fromDir ? `from=${dirParam(fromDir)}` : "", viewParam(search)].filter(Boolean);
18
- return `/${params.length ? `?${params.join("&")}` : ""}${hash || ""}`;
21
+ const params = ["scope=all", fromDir ? `from=${dirParam(fromDir)}` : "", viewParam(search)].filter(Boolean);
22
+ return `/?${params.join("&")}${hash || ""}`;
19
23
  }
20
24
 
21
25
  // A folder's project view, keeping the hash and +search+'s ?view=.
@@ -28,7 +28,7 @@ export function reducedMotion() {
28
28
 
29
29
  // +observed+: the elements whose size changes refit the frame (the stage's
30
30
  // slots, in the order they are observed).
31
- export function createStageFrame({ stage, scroller, status, cloud, queuedSlot, holdEl, asking, extras, dockEl, centerEl, composerEl, observed, isHolding, isCollapsed, isCloudOpen, isRoomCap = () => false }) {
31
+ export function createStageFrame({ stage, scroller, status, cloud, queuedSlot, holdEl, asking, extras, dockEl, centerEl, observed, isHolding, isCollapsed, isCloudOpen, isRoomCap = () => false }) {
32
32
  // The frame (fitFrame): the height held while the turn runs and the
33
33
  // tallest content seen.
34
34
  let held = null;
@@ -71,11 +71,13 @@ export function createStageFrame({ stage, scroller, status, cloud, queuedSlot, h
71
71
  }
72
72
 
73
73
  // Scrolls the stage to show +slot+: eased, or at once (+now+: the cap
74
- // dropped under it). +fromStart+: revealTop's.
74
+ // dropped under it; a running ease stops, or its next frame would take
75
+ // the scroll back toward its target for the taller stage). +fromStart+:
76
+ // revealTop's.
75
77
  function reveal(slot, { now = false, fromStart = false } = {}) {
76
78
  const top = revealTop(slot, { fromStart });
77
79
  if (top === null) return;
78
- if (now) scroller.scrollTop = top;
80
+ if (now) easeScrollTo(scroller, top, { reduce: true });
79
81
  else easeStage(top);
80
82
  }
81
83
 
@@ -98,8 +100,11 @@ export function createStageFrame({ stage, scroller, status, cloud, queuedSlot, h
98
100
  requestAnimationFrame(() => reveal(extras, { now: true }));
99
101
  }
100
102
  }
103
+ // The whole dock, not only its composer card: the info bar under it
104
+ // fills and wraps after a load (the session's facts arrive), and a cap
105
+ // read before that would stay above the panel.
101
106
  new ResizeObserver(() => fitCap()).observe(centerEl);
102
- new ResizeObserver(() => fitCap()).observe(composerEl);
107
+ new ResizeObserver(() => fitCap()).observe(dockEl);
103
108
  window.addEventListener("resize", fitCap);
104
109
 
105
110
  // ── the frame: the one place that writes the stage's height ────────────
@@ -52,15 +52,15 @@ function readCollapsed() {
52
52
  }
53
53
 
54
54
  // +historyNearBottom+: the history's own follow check (the hand-off scrolls
55
- // the history only for a reader at its end). +dockEl+, +centerEl+ and
56
- // +composerEl+ size the stage's cap.
55
+ // the history only for a reader at its end). +dockEl+ and +centerEl+ size
56
+ // the stage's cap.
57
57
  // +taskStop+: the page's stopper (task_stop.js), for the stop-task button
58
58
  // on a running task_wait. +renderMarkdown+ and +linkRefs+: the asking
59
59
  // slot's markdown read and ref pass (stage_slots.js). +workingSet+: the
60
60
  // page's working set (working_set_view.js, web.working_set; null: off): its
61
61
  // rail in the live slots, its footprint at the hand-off.
62
62
  export function createStageView({
63
- historyEl, appendToHistory, isNearBottom: historyNearBottom, sawText, sessionId, dockEl, centerEl, composerEl, taskStop = null,
63
+ historyEl, appendToHistory, isNearBottom: historyNearBottom, sawText, sessionId, dockEl, centerEl, taskStop = null,
64
64
  renderMarkdown, linkRefs, workingSet = null,
65
65
  }) {
66
66
  // The dock becomes a clear column: the stage's card, then the composer's
@@ -521,7 +521,7 @@ export function createStageView({
521
521
  // The cap and the frame (stage_frame.js): the stage's height, held while
522
522
  // it holds a turn, and its own scrolls.
523
523
  const frame = createStageFrame({
524
- stage, scroller, status, cloud, queuedSlot, holdEl, asking, extras, dockEl, centerEl, composerEl,
524
+ stage, scroller, status, cloud, queuedSlot, holdEl, asking, extras, dockEl, centerEl,
525
525
  observed: [status, promptSlot, live, extras, answer, tail, cloudBody, cloud, queuedSlot],
526
526
  isHolding: () => holding,
527
527
  isCollapsed: () => collapsed,