samagotchi 0.121.0 → 0.122.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 (127) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +110 -1
  3. data/bin/chi +7 -3
  4. data/docs/architecture.md +37 -11
  5. data/docs/bundle-authoring.md +2 -1
  6. data/docs/cli.md +11 -4
  7. data/docs/configuration.md +36 -7
  8. data/docs/guardrails.md +63 -19
  9. data/docs/internals/anthropic.md +1 -1
  10. data/docs/internals/background-tasks.md +1 -1
  11. data/docs/internals/engine.md +2 -0
  12. data/docs/internals/participants.md +16 -8
  13. data/docs/internals/remote-sessions.md +15 -11
  14. data/docs/internals/web-push.md +22 -11
  15. data/docs/memory.md +33 -0
  16. data/docs/plugins.md +8 -3
  17. data/docs/sessions.md +21 -0
  18. data/docs/testing.md +41 -1
  19. data/lib/samagotchi/answer_command.rb +1 -1
  20. data/lib/samagotchi/bridge/turn_accumulator.rb +3 -1
  21. data/lib/samagotchi/bridge.rb +12 -11
  22. data/lib/samagotchi/bridge_client/event_stream.rb +14 -26
  23. data/lib/samagotchi/bridge_client/stream_open.rb +85 -0
  24. data/lib/samagotchi/bridge_client/stream_request.rb +8 -2
  25. data/lib/samagotchi/bridge_client.rb +52 -65
  26. data/lib/samagotchi/bridge_secret.rb +9 -7
  27. data/lib/samagotchi/bundle_command/check.rb +27 -2
  28. data/lib/samagotchi/bundles/claude-peer/manifest.yml +2 -2
  29. data/lib/samagotchi/bundles/claude-peer/scripts/pair +20 -6
  30. data/lib/samagotchi/bundles/codex-peer/manifest.yml +2 -2
  31. data/lib/samagotchi/bundles/codex-peer/scripts/pair +14 -3
  32. data/lib/samagotchi/bundles/github-pr/manifest.yml +2 -2
  33. data/lib/samagotchi/bundles/github-pr/plugin.rb +2 -6
  34. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  35. data/lib/samagotchi/bundles/system/memory_guide.md +13 -0
  36. data/lib/samagotchi/child_move.rb +5 -7
  37. data/lib/samagotchi/children_status.rb +2 -1
  38. data/lib/samagotchi/config.rb +5 -0
  39. data/lib/samagotchi/engine.rb +107 -1
  40. data/lib/samagotchi/event_fanout.rb +0 -1
  41. data/lib/samagotchi/guardrail_wiring.rb +24 -6
  42. data/lib/samagotchi/guardrails/parent_approvals.rb +9 -0
  43. data/lib/samagotchi/guardrails_command.rb +41 -6
  44. data/lib/samagotchi/image_store.rb +6 -3
  45. data/lib/samagotchi/interrupted_turn.rb +6 -3
  46. data/lib/samagotchi/live_versions.rb +6 -7
  47. data/lib/samagotchi/log_line.rb +1 -1
  48. data/lib/samagotchi/memory_bundle/profile.rb +1 -1
  49. data/lib/samagotchi/memory_bundle/uninstaller.rb +6 -2
  50. data/lib/samagotchi/memory_orphans.rb +11 -0
  51. data/lib/samagotchi/participant_mode.rb +11 -0
  52. data/lib/samagotchi/plugin/api.rb +14 -8
  53. data/lib/samagotchi/plugin/sessions.rb +13 -4
  54. data/lib/samagotchi/process_group.rb +13 -0
  55. data/lib/samagotchi/push_command.rb +1 -1
  56. data/lib/samagotchi/relay_verifier.rb +2 -3
  57. data/lib/samagotchi/relay_watcher.rb +2 -2
  58. data/lib/samagotchi/remote_attach_command.rb +1 -1
  59. data/lib/samagotchi/reply_wait/poll.rb +8 -2
  60. data/lib/samagotchi/reply_wait.rb +4 -3
  61. data/lib/samagotchi/review_command.rb +1 -1
  62. data/lib/samagotchi/review_start.rb +6 -2
  63. data/lib/samagotchi/run_options.rb +2 -0
  64. data/lib/samagotchi/session.rb +18 -1
  65. data/lib/samagotchi/session_access/contract.rb +1 -1
  66. data/lib/samagotchi/session_access/local.rb +18 -8
  67. data/lib/samagotchi/session_access/remote.rb +37 -12
  68. data/lib/samagotchi/session_access/web_bridge_client.rb +38 -19
  69. data/lib/samagotchi/session_access.rb +21 -9
  70. data/lib/samagotchi/session_continue.rb +2 -3
  71. data/lib/samagotchi/session_manager.rb +133 -29
  72. data/lib/samagotchi/session_setup.rb +8 -4
  73. data/lib/samagotchi/sessions_command.rb +10 -5
  74. data/lib/samagotchi/steer.rb +7 -6
  75. data/lib/samagotchi/system_one/client.rb +12 -6
  76. data/lib/samagotchi/system_one/fake_backend.rb +0 -2
  77. data/lib/samagotchi/system_one/log.rb +44 -9
  78. data/lib/samagotchi/system_one/self_protect.rb +39 -43
  79. data/lib/samagotchi/terminal_ui/attach_launcher.rb +8 -3
  80. data/lib/samagotchi/terminal_ui/attached_loop.rb +4 -2
  81. data/lib/samagotchi/terminal_ui/local_link.rb +28 -19
  82. data/lib/samagotchi/terminal_ui.rb +2 -1
  83. data/lib/samagotchi/tool_runner.rb +2 -1
  84. data/lib/samagotchi/toolkit.rb +95 -10
  85. data/lib/samagotchi/toolkit_binding.rb +115 -7
  86. data/lib/samagotchi/toolkit_command.rb +15 -3
  87. data/lib/samagotchi/toolkit_report_command.rb +318 -0
  88. data/lib/samagotchi/toolkit_suggest.rb +211 -0
  89. data/lib/samagotchi/tools/delegate.rb +1 -1
  90. data/lib/samagotchi/tools/delegate_relay.rb +9 -7
  91. data/lib/samagotchi/tools/memory.rb +1 -1
  92. data/lib/samagotchi/turn_checkpoint.rb +15 -9
  93. data/lib/samagotchi/version.rb +1 -1
  94. data/lib/samagotchi/web/app.rb +127 -69
  95. data/lib/samagotchi/web/participant_access.rb +30 -8
  96. data/lib/samagotchi/web/participant_review.rb +8 -5
  97. data/lib/samagotchi/web/participant_view.rb +7 -3
  98. data/lib/samagotchi/web/participants_admin.rb +13 -0
  99. data/lib/samagotchi/web/principal.rb +3 -4
  100. data/lib/samagotchi/web/public/app.js +1 -1
  101. data/lib/samagotchi/web/public/bubbles.js +3 -2
  102. data/lib/samagotchi/web/public/notifications.js +21 -1
  103. data/lib/samagotchi/web/public/participant.html +3 -2
  104. data/lib/samagotchi/web/public/participant.js +25 -10
  105. data/lib/samagotchi/web/public/participants_panel.js +46 -11
  106. data/lib/samagotchi/web/public/push.js +4 -3
  107. data/lib/samagotchi/web/public/push_devices.js +17 -3
  108. data/lib/samagotchi/web/public/review_history.js +14 -2
  109. data/lib/samagotchi/web/public/review_start.js +1 -3
  110. data/lib/samagotchi/web/public/session_actions.js +14 -2
  111. data/lib/samagotchi/web/public/storage.js +16 -0
  112. data/lib/samagotchi/web/public/turn_events.js +2 -1
  113. data/lib/samagotchi/web/public/turn_html.js +1 -1
  114. data/lib/samagotchi/web/push/client.rb +5 -0
  115. data/lib/samagotchi/web/push/store.rb +16 -3
  116. data/lib/samagotchi/web/push_routes.rb +3 -2
  117. data/lib/samagotchi/web/server.rb +2 -2
  118. data/lib/samagotchi/web/session_access_routes.rb +28 -20
  119. data/lib/samagotchi/web/session_control.rb +4 -2
  120. data/lib/samagotchi/web/session_create.rb +4 -4
  121. data/lib/samagotchi/web/session_hub.rb +6 -4
  122. data/lib/samagotchi/web/session_summary.rb +8 -16
  123. data/lib/samagotchi/web/start_dir.rb +10 -5
  124. data/lib/samagotchi/worker.rb +17 -3
  125. data/lib/samagotchi/worker_link.rb +214 -0
  126. data/lib/samagotchi/worker_sidecar.rb +15 -37
  127. metadata +6 -1
@@ -173,7 +173,7 @@ const participantsControl = createParticipantsControl({
173
173
  // An older prompt drawn before the list came says "a participant": named now.
174
174
  onNames: () => nameUnnamedBadges(document),
175
175
  onChange: () => updateInfoBar(),
176
- toast: (text) => showToast(text),
176
+ toast: (text, action, options) => showToast(text, action, options),
177
177
  });
178
178
  // The start page's model picker and its LLM context and thinking chips
179
179
  // (start_page.js); a fresh chain link's picker too.
@@ -160,9 +160,9 @@ export function createBubbles({
160
160
  // The bubble a reload draws (turn_html.js), with this page's own fields.
161
161
  // +delivery+: how it went into a running turn (next_step, cut, queue): its
162
162
  // queued badge says what it waits for.
163
- function makeUserBubble(prompt, { state = null, label = null, enqueuedId = null, own = false, images = null, delivery = null, author = null } = {}) {
163
+ function makeUserBubble(prompt, { state = null, label = null, enqueuedId = null, own = false, images = null, delivery = null, author = null, turnId = null } = {}) {
164
164
  removeHint();
165
- const div = elementOf(userBubbleTemplate({ content: prompt }, {
165
+ const div = elementOf(userBubbleTemplate({ content: prompt, turn_id: turnId }, {
166
166
  label, state, own, enqueuedId, delivery, author, key: normalize(prompt), thumbs: thumbsTemplate(selected(), images),
167
167
  }));
168
168
  return placeFollowing(div);
@@ -224,6 +224,7 @@ export function createBubbles({
224
224
  else liveTurn.unmatchedMerge = true;
225
225
  }
226
226
  }
227
+ if (started && event.type === "turn_started" && event.turn_id) started.dataset.turnId = event.turn_id;
227
228
  return started;
228
229
  }
229
230
 
@@ -154,6 +154,11 @@ export function createNotifications({
154
154
  let syncAgain = false;
155
155
  // When this page last had the browser check for a newer sw.js.
156
156
  let swCheckedAt = null;
157
+ // startPush's run in flight, and whether the last one failed (GET
158
+ // /api/push while chi web restarts, a phone just woken): the page tries
159
+ // again when it comes back in front.
160
+ let pushStarting = null;
161
+ let pushFailed = false;
157
162
  const badgeKeys = new Set();
158
163
  let baseTitle = "Chi";
159
164
 
@@ -258,8 +263,10 @@ export function createNotifications({
258
263
 
259
264
  // The Home Screen app: its service worker, chi web's key, and whether
260
265
  // chi web has this device. A tab, or chi web without push: the bell as is.
266
+ // One that failed is run again by backInFront (retryPush).
261
267
  async function startPush() {
262
268
  if (typeof NotificationApi !== "function" || !pushSupported({ win, nav })) return;
269
+ pushFailed = false;
263
270
  try {
264
271
  const reg = await nav.serviceWorker.register("/sw.js", { scope: "/" });
265
272
  const sub = await reg.pushManager.getSubscription();
@@ -274,11 +281,20 @@ export function createNotifications({
274
281
  // register() has just checked for a newer sw.js.
275
282
  swCheckedAt = now();
276
283
  renderNotifyBtn();
277
- } catch (_) {}
284
+ } catch (_) {
285
+ pushFailed = true;
286
+ }
278
287
  watchAll();
279
288
  syncDevice();
280
289
  }
281
290
 
291
+ // startPush again, once at a time, while the last one failed and push
292
+ // isn't known yet (no timer: the next time the page comes back in front).
293
+ function retryPush() {
294
+ if (push || !pushFailed || pushStarting) return;
295
+ pushStarting = startPush().finally(() => { pushStarting = null; });
296
+ }
297
+
282
298
  // A Home Screen app can stay open for days: when it comes back in front
283
299
  // it asks for a newer sw.js, at most once per SW_UPDATE_MS.
284
300
  function updateWorker() {
@@ -417,6 +433,7 @@ export function createNotifications({
417
433
  function backInFront() {
418
434
  if (doc.visibilityState !== "visible") return;
419
435
  clearBadge();
436
+ retryPush();
420
437
  watchAll();
421
438
  syncDevice();
422
439
  updateWorker();
@@ -453,6 +470,7 @@ export function createNotifications({
453
470
  button.addEventListener("click", toggleNotify);
454
471
  renderNotifyBtn();
455
472
  const pushReady = startPush();
473
+ pushStarting = pushReady.finally(() => { pushStarting = null; });
456
474
 
457
475
  return {
458
476
  noticeSessions,
@@ -470,5 +488,7 @@ export function createNotifications({
470
488
  pushReady,
471
489
  // The device's tidy-up in flight, or null (specs await it).
472
490
  syncing: () => syncing,
491
+ // startPush in flight (the first, or a retry), or null (specs await it).
492
+ pushStarting: () => pushStarting,
473
493
  };
474
494
  }
@@ -67,7 +67,8 @@ body{font-family:ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,Helvetica
67
67
  .p-person{display:inline-flex;align-items:center;gap:5px;padding:1px 8px;border-radius:999px;border:1px solid var(--border)}
68
68
  .p-dot{width:7px;height:7px;border-radius:50%;background:var(--author-color,var(--author-owner))}
69
69
  .p-note{flex-basis:100%;font-size:12.5px;color:var(--text-muted)}
70
- .p-offline{flex-basis:100%;font-size:12.5px;color:var(--warn-text);background:var(--warn-bg);border:1px solid var(--warn-border);border-radius:8px;padding:4px 10px}
70
+ /* Over the thread's top, out of the sticky header's flow: a read that fails (or recovers) doesn't move the thread. */
71
+ .p-offline{position:absolute;top:calc(100% + 6px);left:16px;right:16px;max-width:760px;margin:0 auto;box-sizing:border-box;box-shadow:var(--toast-shadow);font-size:12.5px;color:var(--warn-text);background:var(--warn-bg);border:1px solid var(--warn-border);border-radius:8px;padding:4px 10px}
71
72
  .p-view-banner{flex-basis:100%;font-size:12.5px;color:var(--warn-text);background:var(--warn-bg);border:1px solid var(--warn-border);border-radius:8px;padding:4px 10px}
72
73
  main{flex:1;min-height:0;overflow-y:auto;padding:16px 16px 8px}
73
74
  .p-thread{max-width:760px;margin:0 auto;display:flex;flex-direction:column;gap:12px}
@@ -167,9 +168,9 @@ button.small{font-size:12px;padding:2px 8px}
167
168
  aria-controls="main" data-view="thread">Thread</button></div>
168
169
  <div class="p-people" id="people"></div>
169
170
  <div class="p-view-banner" id="viewBanner" hidden>Participant view: exactly what participants see of this session, through the same filter. Read-only.</div>
170
- <div class="p-offline" id="offline" role="status" hidden>Can't reach the session — retrying…</div>
171
171
  <div class="p-note" id="note"></div>
172
172
  </div>
173
+ <div class="p-offline" id="offline" role="status" hidden>Can't reach the session — retrying…</div>
173
174
  </header>
174
175
  <div class="p-body">
175
176
  <aside class="p-plan" id="plan" hidden aria-label="Under review">
@@ -24,7 +24,9 @@ import { appendQuote } from "./annotations.js";
24
24
  import { messageAuthorData, participantQuote, participantSource } from "./participant_annotate.js";
25
25
  import { mountComposer } from "./composer_mount.js";
26
26
  import { PROMPT_LINE_PX } from "./composer_size.js";
27
- import { forgetReviewHistory, readReviewHistory, recordReviewComment, rememberReviewHistory } from "./review_history.js";
27
+ import {
28
+ forgetReviewHistory, pruneReviewHistory, readReviewHistory, recordReviewComment, rememberReviewHistory,
29
+ } from "./review_history.js";
28
30
 
29
31
  // A link's #code= opened in a browser that already has a cookie: traded
30
32
  // first, the page reloads without it.
@@ -54,6 +56,8 @@ let usageTimer = null;
54
56
  let failures = 0;
55
57
  let loadSeq = 0;
56
58
  let ended = false;
59
+ // The other links' ↑/↓ lists went at this page's first read (pruneReviewHistory).
60
+ let historyPruned = false;
57
61
  // The Plan view: the subject picked, what it last drew, and which view a
58
62
  // narrow screen shows (the thread first).
59
63
  let subjectPath = null;
@@ -104,6 +108,8 @@ function showEnded(json) {
104
108
  document.title = "chi · review link ended";
105
109
  }
106
110
 
111
+ const OFFLINE_TEXT = "Can't reach the session — retrying…";
112
+
107
113
  // Reads the review data, draws it and streams from it. One that can't be
108
114
  // read (unreachable, a 5xx) keeps what the page shows, says it is
109
115
  // retrying, and reads again with a backoff.
@@ -115,18 +121,22 @@ async function load() {
115
121
  if (!ok) {
116
122
  $("head").hidden = false;
117
123
  if (!data) $("title").textContent = "Review";
118
- $("offline").hidden = !retries(status);
119
- if (retries(status)) {
120
- scheduleRetry(retryDelay(failures++));
121
- } else {
122
- $("note").textContent = status === 404 ? "This session is gone." : `The review couldn't be read (HTTP ${status}).`;
123
- }
124
+ // Said over the thread (#offline), not in the header's rows: the
125
+ // thread stays where it is.
126
+ $("offline").textContent = retries(status) ? OFFLINE_TEXT
127
+ : status === 404 ? "This session is gone." : `The review couldn't be read (HTTP ${status}).`;
128
+ $("offline").hidden = false;
129
+ if (retries(status)) scheduleRetry(retryDelay(failures++));
124
130
  return;
125
131
  }
126
132
  failures = 0;
127
133
  $("offline").hidden = true;
128
134
  data = json;
129
- if (!ownerView) rememberReviewHistory(sessionId, data?.viewer?.id);
135
+ if (!ownerView) {
136
+ rememberReviewHistory(sessionId, data?.viewer?.id);
137
+ if (!historyPruned) pruneReviewHistory(sessionId, data?.viewer?.id);
138
+ historyPruned = true;
139
+ }
130
140
  live = liveFrom(data.current_turn);
131
141
  liveStale = false;
132
142
  render();
@@ -267,6 +277,7 @@ function messageNode(message) {
267
277
  const when = fullTime(message.at);
268
278
  if (when) node.title = when;
269
279
  if (user) {
280
+ if (message.turn_id) node.dataset.turnId = message.turn_id;
270
281
  node.style.setProperty("--author-color", authorColor(message.author));
271
282
  // Whose it is, for an annotation's label (participant_annotate.js).
272
283
  Object.assign(node.dataset, messageAuthorData(message));
@@ -372,7 +383,7 @@ function currentTurnNodes() {
372
383
  const nodes = [];
373
384
  if (turn.prompt !== undefined || turn.automatic) {
374
385
  nodes.push(messageNode({ role: "user", content: turn.automatic ? "An automatic turn" : turn.prompt, author: turn.author,
375
- author_name: turn.author_name, mine: turn.mine, automatic: turn.automatic, at: turn.at }));
386
+ author_name: turn.author_name, mine: turn.mine, automatic: turn.automatic, at: turn.at, turn_id: turn.turn_id }));
376
387
  }
377
388
  const reply = el("div", "p-msg reply live");
378
389
  fillLive(reply, $("liveReply"));
@@ -468,6 +479,7 @@ async function sendComment() {
468
479
  if (!prompt) return;
469
480
  sending = true;
470
481
  $("send").disabled = true;
482
+ showError("");
471
483
  let reply;
472
484
  try {
473
485
  reply = await api(`/api/sessions/${encodeURIComponent(sessionId)}/turn`, {
@@ -481,7 +493,8 @@ async function sendComment() {
481
493
  if (ended) return;
482
494
  if (ok) {
483
495
  recordReviewComment(data?.viewer?.id, prompt);
484
- comment.value = "";
496
+ // What was typed while the comment was in flight stays in the box.
497
+ if (comment.value.trim() === prompt) comment.value = "";
485
498
  composer.fit();
486
499
  composer.drawFoldControls();
487
500
  composer.refreshHistory();
@@ -522,6 +535,8 @@ const composer = ownerView ? null : mountComposer({
522
535
  fold: { session: () => sessionId || null },
523
536
  });
524
537
  if (composer) {
538
+ // An error under the box (a refusal, the images toast) goes at the next edit.
539
+ $("comment").addEventListener("input", () => showError(""));
525
540
  // The session composer's layout (composer.css), and the fold saved in this browser.
526
541
  document.body.classList.add("has-session");
527
542
  composer.newVisit();
@@ -101,6 +101,19 @@ export function chipTemplate(chip) {
101
101
  title=${chip.title} aria-label=${chip.title} aria-haspopup="dialog"><span class="pc-dot" aria-hidden="true"></span>${chip.text}</button>`;
102
102
  }
103
103
 
104
+ // A cap field's dollars (a leading $ allowed): {value}, {value: null} when
105
+ // empty (the Invite then leaves the default cap), or {error}. Both forms read
106
+ // it, so one rule and one wording.
107
+ // @return {{value: number|null}|{error: string}}
108
+ export const CAP_ERROR = "A cap is dollars, 0 to 1000.";
109
+ export function capValue(text) {
110
+ const clean = String(text ?? "").trim();
111
+ if (!clean) return { value: null };
112
+ const value = Number(clean.replace(/^\$/, ""));
113
+ if (!Number.isFinite(value) || value < 0 || value > 1000) return { error: CAP_ERROR };
114
+ return { value };
115
+ }
116
+
104
117
  // An email as chi binds a link to it (Grants.clean_identity, which has the
105
118
  // last word): one @, no spaces, commas, quotes or angle brackets.
106
119
  const EMAIL_RE = /^[^@\s,<>"\\]+@[^@\s,<>"\\]+$/;
@@ -118,15 +131,17 @@ export function inviteBody({ name, kind, days, cap, identity }) {
118
131
  if (email) body.identity = email;
119
132
  const d = Number(days);
120
133
  body.ttl = Math.round((EXPIRY_DAYS.includes(d) ? d : DEFAULT_EXPIRY_DAYS) * 24 * 60 * 60);
121
- const capText = String(cap ?? "").trim();
122
- if (capText) {
123
- const value = Number(capText.replace(/^\$/, ""));
124
- if (!Number.isFinite(value) || value < 0 || value > 1000) return { error: "A cap is dollars, 0 to 1000." };
125
- body.cap = value;
126
- }
134
+ const capped = capValue(cap);
135
+ if (capped.error) return { error: capped.error };
136
+ if (capped.value !== null) body.cap = capped.value;
127
137
  return { body };
128
138
  }
129
139
 
140
+ // The toast for an invite whose panel closed before its answer came.
141
+ export function lateInviteText(name, sessionId) {
142
+ return `${name}'s review link for ${String(sessionId).slice(0, 8)} is ready (the panel closed before it came); it shows only once.`;
143
+ }
144
+
130
145
  // What Revoke asks first: it can't be undone (chi keeps only the link's
131
146
  // digest), as a delete asks.
132
147
  export function revokeConfirmText(name) {
@@ -206,7 +221,7 @@ export function panelTemplate(grants, { now, sessionId, invite = null, error = n
206
221
  // The control: el (#infoText, where the chip is drawn), session() the open
207
222
  // session's id, api {list(id), invite(id, body), revoke(id, pid), cap(id,
208
223
  // pid, cap)}, onChange() (the chip's count or presence changed: redraw the
209
- // bar), toast(text), onNames() (the participants' names changed: name the
224
+ // bar), toast(text, action, {sticky}) (app.js showToast), onNames() (the participants' names changed: name the
210
225
  // badges drawn before them, participant_names.js nameUnnamedBadges).
211
226
  // startReview({onError}): Start a review of it (a review fork of the open
212
227
  // session): the created session, or null (its refusal to onError(text), true
@@ -300,7 +315,10 @@ export function createParticipantsControl({ el, session, api, onChange = () => {
300
315
  const asked = ask();
301
316
  try {
302
317
  const answer = await api.invite(asked.id, body);
303
- if (!stillOpen(asked)) return dropped(asked);
318
+ if (!stillOpen(asked)) {
319
+ lateInvite(asked, answer.participant?.name || body.name, answer.link);
320
+ return dropped(asked);
321
+ }
304
322
  invite = { name: answer.participant?.name || body.name, link: answer.link, qr_svg: answer.qr_svg, lan: answer.lan,
305
323
  warning: answer.warning || null, identity: answer.participant?.identity || null, copied: false };
306
324
  error = null;
@@ -314,10 +332,27 @@ export function createParticipantsControl({ el, session, api, onChange = () => {
314
332
  if (shell.isOpen()) draw();
315
333
  }
316
334
 
335
+ // An invite answered after its panel closed: the grant exists and its link
336
+ // shows only once, so a sticky toast keeps it (Copy link; a failed copy
337
+ // shows the link itself to select), never a later panel.
338
+ function lateInvite(asked, name, link) {
339
+ if (!link) return;
340
+ const copy = async () => {
341
+ try {
342
+ await win.navigator.clipboard.writeText(link);
343
+ toast(`${name}'s review link copied`);
344
+ } catch {
345
+ toast(`${name}'s review link: ${link}`, null, { sticky: true });
346
+ }
347
+ };
348
+ toast(lateInviteText(name, asked.id), { label: "Copy link", run: copy }, { sticky: true });
349
+ }
350
+
317
351
  async function submitCap(form) {
318
- const value = Number(String(form.elements.cap.value).trim().replace(/^\$/, ""));
319
- if (!Number.isFinite(value)) {
320
- error = "A cap is dollars, 0 to 1000.";
352
+ // A cleared field is no cap to set (Number("") would be a $0 cap).
353
+ const { value, error: problem } = capValue(form.elements.cap.value);
354
+ if (problem || value == null) {
355
+ error = CAP_ERROR;
321
356
  return draw();
322
357
  }
323
358
  const asked = ask();
@@ -81,14 +81,15 @@ export async function subscribe({ reg, key, post }) {
81
81
  return { subscription: sub, answer };
82
82
  }
83
83
 
84
- // Unsubscribes this device and tells chi web to forget it.
84
+ // Tells chi web to forget this device, then unsubscribes it: a DELETE
85
+ // that fails (a flaky connection) throws before anything local changes, so
86
+ // the bell stays on with its subscription and the next tap tries again.
85
87
  // @param del (endpoint) => Promise
86
88
  // @return whether there was a subscription
87
89
  export async function unsubscribe({ reg, del }) {
88
90
  const sub = await reg.pushManager.getSubscription();
89
91
  if (!sub) return false;
90
- const endpoint = sub.endpoint;
92
+ await del(sub.endpoint);
91
93
  await sub.unsubscribe();
92
- await del(endpoint);
93
94
  return true;
94
95
  }
@@ -98,6 +98,17 @@ export function sheetTemplate(model) {
98
98
  }<div class="pd-note">Approvals, questions, step limits, cards and failed turns; quiet while a chi web page is in front.</div>`;
99
99
  }
100
100
 
101
+ // Puts every switch in +pop+ back to +model+: lit skips a .checked binding
102
+ // whose value is the one it last set, so a switch the app then refused
103
+ // (iOS's Don't Allow, a failed PATCH) would keep its clicked state.
104
+ export function syncSwitches(pop, model) {
105
+ const rows = [model.thisRow, ...model.others];
106
+ for (const input of pop.querySelectorAll("input[data-pd]")) {
107
+ if (input.dataset.pd === "this") input.checked = model.on;
108
+ else if (input.dataset.pd === "done") input.checked = rows.some((r) => r.id === input.dataset.id && r.done);
109
+ }
110
+ }
111
+
101
112
  // The sheet at the bell. +state+() the bell's state; +endpoint+() this
102
113
  // device's push endpoint (a Promise; null without a subscription);
103
114
  // +toggleThis+() the bell's subscribe / unsubscribe (resolves to its
@@ -111,14 +122,17 @@ export function createPushDevices({ button, api, state, endpoint, toggleThis, no
111
122
  // Each load's turn: an older answer that arrives late is dropped.
112
123
  let loads = 0;
113
124
 
114
- const draw = () => {
115
- if (shell.isOpen()) render(sheetTemplate(sheetModel({ state: state(), info, busy, error, now: now() })), shell.pop);
125
+ const paint = () => {
126
+ const model = sheetModel({ state: state(), info, busy, error, now: now() });
127
+ render(sheetTemplate(model), shell.pop);
128
+ syncSwitches(shell.pop, model);
116
129
  };
130
+ const draw = () => { if (shell.isOpen()) paint(); };
117
131
 
118
132
  const shell = createChipPopover({
119
133
  id: "pushDevices", className: "ctx-popover push-devices", width: 340, el: doc.createElement("span"),
120
134
  anchor: "#notifyBtn", openers: "#notifyBtn", summary: () => ({}), sheet: true, label: "Notifications", doc, win,
121
- show: () => render(sheetTemplate(sheetModel({ state: state(), info, busy, error, now: now() })), shell.pop),
135
+ show: () => paint(),
122
136
  onClose: () => { error = ""; },
123
137
  });
124
138
 
@@ -4,8 +4,9 @@
4
4
  // /api/history (the owner may open a link in the same browser, on the same
5
5
  // origin: each grant's list and the owner's stay apart). Read and written
6
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";
7
+ // not there. A link that ends forgets its list; one that ended while no page
8
+ // was open goes when the next link's page loads (pruneReviewHistory).
9
+ import { readStored, removeStored, storedKeys, writeStored } from "./storage.js";
9
10
 
10
11
  export const REVIEW_HISTORY_PREFIX = "chi_review_history:";
11
12
  const REVIEW_HISTORY_SESSION_PREFIX = "chi_review_history_session:";
@@ -58,3 +59,14 @@ export function forgetReviewHistory(grantId, sessionId) {
58
59
  const key = reviewHistoryKey(grantId || remembered);
59
60
  if (key) removeStored(key);
60
61
  }
62
+
63
+ // A participant page's first read (+sessionId+, its grant +grantId+): every
64
+ // other grant's list and every other session's pointer go, so the lists of
65
+ // links that ended while no page was open don't stay for good. Without
66
+ // either id (the owner's view, an older server's data) nothing goes.
67
+ export function pruneReviewHistory(sessionId, grantId) {
68
+ if (!sessionId || !grantId) return;
69
+ const keep = new Set([reviewHistoryKey(grantId), `${REVIEW_HISTORY_SESSION_PREFIX}${sessionId}`]);
70
+ for (const key of storedKeys(REVIEW_HISTORY_PREFIX)) if (!keep.has(key)) removeStored(key);
71
+ for (const key of storedKeys(REVIEW_HISTORY_SESSION_PREFIX)) if (!keep.has(key)) removeStored(key);
72
+ }
@@ -19,10 +19,8 @@ export function readSubjects(text) {
19
19
  return { subjects: [...new Set(found)], error: null };
20
20
  }
21
21
 
22
- export const parseSubjects = (text) => readSubjects(text).subjects;
23
-
24
22
  // The files as the form shows them again: a path with a space, a comma or
25
- // a quote in quotes, so parseSubjects reads it back whole.
23
+ // a quote in quotes, so readSubjects reads it back whole.
26
24
  export function formatSubjects(subjects) {
27
25
  return (subjects || []).map((s) => (/[\s,"]/.test(s) ? `"${s}"` : s)).join(", ");
28
26
  }
@@ -76,9 +76,21 @@ export function createSessionActions({
76
76
  // +stopHolds+ is the sheet's "Stop all": the worker's stop-all step, then
77
77
  // the stop. A delegate or a background task outlives the worker either way
78
78
  // (docs/sessions.md, "Stopping a worker"), which is why the sheet says so.
79
- async function stopSelected(id = selected(), { stopHolds = false } = {}) {
80
- if (!id) return;
79
+ // One Stop per session at a time (as reviewingIds): a second tap while the
80
+ // holds read (or the stop) is under way would be a second confirm.
81
+ const stopAsks = new Set();
81
82
 
83
+ async function stopSelected(id = selected(), options = {}) {
84
+ if (!id || stopAsks.has(id)) return;
85
+ stopAsks.add(id);
86
+ try {
87
+ await stopOne(id, options);
88
+ } finally {
89
+ stopAsks.delete(id);
90
+ }
91
+ }
92
+
93
+ async function stopOne(id, { stopHolds = false }) {
82
94
  if (!stopHolds) {
83
95
  let holds = [];
84
96
  try {
@@ -21,3 +21,19 @@ export function writeStored(key, value) {
21
21
  export function removeStored(key) {
22
22
  try { globalThis.localStorage.removeItem(key); } catch (_) {}
23
23
  }
24
+
25
+ // The stored keys that start with +prefix+ ([] when they can't be read), a
26
+ // copy: removing one while walking them is safe.
27
+ export function storedKeys(prefix) {
28
+ try {
29
+ const storage = globalThis.localStorage;
30
+ const keys = [];
31
+ for (let i = 0; i < storage.length; i++) {
32
+ const key = storage.key(i);
33
+ if (typeof key === "string" && key.startsWith(prefix)) keys.push(key);
34
+ }
35
+ return keys;
36
+ } catch (_) {
37
+ return [];
38
+ }
39
+ }
@@ -360,11 +360,12 @@ export function snapshotEvents({ current_turn: turn = null, queued = [], queued_
360
360
  // The run's cut wait (TurnAccumulator, as turn_started carried it): the
361
361
  // composer's delivery line reads it.
362
362
  const cutAfter = turn.cut_after != null ? { cut_after: turn.cut_after } : {};
363
+ const turnId = turn.turn_id ? { turn_id: turn.turn_id } : {};
363
364
  // A participant's turn names them (TurnAccumulator keeps author, author_name).
364
365
  const author = turn.author ? { author: turn.author, ...(turn.author_name ? { author_name: turn.author_name } : {}) } : {};
365
366
  // Its wall time (TurnAccumulator keeps turn_started's at): the gap divider before it.
366
367
  const at = typeof turn.at === "string" ? { at: turn.at } : {};
367
- events.push(withImages({ type: "turn_started", prompt: turn.prompt, origin: turn.origin, continue: !!turn.continue, started_at, ...at, ...cutAfter, ...author }, turn.images));
368
+ events.push(withImages({ type: "turn_started", prompt: turn.prompt, origin: turn.origin, continue: !!turn.continue, started_at, ...at, ...cutAfter, ...turnId, ...author }, turn.images));
368
369
  let textIteration = null; // a text bubble is open for this iteration
369
370
  const closeText = () => {
370
371
  if (textIteration !== null) events.push({ type: "generation_completed" });
@@ -313,7 +313,7 @@ export function userBubbleTemplate(message, { label = null, state = null, step =
313
313
  const from = author
314
314
  ? html`<span class="origin-label author-badge" title=${authorBadgeTitle(author.name)} data-unnamed=${author.unnamed ? "1" : nothing}>${authorBadgeText(author.name)}</span>`
315
315
  : label ? html`<span class="origin-label">${label}</span>` : nothing;
316
- return html`<div class=${`bubble user${named ? ` ${named}` : ""}${author ? " by-participant" : ""}`} title=${timeTitle(message?.at)} style=${author ? `--author-color:${author.color}` : nothing} data-author=${author?.author || nothing} data-user-state=${named || nothing} data-step=${step ? Number(step) : nothing} data-copy-source=${copySource({ ...message, role: "user" })} data-user-content=${key !== null ? key : nothing} data-own=${own ? "1" : nothing} data-enqueued-id=${enqueuedId || nothing} data-delivery=${delivery || nothing}>${from}<div class="user-message">${userBodyTemplate(message?.content)}${thumbs}</div>${stateBadgeTemplate(named, delivery)}</div>`;
316
+ return html`<div class=${`bubble user${named ? ` ${named}` : ""}${author ? " by-participant" : ""}`} title=${timeTitle(message?.at)} style=${author ? `--author-color:${author.color}` : nothing} data-author=${author?.author || nothing} data-user-state=${named || nothing} data-step=${step ? Number(step) : nothing} data-copy-source=${copySource({ ...message, role: "user" })} data-user-content=${key !== null ? key : nothing} data-turn-id=${message?.turn_id || nothing} data-own=${own ? "1" : nothing} data-enqueued-id=${enqueuedId || nothing} data-delivery=${delivery || nothing}>${from}<div class="user-message">${userBodyTemplate(message?.content)}${thumbs}</div>${stateBadgeTemplate(named, delivery)}</div>`;
317
317
  }
318
318
 
319
319
  // The notice of a turn that ended with no answer (the server's
@@ -76,6 +76,11 @@ module Samagotchi
76
76
  result_for(response, ms(started))
77
77
  rescue *NETWORK_ERRORS => e
78
78
  Result.new(status: :failed, code: nil, ms: ms(started), error: e.is_a?(Timeout::Error) ? "timeout" : e.class.name)
79
+ rescue StandardError => e
80
+ # Anything else is this device's failure too (a p256dh off the
81
+ # curve on disk: Crypto.encrypt raises), never the other devices'
82
+ # or the Notifier's flush. Its class, never its message.
83
+ Result.new(status: :failed, code: nil, ms: ms(started), error: e.class.name)
79
84
  end
80
85
 
81
86
  private
@@ -201,11 +201,14 @@ module Samagotchi
201
201
  added
202
202
  end
203
203
 
204
- # Removes the subscription with this short id or endpoint.
204
+ # Removes the subscription with this short id or endpoint, only one
205
+ # subscribed on +origin+ (nil: any; a push service's 404/410).
205
206
  # @return [Sub, nil] the one removed
206
- def remove(id_or_endpoint)
207
+ def remove(id_or_endpoint, origin: nil)
207
208
  update do |subs|
208
- gone = subs.find { |sub| sub.id == id_or_endpoint || sub.endpoint == id_or_endpoint }
209
+ gone = subs.find do |sub|
210
+ (sub.id == id_or_endpoint || sub.endpoint == id_or_endpoint) && (origin.nil? || sub.origin == origin)
211
+ end
209
212
  [subs - [gone], gone]
210
213
  end
211
214
  end
@@ -307,6 +310,7 @@ module Samagotchi
307
310
  unless p256dh&.bytesize == 65 && p256dh.getbyte(0) == 4
308
311
  raise Invalid, "a push subscription's p256dh must be a P-256 public key (65 bytes, base64url)"
309
312
  end
313
+ raise Invalid, "a push subscription's p256dh is not a point on P-256" unless point?(p256dh)
310
314
  raise Invalid, "a push subscription's auth must be 16 bytes (base64url)" unless decoded(keys["auth"])&.bytesize == 16
311
315
 
312
316
  [endpoint, keys["p256dh"], keys["auth"]]
@@ -331,6 +335,15 @@ module Samagotchi
331
335
  @services.any? { |entry| entry.start_with?(".") ? host.end_with?(entry) && host.length > entry.length : host == entry }
332
336
  end
333
337
 
338
+ # The key as Crypto.encrypt builds it: 65 bytes starting 0x04 can
339
+ # still lie off the curve (encrypt would raise on every push).
340
+ def point?(raw)
341
+ Crypto.ec_public(raw)
342
+ true
343
+ rescue ArgumentError, OpenSSL::OpenSSLError
344
+ false
345
+ end
346
+
334
347
  def decoded(text)
335
348
  Crypto.unb64u(text)
336
349
  rescue ArgumentError
@@ -86,7 +86,8 @@ module Samagotchi
86
86
  [204, { "Cache-Control" => "no-store" }, []]
87
87
  end
88
88
 
89
- # {endpoint} → 204: this device's bell turned off.
89
+ # {endpoint} → 204: this device's bell turned off (only a device
90
+ # subscribed on this origin, as the other device routes).
90
91
  def handle_push_unsubscribe(req)
91
92
  return push_off unless @push
92
93
 
@@ -94,7 +95,7 @@ module Samagotchi
94
95
  endpoint = body["endpoint"] if body.is_a?(Hash)
95
96
  return error_response(400, "missing_fields", "endpoint is required") unless endpoint.is_a?(String) && !endpoint.empty?
96
97
 
97
- gone = @push.store.remove(endpoint)
98
+ gone = @push.store.remove(endpoint, origin: @push.origin)
98
99
  Log.info(:web, "push_unsubscribed", device: gone.id) if gone
99
100
  [204, { "Cache-Control" => "no-store" }, []]
100
101
  end
@@ -86,9 +86,9 @@ module Samagotchi
86
86
  def self.launch(port: nil, host: nil, scope: "project", start_dir: nil, open_browser: false, markdown: false,
87
87
  view: Config::BY_KEY["web.view"].default, annotate_presets: Config::BY_KEY["web.annotate_presets"].default,
88
88
  editor: Config::BY_KEY["web.editor"].default, new_token: false,
89
- working_set: Config::BY_KEY["web.working_set"].default, tunnel: nil)
89
+ working_set: Config::BY_KEY["web.working_set"].default, tunnel: nil, start_dir_from: :flag)
90
90
  start_given = !start_dir.to_s.strip.empty?
91
- start_dir = StartDir.resolve(start_dir)
91
+ start_dir = StartDir.resolve(start_dir, from: start_dir_from)
92
92
  rotate_token if new_token
93
93
  public_url = public_url_setting unless tunnel
94
94
  setting = host_setting(host)