samagotchi 0.172.0 → 0.173.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 (120) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +44 -1
  3. data/docs/architecture.md +16 -5
  4. data/docs/cli.md +2 -1
  5. data/docs/configuration.md +1 -1
  6. data/docs/internals/background-tasks.md +20 -7
  7. data/docs/internals/bridge.md +2 -2
  8. data/docs/internals/engine.md +2 -1
  9. data/docs/internals/participants.md +67 -9
  10. data/docs/internals/remote-sessions.md +1 -1
  11. data/docs/internals/web-frontend.md +44 -15
  12. data/docs/plugins.md +3 -1
  13. data/docs/sessions.md +2 -2
  14. data/docs/testing.md +43 -3
  15. data/lib/samagotchi/bridge.rb +3 -2
  16. data/lib/samagotchi/bundle_command/try/sandbox.rb +2 -2
  17. data/lib/samagotchi/bundles/core/manifest.yml +2 -2
  18. data/lib/samagotchi/bundles/slow-commands/manifest.yml +3 -3
  19. data/lib/samagotchi/bundles/slow-commands/plugin.rb +3 -3
  20. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  21. data/lib/samagotchi/engine/participants.rb +2 -2
  22. data/lib/samagotchi/engine.rb +0 -1
  23. data/lib/samagotchi/file_ref.rb +3 -5
  24. data/lib/samagotchi/guardrails/participant_refusal.rb +1 -1
  25. data/lib/samagotchi/memory_usage.rb +2 -1
  26. data/lib/samagotchi/message_parts.rb +5 -3
  27. data/lib/samagotchi/objectives_backing.rb +6 -10
  28. data/lib/samagotchi/parent_report.rb +1 -1
  29. data/lib/samagotchi/participant_prompts.rb +101 -0
  30. data/lib/samagotchi/participant_turn_mode.rb +1 -1
  31. data/lib/samagotchi/project_env.rb +7 -5
  32. data/lib/samagotchi/prompt_history.rb +2 -2
  33. data/lib/samagotchi/send_command/parent_gate.rb +2 -2
  34. data/lib/samagotchi/send_command.rb +4 -4
  35. data/lib/samagotchi/session_command_catalog.rb +210 -0
  36. data/lib/samagotchi/session_commands.rb +12 -183
  37. data/lib/samagotchi/session_manager/lifecycle.rb +5 -4
  38. data/lib/samagotchi/session_manager.rb +2 -1
  39. data/lib/samagotchi/session_stores.rb +2 -0
  40. data/lib/samagotchi/spawn_env.rb +75 -0
  41. data/lib/samagotchi/task_files.rb +51 -0
  42. data/lib/samagotchi/task_transcript.rb +67 -0
  43. data/lib/samagotchi/task_watch.rb +8 -6
  44. data/lib/samagotchi/terminal_ui/attached_loop/composer.rb +3 -3
  45. data/lib/samagotchi/terminal_ui/attached_loop/questions.rb +2 -2
  46. data/lib/samagotchi/terminal_ui/attached_loop.rb +3 -3
  47. data/lib/samagotchi/terminal_ui/input_support.rb +1 -1
  48. data/lib/samagotchi/testing/boundary.rb +5 -0
  49. data/lib/samagotchi/tool_activity.rb +63 -79
  50. data/lib/samagotchi/tool_names.rb +179 -0
  51. data/lib/samagotchi/tool_view.rb +3 -5
  52. data/lib/samagotchi/tools/ask_user_question.rb +2 -1
  53. data/lib/samagotchi/tools/builtins.rb +1 -1
  54. data/lib/samagotchi/tools/cancel_reminder.rb +2 -1
  55. data/lib/samagotchi/tools/cancel_schedule.rb +3 -1
  56. data/lib/samagotchi/tools/context_read.rb +2 -1
  57. data/lib/samagotchi/tools/delegate.rb +2 -1
  58. data/lib/samagotchi/tools/delegate_result.rb +2 -1
  59. data/lib/samagotchi/tools/edit.rb +2 -1
  60. data/lib/samagotchi/tools/execute.rb +22 -28
  61. data/lib/samagotchi/tools/forget_outputs.rb +2 -1
  62. data/lib/samagotchi/tools/leftovers.rb +8 -4
  63. data/lib/samagotchi/tools/list_reminders.rb +2 -1
  64. data/lib/samagotchi/tools/list_schedules.rb +3 -1
  65. data/lib/samagotchi/tools/list_sessions.rb +2 -1
  66. data/lib/samagotchi/tools/memory.rb +3 -2
  67. data/lib/samagotchi/tools/objectives_tool.rb +5 -4
  68. data/lib/samagotchi/tools/read.rb +2 -1
  69. data/lib/samagotchi/tools/register_reminder.rb +2 -1
  70. data/lib/samagotchi/tools/schedule_task.rb +3 -1
  71. data/lib/samagotchi/tools/send_note.rb +2 -1
  72. data/lib/samagotchi/tools/task_create.rb +2 -1
  73. data/lib/samagotchi/tools/task_get.rb +2 -1
  74. data/lib/samagotchi/tools/task_list.rb +2 -1
  75. data/lib/samagotchi/tools/task_runtime.rb +34 -154
  76. data/lib/samagotchi/tools/task_stop.rb +2 -1
  77. data/lib/samagotchi/tools/task_wait.rb +3 -2
  78. data/lib/samagotchi/tools/web_fetch.rb +2 -1
  79. data/lib/samagotchi/tools/write.rb +2 -1
  80. data/lib/samagotchi/turn_checkpoint.rb +1 -1
  81. data/lib/samagotchi/version.rb +1 -1
  82. data/lib/samagotchi/web/app.rb +38 -36
  83. data/lib/samagotchi/web/message_display.rb +1 -7
  84. data/lib/samagotchi/web/participant_access.rb +12 -4
  85. data/lib/samagotchi/web/participant_history.rb +68 -0
  86. data/lib/samagotchi/web/participant_images.rb +2 -1
  87. data/lib/samagotchi/web/participant_show.rb +5 -5
  88. data/lib/samagotchi/web/participants_admin.rb +1 -1
  89. data/lib/samagotchi/web/public/app.js +13 -10
  90. data/lib/samagotchi/web/public/card_kinds.js +51 -0
  91. data/lib/samagotchi/web/public/card_registry.js +248 -0
  92. data/lib/samagotchi/web/public/cards_offscreen.js +3 -3
  93. data/lib/samagotchi/web/public/cards_place.js +21 -4
  94. data/lib/samagotchi/web/public/history_shape.js +1 -2
  95. data/lib/samagotchi/web/public/participant_history.js +27 -0
  96. data/lib/samagotchi/web/public/question_cards.js +16 -15
  97. data/lib/samagotchi/web/public/reload_check.js +90 -72
  98. data/lib/samagotchi/web/public/session_sync.js +4 -2
  99. data/lib/samagotchi/web/public/session_view.js +6 -1
  100. data/lib/samagotchi/web/public/stage_asking.js +18 -13
  101. data/lib/samagotchi/web/public/stage_place.js +144 -0
  102. data/lib/samagotchi/web/public/stage_probe.js +64 -0
  103. data/lib/samagotchi/web/public/stage_view.js +52 -104
  104. data/lib/samagotchi/web/public/stage_waiting.js +28 -17
  105. data/lib/samagotchi/web/public/task_stop.js +1 -1
  106. data/lib/samagotchi/web/push_routes.rb +1 -1
  107. data/lib/samagotchi/web/reload_check_route.rb +5 -2
  108. data/lib/samagotchi/web/request_body.rb +72 -0
  109. data/lib/samagotchi/web/server.rb +70 -0
  110. data/lib/samagotchi/web/session_access_routes.rb +13 -11
  111. data/lib/samagotchi/web/session_control.rb +21 -15
  112. data/lib/samagotchi/web/session_create.rb +2 -1
  113. data/lib/samagotchi/web/session_show.rb +8 -8
  114. data/lib/samagotchi/web/viewer.rb +7 -2
  115. data/lib/samagotchi/web/working_set_routes.rb +3 -3
  116. data/lib/samagotchi/worker.rb +49 -182
  117. data/lib/samagotchi/worker_exit_claim.rb +102 -0
  118. data/lib/samagotchi/worker_participant_gate.rb +156 -0
  119. data/lib/samagotchi/worker_task_wakes.rb +2 -2
  120. metadata +16 -1
@@ -0,0 +1,64 @@
1
+ // The stage's perf probe (script/stage-perf-probe, docs/testing.md): off
2
+ // unless the page was opened with ?stage_probe=1 (kept for the tab in
3
+ // sessionStorage, chi_stage_probe, so a reload or a hash jump keeps it;
4
+ // ?stage_probe=0 drops it) or <body data-stage-probe="1"> (read at each call:
5
+ // Web Inspector can set it after the page loaded). Probing, +measured+
6
+ // times its function as a performance measure, and the page gets
7
+ // globalThis.chiStageProbe.report(): each name's {n, p50, p95, max} in ms,
8
+ // the measures cleared after. Off, +measured+ only runs the function.
9
+ const KEY = "chi_stage_probe";
10
+ let kept = null;
11
+
12
+ // The tab's flag, read once per page load (storage can throw: off then).
13
+ function keptOn() {
14
+ if (kept !== null) return kept;
15
+ kept = false;
16
+ try {
17
+ const asked = new URLSearchParams(globalThis.location?.search || "").get("stage_probe");
18
+ if (asked === "1") sessionStorage.setItem(KEY, "1");
19
+ else if (asked === "0") sessionStorage.removeItem(KEY);
20
+ kept = sessionStorage.getItem(KEY) === "1";
21
+ } catch (_) {
22
+ kept = false;
23
+ }
24
+ return kept;
25
+ }
26
+
27
+ export const probing = () => globalThis.document?.body?.dataset?.stageProbe === "1" || keptOn();
28
+
29
+ const at = (sorted, q) => sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))];
30
+ const round = (ms) => Math.round(ms * 1000) / 1000;
31
+
32
+ // Each name's measures since the last report or clear: past MAX_MEASURES the
33
+ // name's measures are cleared (a page left probing for hours stays small).
34
+ const MAX_MEASURES = 10_000;
35
+ const counts = new Map();
36
+
37
+ export function report() {
38
+ counts.clear();
39
+ const byName = {};
40
+ for (const m of performance.getEntriesByType("measure")) (byName[m.name] ||= []).push(m.duration);
41
+ performance.clearMeasures();
42
+ performance.clearMarks();
43
+ return Object.fromEntries(Object.entries(byName).map(([name, list]) => {
44
+ const sorted = list.sort((a, b) => a - b);
45
+ return [name, { n: sorted.length, p50: round(at(sorted, 0.5)), p95: round(at(sorted, 0.95)), max: round(sorted[sorted.length - 1]) }];
46
+ }));
47
+ }
48
+
49
+ export function measured(name, fn) {
50
+ if (!probing()) return fn();
51
+ globalThis.chiStageProbe ||= { report };
52
+ const start = performance.now();
53
+ try {
54
+ return fn();
55
+ } finally {
56
+ // The probe never breaks the page: a measure the browser refuses is lost.
57
+ try {
58
+ const n = (counts.get(name) || 0) + 1;
59
+ if (n > MAX_MEASURES) performance.clearMeasures(name);
60
+ counts.set(name, n > MAX_MEASURES ? 1 : n);
61
+ performance.measure(name, { start, end: performance.now() });
62
+ } catch (_) { /* not measured */ }
63
+ }
64
+ }
@@ -21,14 +21,15 @@
21
21
  // (web-frontend.md, The stage's modules): the nodes are stage_dom.js's, the
22
22
  // live slots stage_slots.js's, the cap and the held height stage_frame.js's,
23
23
  // the in-use watch that times the hand-off stage_watch.js's, the hand-off
24
- // itself stage_handoff.js's, the cloud stage_cloud.js's, the docked card and
25
- // the fold stage_asking.js's, its pager stage_pager.js's, the waiting cards
26
- // as data stage_waiting.js's, the answer's reading stage_answer.js's, the
27
- // quiet signal stage_stall.js's and its clocks stage_quiet_clock.js's. A new
24
+ // itself stage_handoff.js's, where a row or a card goes stage_place.js's,
25
+ // the cloud stage_cloud.js's, the docked card and the fold stage_asking.js's,
26
+ // its pager stage_pager.js's, the waiting cards as data stage_waiting.js's,
27
+ // the answer's reading stage_answer.js's, the quiet signal stage_stall.js's
28
+ // and its clocks stage_quiet_clock.js's, the perf probe stage_probe.js's. A new
28
29
  // stage feature goes into its own stage_<feature>.js, wired here in a few
29
30
  // lines; each module resets itself from emptySlots.
30
31
  import { createTurnBlock } from "./turn_block.js";
31
- import { chipLabelText, flashOf, handOffDue, headlineOf, isPlain, liveSlots, MARKS, foldedRowText, phaseLabel, placeFor, placeKind, QUEUED_CHILDREN, stepSlotText } from "./stage_model.js";
32
+ import { chipLabelText, flashOf, handOffDue, headlineOf, isPlain, liveSlots, MARKS, foldedRowText, phaseLabel, QUEUED_CHILDREN, stepSlotText } from "./stage_model.js";
32
33
  import { createStageSlots, node } from "./stage_slots.js";
33
34
  import { createStageDom } from "./stage_dom.js";
34
35
  import { createStageAnswer } from "./stage_answer.js";
@@ -45,12 +46,12 @@ import { createStageQuietClock } from "./stage_quiet_clock.js";
45
46
  import { formatDuration } from "./timing.js";
46
47
  import { createWorkingSetRail } from "./working_set_rail.js";
47
48
  import { createOpenedTurn } from "./stage_opened.js";
48
- import { askingRefs } from "./turn_model.js";
49
- import { ASKS, PENDING } from "./stage_cards.js";
50
49
  import { createStageAsking } from "./stage_asking.js";
51
- import { cardIn, createStageWaiting, isApprovalCard, isBlocking, waitingKey, waitingKind } from "./stage_waiting.js";
50
+ import { cardIn, createStageWaiting, waitingKey } from "./stage_waiting.js";
52
51
  import { stampRows } from "./working_set_view.js";
53
52
  import { createOwnerWait } from "./stage_owner_wait.js";
53
+ import { measured } from "./stage_probe.js";
54
+ import { createStagePlace } from "./stage_place.js";
54
55
 
55
56
  // The turn-end read (markdown, answer_display) settles within this, or the
56
57
  // hand-off stops waiting for it.
@@ -73,12 +74,13 @@ const FLASH_MS = 4000;
73
74
  // waits on (live_timing.js note), +serverGen+() a joiner's generation.
74
75
  // +canCancel+() whether this turn's Stop turn shows (a participant's own
75
76
  // turn only); +ownerWait+() the kind a participant's view waits for the
76
- // owner on, or null (stage_owner_wait.js).
77
+ // owner on, or null (stage_owner_wait.js). +createWaiting+: the registry's
78
+ // factory (stage_waiting.js; a test passes an older one's shape).
77
79
  export function createStageView({
78
80
  historyEl, isNearBottom: historyNearBottom, sawText, sessionId, dockEl, centerEl, taskStop = null,
79
81
  renderMarkdown, linkRefs, workingSet = null, onCancel = null, onHandedOff = null,
80
82
  clock = () => Date.now(), streamLive = () => true, timingNote = () => "", serverGen = () => null,
81
- canCancel = () => true, ownerWait = () => null,
83
+ canCancel = () => true, ownerWait = () => null, createWaiting = createStageWaiting,
82
84
  }) {
83
85
  // The stage's nodes (stage_dom.js), then their behaviour here and in the
84
86
  // stage's modules.
@@ -196,7 +198,9 @@ export function createStageView({
196
198
  // The cards that wait in the stage, as data (stage_waiting.js): the
197
199
  // docked card, its fold, what blocks, the approval's cap read them. The
198
200
  // fold of the asking card is this tab's own, kept per session.
199
- const waiting = createStageWaiting({ sessionId });
201
+ const waiting = createWaiting({ sessionId });
202
+ // The e2e's stage check reads it off the node (spec/e2e/support/fixtures.js).
203
+ stage.chiWaiting = () => waiting.list();
200
204
  let dockedAtLastRefresh = [];
201
205
  // The asking form and the stage's fold (stage_asking.js).
202
206
  const ask = createStageAsking({
@@ -204,7 +208,7 @@ export function createStageView({
204
208
  isEnded: () => !!endKind, promptEl: () => promptEl, setCloud: (open) => cloudView.setCloud(open), scheduleRefresh, pendingCard, waiting,
205
209
  });
206
210
  const {
207
- askingGen, asksOf, askedFor, askedText, docks, leadInText, openTurn, settleCards, askingCard, cardOf, foldedText, markOwnToggles,
211
+ askedText, settleCards, askingCard, cardOf, foldedText, markOwnToggles,
208
212
  isCollapsed, drawCollapsed, applyCollapsed, setCollapsed,
209
213
  } = ask;
210
214
 
@@ -227,11 +231,10 @@ export function createStageView({
227
231
  requestAnimationFrame(refresh);
228
232
  }
229
233
 
230
- // A card that blocks the turn waits (stage_waiting.js, checked against
231
- // the slots first: a replay answers a card and starts the next step in one
232
- // task, before the refresh).
234
+ // A card that blocks the turn waits (stage_waiting.js: every way a card
235
+ // stops waiting settles it at once, also a replay's answer and next step
236
+ // in one task, before the refresh).
233
237
  function pendingCard() {
234
- ask.reconcileWaiting();
235
238
  return waiting.count() > 0;
236
239
  }
237
240
 
@@ -263,7 +266,12 @@ export function createStageView({
263
266
  // the card's own task, never a frame apart.
264
267
  new MutationObserver(() => refresh()).observe(extras, { childList: true, subtree: true });
265
268
 
269
+ // Timed when the perf probe is on (stage_probe.js).
266
270
  function refresh() {
271
+ measured("stage:refresh", drawRefresh);
272
+ }
273
+
274
+ function drawRefresh() {
267
275
  rafPending = false;
268
276
  const { turn, blockEl } = view.current();
269
277
  if (!holding || !turn) return;
@@ -283,7 +291,6 @@ export function createStageView({
283
291
  const thinking = thinkingLine && thinkingLine.step === turn.gens.length ? thinkingLine.text : "";
284
292
  // A question blocks the turn: its card takes the live slots' room. An
285
293
  // asking card's turn goes on: the status waits, the slots stay.
286
- ask.reconcileWaiting();
287
294
  settleCards();
288
295
  markOwnToggles();
289
296
  const blocked = pendingCard();
@@ -490,6 +497,7 @@ export function createStageView({
490
497
  markOwnToggles();
491
498
  opener.reset();
492
499
  waiting.reset();
500
+ placer.reset();
493
501
  dockedAtLastRefresh = [];
494
502
  miniTool.classList.remove("ts-mini-question");
495
503
  cloudView.reset();
@@ -536,6 +544,12 @@ export function createStageView({
536
544
  blockPlace, promptWords, isCollapsed, releaseTurn, clearStage, onHandedOff,
537
545
  });
538
546
 
547
+ // Where a row or a card goes while the stage holds a turn (stage_place.js).
548
+ const placer = createStagePlace({
549
+ historyEl, extras, tail, queuedSlot, ensureQueuedSlot, handoff, quiet, view, opener, waiting, ask, frame: () => frame, refresh,
550
+ scheduleRefresh, holding: () => holding, opened: () => opened, endKind: () => endKind, promptEl: () => promptEl, historyNearBottom,
551
+ });
552
+
539
553
  function dropBare() {
540
554
  if (!bare) return;
541
555
  bare = false;
@@ -680,93 +694,11 @@ export function createStageView({
680
694
  handoff.reset();
681
695
  release();
682
696
  },
683
- // The stage's extras while it holds a turn (a card, a prompt for its
684
- // next step, a command, a note, the end line), its queued slot for a
685
- // line queued for after it; false: the history takes it.
686
- place(el) {
687
- // A turn still sliding away goes into the history first: what comes
688
- // now comes after it.
689
- handoff.settle();
690
- const waits = !!(el.matches?.(PENDING) || el.querySelector?.(ASKS));
691
- const kind = placeKind(el);
692
- const where = placeFor({ live: holding, handingOff: false, kind, opened: opened && !endKind });
693
- // A late recap (idle-only, it describes the chat before this turn)
694
- // goes above an opened turn, not inside it.
695
- const above = kind === "recap" && opened ? [promptEl, view.current().blockEl].find((x) => x?.parentElement === historyEl) : null;
696
- if (above) {
697
- historyEl.insertBefore(el, above);
698
- return true;
699
- }
700
- if (where === "history") return false;
701
- quiet.alive();
702
- if (where === "queued") {
703
- ensureQueuedSlot();
704
- queuedSlot.appendChild(el);
705
- scheduleRefresh();
706
- return true;
707
- }
708
- // An opened turn's row: the history's end, in arrival order; a card
709
- // that stopped waiting before it (a replay answers it and steers in
710
- // one task, before the refresh) goes there first.
711
- if (where === "opened") {
712
- ask.reconcileWaiting();
713
- settleCards();
714
- opener.add(el);
715
- scheduleRefresh();
716
- return true;
717
- }
718
- // A card that waits for the user docks: the turn opens in the
719
- // history, a lead-in lands there in this task, the card stays here.
720
- const docked = docks(el);
721
- const key = waitingKey(el);
722
- // A card drawn again with its key (the same question) keeps its lead-in.
723
- const kept = docked && opener.has(key);
724
- const reason = docked && !kept ? leadInText(el) : "";
725
- // Read before the turn's pieces make the history taller: with no
726
- // lead-in to read, a reader at the end follows the turn's move.
727
- const atEnd = docked ? historyNearBottom() : false;
728
- if (docked) openTurn({ follow: atEnd && !reason });
729
- const slot = endKind ? tail : extras;
730
- const stick = slot.scrollHeight - slot.scrollTop - slot.clientHeight < 24;
731
- // The stage's order (stage_waiting.js): a card that blocks goes before
732
- // the asking ones, as a reload places them.
733
- const behind = isBlocking(waitingKind(el)) ? [...slot.children].find((x) => waitingKind(x) === "asks") : null;
734
- slot.insertBefore(el, behind || null);
735
- slot.hidden = false;
736
- // The card is the stage's to keep (stage_waiting.js): docked when it
737
- // waits for the user (its lead-in is the opener's, by the same key).
738
- const waitKind = waitingKind(el);
739
- if (waitKind) waiting.arrive(key, { kind: waitKind, docked, approval: isApprovalCard(el) });
740
- if (stick || waits) slot.scrollTop = slot.scrollHeight;
741
- if (kept) opener.relink(key, el);
742
- if (reason) {
743
- const { turn } = view.current();
744
- opener.ask({
745
- card: el, key, text: reason, refs: askingRefs(turn) || askingGen(asksOf(el))?.refs || null, step: turn?.gens.length || 0,
746
- turnId: promptEl?.dataset.turnId || null, questionId: el.dataset.qid ?? null, follow: atEnd,
747
- });
748
- }
749
- // The step limit: its card goes under its ended turn in the
750
- // conversation at once, as a reload draws it (the hand-off: its fold,
751
- // the history's follow and the reload check as for any finished turn;
752
- // the in-use watch and the end read don't hold it).
753
- if (endKind && waitKind === "continue") {
754
- handoff.handOff();
755
- return true;
756
- }
757
- // A waiting card and the asking form (refresh) land in one task.
758
- if (waits) refresh();
759
- else scheduleRefresh();
760
- // The asking form: the stage shrinks to the card; an answer can also
761
- // shrink it to a remaining card, or release it at the next step.
762
- if (docked) frame.forgetContent();
763
- if (waits && el.matches?.(".bubble.question")) askedFor(el);
764
- // A card that waits for the user is brought into the stage's view: in
765
- // a short window the prompt and headline fill it and the card sat
766
- // below, out of sight (once the stage has grown for it).
767
- if (waits) frame.afterGrowth(() => frame.reveal(slot));
768
- return true;
769
- },
697
+ // The stage's extras while it holds a turn, its queued slot, an opened
698
+ // turn's history end; false: the history takes it (stage_place.js).
699
+ place: (el) => placer.place(el),
700
+ // What a card about to be placed waits as (card_kinds.js; stage_place.js).
701
+ expectWaiting: (key, info) => placer.expect(key, info),
770
702
  // Where the live timing line goes (the status row), null: the history.
771
703
  timingHost: () => {
772
704
  handoff.settle();
@@ -815,6 +747,22 @@ export function createStageView({
815
747
  opener.settle(key, card);
816
748
  return true;
817
749
  },
750
+ // A plugin card redrawn in place that still waits (cards_place.js
751
+ // upsertCard; +info+: card_kinds.js cardWait): its entry patched, or, for
752
+ // a card in the stage that waits again (its actions back), arrived anew;
753
+ // the stage redrawn at once (a new title changes no child: the extras'
754
+ // observer doesn't see it).
755
+ // An older stage_waiting.js (a mixed cache) has no update: arrive again,
756
+ // which keeps an entry's order.
757
+ updateWaiting: (key, info) => {
758
+ const was = waiting.get(key);
759
+ if (!waiting.update?.(key, info)) {
760
+ const card = cardIn(extras, key) || cardIn(tail, key);
761
+ if (!info?.kind || (!was && !card)) return;
762
+ waiting.arrive(key, { kind: info.kind, docked: was ? was.docked : ask.docks(card), approval: !!was?.approval, summary: info.summary });
763
+ }
764
+ refresh();
765
+ },
818
766
  // The waiting cards as data (the tests' and the harness's read).
819
767
  waiting: { list: () => waiting.list(), front: () => waiting.front(), docked: () => waiting.docked(), folded: () => waiting.folded(), count: (o) => waiting.count(o) },
820
768
  root: stage,
@@ -6,15 +6,14 @@
6
6
  //
7
7
  // Its feed: +arrive+ from stage_view.js place (a card the stage keeps),
8
8
  // +settle+ from question_cards.js's resolve path (onSettled: answered,
9
- // cancelled, replaced, removed; the continue card resolved or dropped), from
9
+ // cancelled, replaced, removed; the continue card resolved or dropped; done:
10
+ // answered, cancelled or resolved for good, which removes its stored fold), from
10
11
  // cards_place.js upsertCard for a plugin card redrawn without its actions,
11
12
  // and from stage_view.js turnEnded for the warn cards leaving with the
12
- // block; +reset+ from stage_view.js emptySlots. A second feed only settles:
13
- // +reconcile+ (stage_asking.js: at each refresh, and before the fold, the
14
- // blocking read and an opened row) drops an entry whose card
15
- // is gone or waits no more, for a card answered outside question_cards.js
16
- // (the stage's unit tests answer a card by its classes alone). It never
17
- // adds or docks: arrive is the one way in.
13
+ // block; +reset+ from stage_view.js emptySlots. Settle is the one way out
14
+ // (nothing reads the slots back to drop an entry: the tests compare the two,
15
+ // stage_cuts_parity.test.js crossCheck and the e2e's stage check). Arrive is
16
+ // the one way in.
18
17
  //
19
18
  // A card's entry: its kind (KINDS), docked (it shows alone in the box above
20
19
  // the composer, its turn opened in the history: stage_asking.js docks; its
@@ -27,8 +26,9 @@
27
26
  // fold (the docked card's own, stage_asking.js) is the folded card's key and
28
27
  // how many cards waited when it was folded. That fold is this tab's own: it
29
28
  // is kept in sessionStorage (one entry per session) so a reload or a resync
30
- // mid-turn draws the card as the user left it, and it goes when the card is
31
- // answered or cancelled, when the fold drops, and when the turn hands off.
29
+ // mid-turn draws the card as the user left it, and it goes when that card is
30
+ // answered or cancelled (settle with done: no other card's answer touches
31
+ // it), when the fold drops, and when the turn hands off.
32
32
  import { ASKS, PENDING, WARN_CARD } from "./stage_cards.js";
33
33
  import { readSession, removeSession, writeSession } from "./storage.js";
34
34
 
@@ -147,17 +147,32 @@ export function createStageWaiting({ sessionId = null, storage = tabStorage } =
147
147
  return {
148
148
  // +key+ came to the stage (again: its kind and flags change, its place in
149
149
  // the order stays).
150
- arrive(key, { kind, docked = false, approval = false } = {}) {
150
+ // +summary+: the folded row's text from its data (card_kinds.js), null:
151
+ // none (stage_asking.js foldedText reads the card then).
152
+ arrive(key, { kind, docked = false, approval = false, summary = null } = {}) {
151
153
  if (!key || !KINDS.includes(kind)) return;
152
154
  const was = cards.get(key);
153
155
  // A new card goes in front of what the pager was on.
154
156
  if (!was) paged = null;
155
157
  cards.set(key, {
156
- kind, docked: !!docked, approval: !!approval, order: was ? was.order : seq++,
158
+ kind, docked: !!docked, approval: !!approval, summary: typeof summary === "string" ? summary : null, order: was ? was.order : seq++,
157
159
  });
158
160
  },
159
- // +key+ stopped waiting (+only+: when it is that kind).
160
- settle(key, { only = null } = {}) {
161
+ // +key+'s card was redrawn in place, still waiting (cards_place.js
162
+ // upsertCard): its kind and summary as its data says now, its order and
163
+ // docking as they were. Whether there was an entry to patch.
164
+ update(key, { kind, summary = null } = {}) {
165
+ const was = cards.get(key);
166
+ if (!was) return false;
167
+ cards.set(key, { ...was, kind: KINDS.includes(kind) ? kind : was.kind, summary: typeof summary === "string" ? summary : was.summary });
168
+ return true;
169
+ },
170
+ // +key+ stopped waiting (+only+: when it is that kind). +done+: for
171
+ // good (answered, cancelled, the continue card resolved): the fold this
172
+ // tab kept goes when it names this card, also when the stage holds no
173
+ // entry for it (a replay's earlier card, a history question).
174
+ settle(key, { only = null, done = false } = {}) {
175
+ if (done && key && storedFold()?.key === key) storage.remove(at());
161
176
  const was = cards.get(key);
162
177
  if (!was || (only && was.kind !== only)) return false;
163
178
  cards.delete(key);
@@ -173,10 +188,6 @@ export function createStageWaiting({ sessionId = null, storage = tabStorage } =
173
188
  foldedWith = 0;
174
189
  paged = null;
175
190
  },
176
- // The second feed: every entry +waits+(key, kind) says no to settles.
177
- reconcile(waits) {
178
- for (const [key, { kind }] of [...cards.entries()]) if (!waits(key, kind)) cards.delete(key);
179
- },
180
191
  has: (key) => cards.has(key),
181
192
  get: (key) => (cards.has(key) ? { key, ...cards.get(key) } : null),
182
193
  // The docked cards' keys, in the stage's order.
@@ -27,7 +27,7 @@ const WAIT_SUFFIX = / · up to \d+s$/;
27
27
  // a message from the user waited: "4s mark") and went on as a task (Tools::Execute::HANDED_OVER), then its task_id line.
28
28
  // Anchored at the start, an optional "ran as: …" line and "[execute]" lead
29
29
  // before it: a "task_id:" line anywhere else is the command's own output.
30
- // The twin of TaskRuntime.handed_over_id.
30
+ // The twin of TaskTranscript.handed_over_id.
31
31
  const HANDED_OVER = /^(?:ran as: [^\n]*\n)?(?:\[execute\]\n)?Still running at the \d+s (?:limit|mark):[^\n]*\ntask_id: (\S+)/;
32
32
 
33
33
  // The task id an execute row's output hands over, else null.
@@ -26,7 +26,7 @@ module Samagotchi
26
26
  def handle_push_info(req)
27
27
  return json_response(200, { enabled: false, public_key: nil, origin: nil, this: nil }) unless @push
28
28
 
29
- endpoint = req.params["endpoint"].to_s
29
+ endpoint = req.GET["endpoint"].to_s
30
30
  subs = @push.store.subscriptions
31
31
  mine = subs.select { |sub| sub.origin == @push.origin }
32
32
  this = endpoint.empty? ? nil : mine.find { |sub| sub.endpoint == endpoint }
@@ -51,8 +51,8 @@ module Samagotchi
51
51
 
52
52
  private
53
53
 
54
- # {turn_id, same, kinds, excused, explained, drawn, undrawn} from the
55
- # page: 204, whatever it said
54
+ # {turn_id, same, kinds, excused, explained, drawn, undrawn,
55
+ # cards_compared?} from the page: 204, whatever it said
56
56
  # (fire-and-forget); 400 for a body that isn't a JSON object.
57
57
  # worker_version is chi web's own view of the session's worker (its
58
58
  # sidecar), never the body's.
@@ -70,6 +70,9 @@ module Samagotchi
70
70
  # count chi web should keep at 0.
71
71
  undrawn = body["undrawn"].is_a?(Integer) ? body["undrawn"].clamp(0, 10_000) : 0
72
72
  fields = { sid: id, turn_id: turn_id, same: same, drawn: drawn, undrawn: undrawn, worker_version: checked_worker_version(id) }
73
+ # A page with no card registry (an app.js older than its reload_check.js)
74
+ # compared no cards or questions: its "same" is the history's alone.
75
+ fields[:cards_compared] = false if body["cards_compared"] == false
73
76
  Log.info(:web, "reload_checked", **fields)
74
77
  unless same
75
78
  Log.info(:web, "reload_mismatch", **fields.except(:same), kinds: checked_tokens(body["kinds"], KINDS),
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Samagotchi
4
+ module Web
5
+ # Every request body chi web reads, read through #request_body: capped,
6
+ # 64 KB unless the call names its own cap (an image's 20 MB, an owner's
7
+ # turn 16 MB, …). Over the cap is BodyTooLarge, which App#route answers
8
+ # 413 too_large with Connection: close (Web::Server then doesn't drain
9
+ # the rest). Rack's req.params / req.POST would read a form body
10
+ # uncapped: chi web reads a query with req.GET
11
+ # (spec/web/no_body_params_spec.rb). Included in App.
12
+ # See docs/internals/participants.md (The gate).
13
+ module RequestBody
14
+ SMALL_BODY_LIMIT = 64 * 1024
15
+ # An owner's turn or new session: prompt text and small fields (images
16
+ # are refs to separate uploads). A big piped `chi send` is a big
17
+ # prompt; over this it goes the Bridge's 413 way, into the input-file
18
+ # fallback (SessionManager::Delivery). It stays at most
19
+ # 32 × Bridge::MAX_BODY_BYTES, what the Bridge skips before its 413.
20
+ OWNER_TURN_BODY_LIMIT = 16 * 1024 * 1024
21
+ # What the worker's Bridge takes (Bridge::MAX_BODY_BYTES's number: chi
22
+ # web doesn't load the Bridge; spec/web/request_body_cap_spec.rb keeps
23
+ # them equal): a participant's turn and an answer, which chi web
24
+ # relays to it.
25
+ BRIDGE_BODY_LIMIT = 1_000_000
26
+ # POST …/context/:name/push: a text up to ContextSources::TEXT_MAX_BYTES
27
+ # (1 MB), JSON-escaped (a control character is 6 bytes).
28
+ CONTEXT_PUSH_BODY_LIMIT = 16 * 1024 * 1024
29
+
30
+ # A body over its cap. The message is the 413's one text: "<what> may
31
+ # be up to <size>".
32
+ class BodyTooLarge < StandardError
33
+ attr_reader :limit, :what
34
+
35
+ def initialize(limit, what)
36
+ @limit = limit
37
+ @what = what
38
+ super("#{what} may be up to #{RequestBody.size_words(limit)}")
39
+ end
40
+ end
41
+
42
+ # 65_536 → "64 KB", 20_971_520 → "20 MB", 1_000_000 (the Bridge's
43
+ # cap) → "1 MB", 1000 → "1000 bytes".
44
+ def self.size_words(bytes)
45
+ mib = 1024 * 1024
46
+ return "#{bytes / mib} MB" if bytes >= mib && (bytes % mib).zero?
47
+ return "#{bytes / 1_000_000} MB" if bytes >= 1_000_000 && (bytes % 1_000_000).zero?
48
+ return "#{bytes / 1024} KB" if bytes >= 1024 && (bytes % 1024).zero?
49
+
50
+ "#{bytes} bytes"
51
+ end
52
+
53
+ private
54
+
55
+ # The request body, "" when there is none: WEBrick (through rackup)
56
+ # raises LengthRequired on reading a POST that has neither a
57
+ # Content-Length nor a chunked body (plain `curl -X POST`). Over
58
+ # +limit+ bytes, by its Content-Length (nothing read) or by what came
59
+ # (a chunked body, a Content-Length that lies: at most limit + 1
60
+ # read), it raises BodyTooLarge naming +what+.
61
+ def request_body(req, limit = SMALL_BODY_LIMIT, what: "a request body")
62
+ return "" if req.get_header("CONTENT_LENGTH").nil? && req.get_header("HTTP_TRANSFER_ENCODING").nil?
63
+ raise BodyTooLarge.new(limit, what) if req.content_length.to_i > limit
64
+
65
+ raw = req.body.read(limit + 1).to_s
66
+ raise BodyTooLarge.new(limit, what) if raw.bytesize > limit
67
+
68
+ raw
69
+ end
70
+ end
71
+ end
72
+ end
@@ -82,6 +82,76 @@ module Samagotchi
82
82
  # chi web is the only WEBrick server chi runs.
83
83
  WEBrick::HTTPRequest.prepend(ProxyGate::RawHeaderNames) unless WEBrick::HTTPRequest < ProxyGate::RawHeaderNames
84
84
 
85
+ # How much of a refused body (any 4xx or 5xx to a request with a
86
+ # body) the server still reads and drops after its answer, and for
87
+ # how long, so the client reads the answer before the close (a close
88
+ # with unread bytes is a reset, which can lose the answer on the
89
+ # client's side). The thread is held at most LINGER_SECONDS; memory
90
+ # is one 64 KB buffer.
91
+ LINGER_BYTES = 4 * 1024 * 1024
92
+ LINGER_SECONDS = 2.0
93
+
94
+ # A refusal (status 400 or more) to a request that declared a body
95
+ # (Content-Length > 0, or Transfer-Encoding), and any answer with
96
+ # Connection: close (App's 413 too_large), end the connection: WEBrick
97
+ # would otherwise read and drop the rest of the body
98
+ # (HTTPRequest#fixup, up to its Content-Length) to keep the connection
99
+ # alive, before it sends the answer; rackup never tells WEBrick about
100
+ # the header (WEBrick reads it only as it sends). One rule here, not
101
+ # per route: the gate's 401, a participant's 403/404, the image
102
+ # path's own 413 and 429 close as App's 413 does. A 2xx/3xx stays
103
+ # alive (WEBrick drains a body the app left, as before); a hijacked
104
+ # stream is left to its own.
105
+ module CloseOnConnectionClose
106
+ def service(req, res)
107
+ super
108
+ return if res.body.respond_to?(:call)
109
+
110
+ body = req["content-length"].to_i.positive? || !req["transfer-encoding"].nil?
111
+ return unless res["connection"].to_s.casecmp?("close") || (res.status >= 400 && body)
112
+
113
+ res.keep_alive = false
114
+ res.linger = body
115
+ end
116
+ end
117
+
118
+ # The answer of a connection CloseOnConnectionClose ended with a body
119
+ # left: sent, then the rest read and dropped up to LINGER_BYTES /
120
+ # LINGER_SECONDS (Server.linger) before WEBrick closes the socket.
121
+ module LingerAfterAnswer
122
+ attr_accessor :linger
123
+
124
+ def send_response(socket)
125
+ super
126
+ Server.linger(socket) if linger
127
+ end
128
+ end
129
+
130
+ Rackup::Handler::WEBrick.prepend(CloseOnConnectionClose) unless Rackup::Handler::WEBrick < CloseOnConnectionClose
131
+ WEBrick::HTTPResponse.prepend(LingerAfterAnswer) unless WEBrick::HTTPResponse < LingerAfterAnswer
132
+
133
+ # Read and drop what the client still sends after the answer (its
134
+ # write side shut first, so the answer and an EOF reach it), up to
135
+ # +bytes+ or +seconds+, whichever comes first.
136
+ def self.linger(socket, bytes: LINGER_BYTES, seconds: LINGER_SECONDS)
137
+ io = socket.to_io
138
+ io.shutdown(Socket::SHUT_WR)
139
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + seconds
140
+ buffer = +""
141
+ while bytes.positive?
142
+ wait = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
143
+ break unless wait.positive? && io.wait_readable(wait)
144
+
145
+ chunk = io.read_nonblock([bytes, 65_536].min, buffer, exception: false)
146
+ break if chunk.nil?
147
+ next if chunk == :wait_readable
148
+
149
+ bytes -= chunk.bytesize
150
+ end
151
+ rescue IOError, SystemCallError
152
+ nil
153
+ end
154
+
85
155
  # `chi web`: one server serves every project, the scope is in the page
86
156
  # URL. If a chi web already runs on the port, print (and with --open,
87
157
  # open) its page for +start_dir+ and leave it be; else start one.