samagotchi 0.172.1 → 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 (115) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +31 -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 +19 -6
  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 +11 -6
  12. data/docs/plugins.md +3 -1
  13. data/docs/sessions.md +2 -2
  14. data/docs/testing.md +26 -10
  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/list_reminders.rb +2 -1
  63. data/lib/samagotchi/tools/list_schedules.rb +3 -1
  64. data/lib/samagotchi/tools/list_sessions.rb +2 -1
  65. data/lib/samagotchi/tools/memory.rb +3 -2
  66. data/lib/samagotchi/tools/objectives_tool.rb +5 -4
  67. data/lib/samagotchi/tools/read.rb +2 -1
  68. data/lib/samagotchi/tools/register_reminder.rb +2 -1
  69. data/lib/samagotchi/tools/schedule_task.rb +3 -1
  70. data/lib/samagotchi/tools/send_note.rb +2 -1
  71. data/lib/samagotchi/tools/task_create.rb +2 -1
  72. data/lib/samagotchi/tools/task_get.rb +2 -1
  73. data/lib/samagotchi/tools/task_list.rb +2 -1
  74. data/lib/samagotchi/tools/task_runtime.rb +34 -154
  75. data/lib/samagotchi/tools/task_stop.rb +2 -1
  76. data/lib/samagotchi/tools/task_wait.rb +3 -2
  77. data/lib/samagotchi/tools/web_fetch.rb +2 -1
  78. data/lib/samagotchi/tools/write.rb +2 -1
  79. data/lib/samagotchi/turn_checkpoint.rb +1 -1
  80. data/lib/samagotchi/version.rb +1 -1
  81. data/lib/samagotchi/web/app.rb +38 -36
  82. data/lib/samagotchi/web/message_display.rb +1 -7
  83. data/lib/samagotchi/web/participant_access.rb +12 -4
  84. data/lib/samagotchi/web/participant_history.rb +68 -0
  85. data/lib/samagotchi/web/participant_images.rb +2 -1
  86. data/lib/samagotchi/web/participant_show.rb +5 -5
  87. data/lib/samagotchi/web/participants_admin.rb +1 -1
  88. data/lib/samagotchi/web/public/app.js +11 -9
  89. data/lib/samagotchi/web/public/card_registry.js +248 -0
  90. data/lib/samagotchi/web/public/cards_offscreen.js +3 -3
  91. data/lib/samagotchi/web/public/cards_place.js +8 -2
  92. data/lib/samagotchi/web/public/history_shape.js +1 -2
  93. data/lib/samagotchi/web/public/participant_history.js +27 -0
  94. data/lib/samagotchi/web/public/question_cards.js +1 -15
  95. data/lib/samagotchi/web/public/reload_check.js +90 -72
  96. data/lib/samagotchi/web/public/session_view.js +6 -1
  97. data/lib/samagotchi/web/public/stage_asking.js +6 -20
  98. data/lib/samagotchi/web/public/stage_view.js +2 -2
  99. data/lib/samagotchi/web/public/stage_waiting.js +4 -10
  100. data/lib/samagotchi/web/public/task_stop.js +1 -1
  101. data/lib/samagotchi/web/push_routes.rb +1 -1
  102. data/lib/samagotchi/web/reload_check_route.rb +5 -2
  103. data/lib/samagotchi/web/request_body.rb +72 -0
  104. data/lib/samagotchi/web/server.rb +70 -0
  105. data/lib/samagotchi/web/session_access_routes.rb +13 -11
  106. data/lib/samagotchi/web/session_control.rb +21 -15
  107. data/lib/samagotchi/web/session_create.rb +2 -1
  108. data/lib/samagotchi/web/session_show.rb +8 -8
  109. data/lib/samagotchi/web/viewer.rb +7 -2
  110. data/lib/samagotchi/web/working_set_routes.rb +3 -3
  111. data/lib/samagotchi/worker.rb +49 -182
  112. data/lib/samagotchi/worker_exit_claim.rb +102 -0
  113. data/lib/samagotchi/worker_participant_gate.rb +156 -0
  114. data/lib/samagotchi/worker_task_wakes.rb +2 -2
  115. metadata +13 -1
@@ -7,87 +7,95 @@
7
7
  // entries that would explain the differences (`explained`: all of them
8
8
  // have one), so chi web's log counts each class apart (the bugs turn
9
9
  // drawings close, the deliberate ones). It posts the counts, never
10
- // content: {turn_id, same, kinds, excused, explained, drawn, undrawn}; chi
10
+ // content: {turn_id, same, kinds, excused, explained, drawn, undrawn} (and
11
+ // cards_compared: false when the page passed no card registry); chi
11
12
  // web logs them (reload_checked, reload_mismatch). `undrawn`: how many rows
12
13
  // of the reload came without their turn's drawing (turn_block.js's plain
13
14
  // fallback, data-undrawn): 0 unless chi web missed one. Fire-and-forget: no toast, no
14
15
  // store write, a failure is dropped.
15
16
  //
16
- // Compared: the turn's own cards and questions too. A drawn turn already
17
- // renders its plugin cards (turn_block.js), and the snapshot's questions and
18
- // an undrawn turn's entries are placed into the offscreen holder by
19
- // cards_offscreen.js, the same placer the page uses with inert hooks. Only
20
- // entries CardStore attributes to this turn (of_turn) are compared; a card
21
- // the turn doesn't own (another turn's, a between-turn notice) is dropped on
22
- // both sides, and a question the read attributes to no turn and stamps to no
23
- // opening (an older worker) is dropped as well, since nothing places it.
24
- // What a card's equality means: its id and title, or a question's summary line
25
- // — not its body, its buttons, its fold or the tag it is drawn in.
26
- // Between-turn cards and notices are out of scope (the e2e reload checks
27
- // cover them).
17
+ // Compared apart: the turn's cards and questions, as data. The page's
18
+ // registry (card_registry.js, fed by the stream) against one seeded from the
19
+ // read: the entries of this turn (of_turn) on both sides, equal on key,
20
+ // kind, status and summary (not body, buttons, fold or the tag a card is
21
+ // drawn in). A difference adds "card" or "question" to +kinds+ (the same
22
+ // body: chi web's KINDS has both). CardStore keeps the newest
23
+ // CARD_STORE_CAP cards and questions together: a read that lists that many
24
+ // may have lost an older one, so a key live has and such a read hasn't is
25
+ // no difference. A question the read attributes to no turn and stamps to no
26
+ // opening (an older worker) leaves the questions out of it. The history's
27
+ // compare drops the card and question items on both sides (their place in
28
+ // a finished turn is stage_cuts_parity.test.js's turn-end cut and the e2e's
29
+ // reload checks now); it keeps notices, hook notices and guardrail
30
+ // warnings. Between-turn cards and notices are out of scope (the e2e
31
+ // reload checks cover them).
28
32
  import { compareShapes, historyShape } from "./history_shape.js";
29
- import { isCard, splitSnapshotCards } from "./card.js";
30
33
  import { turnElements } from "./turn_range.js";
34
+ import { createCardRegistry } from "./card_registry.js";
35
+ import { measured, probing } from "./stage_probe.js";
31
36
  // The opening of a turn (the stage's hand-off reads it too).
32
37
  import { OPENING } from "./stage_handoff.js";
33
38
  // Not the turn's: the lines queued for after it (they open the next turns).
34
39
  const NOT_THE_TURNS = ".bubble.user.queued, .bubble.command.queued";
40
+ // Bridge::CardStore::CAPACITY: the cards and questions a read lists at most
41
+ // (spec/web/reload_check_route_spec.rb reads it).
42
+ const CARD_STORE_CAP = 20;
35
43
 
36
44
  function openingId(el) {
37
45
  return el?.dataset?.turnId || el?.dataset?.openingId || null;
38
46
  }
39
47
 
40
- // The snapshot entries this turn owns (CardStore's of_turn): a drawn turn
41
- // already renders its cards, so only its questions come from the placer; an
42
- // undrawn turn has all of them placed, as a reload places them. Entries the
43
- // page shows elsewhere, the running turn's and the ones that came during it
44
- // are out (splitSnapshotCards), as in session_view.js.
45
- function turnEntries(cards, capabilities, turnId, drawn) {
46
- const placed = splitSnapshotCards(cards, capabilities).placed.filter((entry) => entry?.of_turn === turnId);
47
- return drawn ? placed.filter((entry) => entry?.type === "question") : placed;
48
- }
49
-
50
48
  // A question the read attributes to no turn (an older worker: no of_turn, and
51
- // no opening it came after, or one stamped to this very turn) has nothing to
52
- // place it from, so its card is left out of the compare. Only entries that
53
- // could belong to this turn count: one stamped to another turn does not
54
- // silence questions here.
49
+ // no opening it came after, or one stamped to this very turn): the registry
50
+ // can't say whose it is, so the questions are left out of the compare. Only
51
+ // entries that could belong to this turn count: one stamped to another turn
52
+ // does not silence questions here.
55
53
  function looseQuestions(cards, turnId) {
56
54
  return (Array.isArray(cards) ? cards : []).some((entry) => entry?.type === "question"
57
55
  && entry?.of_turn == null && (entry?.opening_id == null || String(entry.opening_id) === String(turnId)));
58
56
  }
59
57
 
60
- // The ids of the snapshot's cards that are not this turn's.
61
- function foreignIds(cards, turnId) {
62
- return new Set((Array.isArray(cards) ? cards : [])
63
- .filter((entry) => isCard(entry) && entry?.of_turn !== turnId)
64
- .map((entry) => String(entry.id ?? "")));
58
+ // Whether CardStore's cap may have pushed one of this turn's entries out of
59
+ // +cards+ (the read's listing).
60
+ function capped(cards) {
61
+ return (Array.isArray(cards) ? cards : []).filter((entry) => entry?.type === "card" || entry?.type === "question").length >= CARD_STORE_CAP;
65
62
  }
66
63
 
67
- // This turn's items only: a card of another turn or between turns is dropped
68
- // by id; a question the worker didn't attribute to a turn (an older worker)
69
- // has nothing to place it from, so questions are dropped on both sides.
70
- function turnOnly(shape, foreign, questions) {
71
- return shape.filter((item) => {
72
- if (item.kind === "card") return !foreign.has(item.id);
73
- if (item.kind === "question") return questions;
74
- return true;
75
- });
64
+ // The kinds ("card", "question") in which the turn's entries live and in the
65
+ // read differ.
66
+ function cardKinds(live, reloaded, { capped: lossy, questions }) {
67
+ const kinds = new Set();
68
+ const kindOf = (key) => (key.startsWith("q:") ? "question" : "card");
69
+ const mine = (list) => new Map(list.filter((e) => questions || !e.key.startsWith("q:")).map((e) => [e.key, e]));
70
+ const a = mine(live);
71
+ const b = mine(reloaded);
72
+ for (const [key, e] of a) {
73
+ const r = b.get(key);
74
+ if (!r) {
75
+ if (!lossy) kinds.add(kindOf(key));
76
+ continue;
77
+ }
78
+ if (["kind", "status", "summary"].some((f) => e[f] !== r[f])) kinds.add(kindOf(key));
79
+ }
80
+ for (const key of b.keys()) if (!a.has(key)) kinds.add(kindOf(key));
81
+ return [...kinds];
76
82
  }
77
83
 
84
+ const NOT_CARDS = (item) => item.kind !== "card" && item.kind !== "question";
85
+
78
86
  // @param enabled () => whether the check is on (the body's attribute)
79
87
  // @param sessionId () => the open session's id
80
88
  // @param running () => whether a turn runs now (liveTurn.running: a queued
81
89
  // turn started streaming)
82
90
  // @param read (id) => the session as a reload reads it (the full GET)
83
91
  // @param render (data) => that read drawn as a reload draws it (a fragment)
84
- // @param place (holder, entries) puts the turn's snapshot entries into that
85
- // holder as a reload's placement would (cards_offscreen.js); without it,
86
- // cards and questions are dropped from both sides
87
- // @param capabilities () => the page's capabilities (which notices it shows
88
- // elsewhere)
92
+ // @param cards () => the page's card registry (card_registry.js); without
93
+ // it, the cards and questions are left out
94
+ // @param place unused: an older app.js passes cards_offscreen.js's placer
95
+ // @param capabilities () => the page's capabilities (unused now; an older
96
+ // app.js passes it)
89
97
  // @param post (id, body) => the counts to chi web
90
- export function createReloadCheck({ enabled, sessionId, running, read, render, place = null, capabilities = () => null, post }) {
98
+ export function createReloadCheck({ enabled, sessionId, running, read, render, cards = null, post }) {
91
99
  // The hand-off's pieces (stage_view.js onHandedOff), in their order;
92
100
  // +immediate+: another turn took the stage at once.
93
101
  async function handedOff({ pieces = [], immediate = false } = {}) {
@@ -96,36 +104,46 @@ export function createReloadCheck({ enabled, sessionId, running, read, render, p
96
104
  const turnId = openingId(opening?.matches?.(OPENING) ? opening : null);
97
105
  if (!turnId) return;
98
106
  const id = sessionId();
107
+ const handedAt = performance.now();
99
108
  try {
100
109
  const data = await read(id);
101
110
  if (sessionId() !== id || running()) return;
102
- // The live pieces as they read now, after the read: a canceled or
103
- // failed turn hands off at once, and its timing line takes the turn
104
- // record's figure when its own re-read lands (refreshTimingFromSession),
105
- // which started at the turn's end, before this one.
106
- // Whether the read had a drawing for the turn (turn drawings, P2): a
107
- // drawn one already renders its own cards, an undrawn one has them
108
- // placed after the render.
109
- const drawn = !!data?.turn_drawings?.[turnId];
110
- const entries = place ? turnEntries(data.cards, capabilities(), turnId, drawn) : [];
111
- // A question the read can't place for this turn (see looseQuestions) is
112
- // left out of the compare on both sides.
113
- const questions = !!place && !looseQuestions(data.cards, turnId);
114
- const shapeOf = (shape) => turnOnly(shape, foreignIds(data.cards, turnId), questions);
115
- const live = shapeOf(historyShape(rest.filter((el) => !el.matches?.(NOT_THE_TURNS))));
116
- const holder = document.createElement("div");
117
- holder.append(render(data));
118
- // The turn's own cards and questions, where a reload would put them.
119
- if (place) place(holder, entries);
120
- const reopened = [...holder.querySelectorAll(OPENING)].find((el) => openingId(el) === turnId);
121
- const reloaded = reopened ? shapeOf(historyShape(turnElements(reopened, { container: holder }))) : [];
122
- const { same, kinds, excused, explained } = reopened ? compareShapes(live, reloaded)
123
- : { same: false, kinds: ["prompt"], excused: [], explained: false };
124
- const undrawn = holder.querySelectorAll("[data-undrawn]").length;
125
- await post(id, { turn_id: turnId, same, kinds, excused, explained, drawn, undrawn });
111
+ // The perf probe (stage_probe.js): the compare's own time, and the
112
+ // hand-off to the post.
113
+ const body = measured("reload:compare", () => compare(data, rest, turnId));
114
+ await post(id, body);
115
+ if (probing()) performance.measure("reload:posted", { start: handedAt, end: performance.now() });
126
116
  } catch (_) {
127
117
  // Fire-and-forget: a failed read or post is no finding.
128
118
  }
129
119
  }
120
+
121
+ // The counts for the turn +turnId+: the live pieces (+rest+, after its
122
+ // opening) against +data+, the read.
123
+ function compare(data, rest, turnId) {
124
+ // The live pieces as they read now, after the read: a canceled or
125
+ // failed turn hands off at once, and its timing line takes the turn
126
+ // record's figure when its own re-read lands (refreshTimingFromSession),
127
+ // which started at the turn's end, before this one.
128
+ // Whether the read had a drawing for the turn (turn drawings, P2).
129
+ const drawn = !!data?.turn_drawings?.[turnId];
130
+ const live = historyShape(rest.filter((el) => !el.matches?.(NOT_THE_TURNS))).filter(NOT_CARDS);
131
+ const holder = document.createElement("div");
132
+ holder.append(render(data));
133
+ const reopened = [...holder.querySelectorAll(OPENING)].find((el) => openingId(el) === turnId);
134
+ const reloaded = reopened ? historyShape(turnElements(reopened, { container: holder })).filter(NOT_CARDS) : [];
135
+ const verdict = reopened ? compareShapes(live, reloaded)
136
+ : { same: false, kinds: ["prompt"], excused: [], explained: false };
137
+ const registry = cards?.();
138
+ const cardsDiffer = registry ? cardKinds(registry.forTurn(turnId), createCardRegistry().seed(data).forTurn(turnId),
139
+ { capped: capped(data?.cards), questions: !looseQuestions(data?.cards, turnId) }) : [];
140
+ const kinds = [...verdict.kinds, ...cardsDiffer.filter((k) => !verdict.kinds.includes(k))];
141
+ const same = verdict.same && !cardsDiffer.length;
142
+ const explained = verdict.explained && !cardsDiffer.length;
143
+ const undrawn = holder.querySelectorAll("[data-undrawn]").length;
144
+ // No registry (a stale app.js): cards and questions went unchecked, so
145
+ // a "same" is the history's alone.
146
+ return { turn_id: turnId, same, kinds, excused: verdict.excused, explained, drawn, undrawn, ...(registry ? {} : { cards_compared: false }) };
147
+ }
130
148
  return { handedOff };
131
149
  }
@@ -19,6 +19,8 @@
19
19
  // wsPreview its reader and peek (ws_reader.js), null without them: reset with the session
20
20
  // gapClock the page's last activity (time_gaps.js createGapClock)
21
21
  // bubbles, cards bubbles.js, cards_place.js
22
+ // cardRegistry the open session's cards as data (card_registry.js): seeded
23
+ // from a read before its replay, reset with the session; null: none
22
24
  // markdown markdown_place.js (linkTextRefs, applyFinalMarkdown)
23
25
  // capabilities() the page's capabilities (card.js shownElsewhere, the history's cards)
24
26
  // page: {setReviseAnchor(anchor), renderInitRow(), setMarkdownWarning(warning),
@@ -49,7 +51,7 @@ export function createSessionView(deps) {
49
51
  const {
50
52
  store, historyEl, getSession,
51
53
  liveTurn, turnDom, questionCards, shownTexts, objectives, featureGates, markdownTip, workingSet = null, wsPreview = null, gapClock,
52
- bubbles, cards, markdown, capabilities, page, later,
54
+ bubbles, cards, markdown, capabilities, page, later, cardRegistry = null,
53
55
  } = deps;
54
56
  const { makeUserBubble, addEndBubble, showGuardrailWarning, showRecap } = bubbles;
55
57
  const { placeSnapshotCards, upsertCard } = cards;
@@ -78,6 +80,7 @@ export function createSessionView(deps) {
78
80
  });
79
81
  later.commandList().close();
80
82
  later.resetTurnView();
83
+ cardRegistry?.reset();
81
84
  objectives.reset();
82
85
  seedInitTasks(later.initTasks(), []);
83
86
  renderInitRow();
@@ -144,6 +147,8 @@ export function createSessionView(deps) {
144
147
  // chi web's unfold of the join (TurnAccumulator.join_events): the turn in
145
148
  // progress and the queue behind it as the live events that draw them.
146
149
  const replay = data.replay ?? [];
150
+ // The cards as data: the read first, then its replay (card_registry.js).
151
+ cardRegistry?.seed(data);
147
152
  // Marked replayed: a call's duration isn't timed from the replay's clock.
148
153
  replay.forEach((event) => later.handlers()[event.type]?.({ ...event, replayed: true }));
149
154
  // A join mid-generation: the worker's word on it clocks the delivery line.
@@ -8,9 +8,8 @@
8
8
  import { handOffOrder, stageCollapsed } from "./stage_model.js";
9
9
  import { readStored, writeStored } from "./storage.js";
10
10
  import { ASKS, PENDING, waitsInStage } from "./stage_cards.js";
11
- import { cardIn, waitingKey, waitingKind } from "./stage_waiting.js";
11
+ import { cardIn, waitingKey } from "./stage_waiting.js";
12
12
  import { warnDiffers } from "./card_kinds.js";
13
- import { probing } from "./stage_probe.js";
14
13
 
15
14
  const COLLAPSE_KEY = "chi_stage_collapsed";
16
15
  // The cards that get a lead-in bubble when their step wrote text: chi's own
@@ -125,24 +124,11 @@ export function createStageAsking({
125
124
  opener.open(handOffOrder({ prompt: promptEl(), block: blockEl, extras: rows }), { follow });
126
125
  }
127
126
 
128
- // The waiting cards as data against the slots, a debug check only (the
129
- // perf probe, or <body data-stage-check="1">: the e2e and the tests): an
130
- // entry whose card is gone from the extras and the tail or waits no more,
131
- // or a card in them that waits with no entry, warns "stage: waiting drift".
132
- // It settles nothing: every way a card stops waiting settles through a
133
- // hook (stage_waiting.js). Off, it returns at once.
134
- function reconcileWaiting() {
135
- if (!probing() && globalThis.document?.body?.dataset?.stageCheck !== "1") return;
136
- const keys = new Set();
137
- for (const { key } of waiting.list()) {
138
- keys.add(key);
139
- if (!waitingKind(cardIn(extras, key) || cardIn(tail, key))) console.warn("stage: waiting drift", key);
140
- }
141
- for (const el of [...(extras?.children || []), ...(tail?.children || [])]) {
142
- const key = waitingKey(el);
143
- if (key && waitingKind(el) && !keys.has(key)) console.warn("stage: waiting drift", key);
144
- }
145
- }
127
+ // A no-op kept one release for a mixed cache (remove in the next one): a
128
+ // stale stage_view.js (0.172.1's) calls it at the end of each refresh. The
129
+ // drift check it ran is the tests' now (stage_cuts_parity.test.js
130
+ // crossCheck, the e2e's stage check).
131
+ function reconcileWaiting() {}
146
132
 
147
133
  // An opened turn's cards that stopped waiting go into the history: one
148
134
  // with a lead-in under it (also after the turn's end, so a card
@@ -199,6 +199,8 @@ export function createStageView({
199
199
  // docked card, its fold, what blocks, the approval's cap read them. The
200
200
  // fold of the asking card is this tab's own, kept per session.
201
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();
202
204
  let dockedAtLastRefresh = [];
203
205
  // The asking form and the stage's fold (stage_asking.js).
204
206
  const ask = createStageAsking({
@@ -379,8 +381,6 @@ export function createStageView({
379
381
  extras.hidden = !extras.firstChild;
380
382
  answer.hidden = !answer.firstChild;
381
383
  tail.hidden = !tail.firstChild;
382
- // The registry against the slots: a debug check only (stage_asking.js).
383
- ask.reconcileWaiting();
384
384
  }
385
385
 
386
386
  // The next step after a blocking card's answer, or an answer that leaves
@@ -10,12 +10,10 @@
10
10
  // answered, cancelled or resolved for good, which removes its stored fold), from
11
11
  // cards_place.js upsertCard for a plugin card redrawn without its actions,
12
12
  // and from stage_view.js turnEnded for the warn cards leaving with the
13
- // block; +reset+ from stage_view.js emptySlots. Settle is the one way out:
14
- // +reconcile+ (the old second feed, which dropped an entry whose card was
15
- // gone or waited no more) is called by nobody now and stays one release
16
- // for a mixed cache (an older stage_asking.js calls it); stage_asking.js
17
- // reconcileWaiting only compares and warns (a debug check). Arrive is the
18
- // 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.
19
17
  //
20
18
  // A card's entry: its kind (KINDS), docked (it shows alone in the box above
21
19
  // the composer, its turn opened in the history: stage_asking.js docks; its
@@ -190,10 +188,6 @@ export function createStageWaiting({ sessionId = null, storage = tabStorage } =
190
188
  foldedWith = 0;
191
189
  paged = null;
192
190
  },
193
- // The second feed: every entry +waits+(key, kind) says no to settles.
194
- reconcile(waits) {
195
- for (const [key, { kind }] of [...cards.entries()]) if (!waits(key, kind)) cards.delete(key);
196
- },
197
191
  has: (key) => cards.has(key),
198
192
  get: (key) => (cards.has(key) ? { key, ...cards.get(key) } : null),
199
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.
@@ -14,6 +14,7 @@ require_relative "../client_id"
14
14
  require_relative "../children_status"
15
15
  require_relative "../session_metrics"
16
16
  require_relative "../version"
17
+ require_relative "request_body"
17
18
  require_relative "session_hub"
18
19
 
19
20
  module Samagotchi
@@ -63,8 +64,9 @@ module Samagotchi
63
64
  end
64
65
 
65
66
  # The body as a Hash ({} when there is none), or nil when it isn't one.
66
- def body_hash(req)
67
- raw = request_body(req)
67
+ # Read up to +limit+ bytes (RequestBody: over it is the 413).
68
+ def body_hash(req, limit = RequestBody::SMALL_BODY_LIMIT)
69
+ raw = request_body(req, limit)
68
70
  return {} if raw.to_s.strip.empty?
69
71
 
70
72
  parsed = parse_json(raw)
@@ -80,12 +82,12 @@ module Samagotchi
80
82
  # where input for it goes (SessionAccess::Local#head): 200 {id, asked,
81
83
  # via}, id the chain's newest link of a continued one.
82
84
  def handle_resolve(req)
83
- given = req.params["id"].to_s
85
+ given = req.GET["id"].to_s
84
86
  return session_not_found(given) unless Session.valid_id?(given)
85
87
  return participant_resolve(principal(req).grant, given) unless principal(req).owner?
86
88
 
87
89
  id = session_access.resolve(given)
88
- return json_response(200, { id: id }) unless truthy_param?(req.params["head"])
90
+ return json_response(200, { id: id }) unless truthy_param?(req.GET["head"])
89
91
 
90
92
  head = session_access.head(id)
91
93
  json_response(200, { id: head.id, asked: head.asked, via: head.via.to_s })
@@ -122,18 +124,18 @@ module Samagotchi
122
124
  # folder or below), live=1, archived=1, tests=0 (leave test runs out),
123
125
  # sort, order, limit. An array, newest first by default.
124
126
  def handle_summaries(req)
125
- dir, error = scope_dir(req.params["dir"])
127
+ dir, error = scope_dir(req.GET["dir"])
126
128
  return error if error
127
129
 
128
- cwd = req.params["cwd"].to_s
130
+ cwd = req.GET["cwd"].to_s
129
131
  cwd = nil if cwd.strip.empty?
130
132
  return error_response(400, "invalid_cwd", "cwd is an absolute path: #{cwd[0, 200]}") if cwd && !cwd.start_with?("/")
131
133
 
132
134
  rows = session_access.summaries(
133
- live: truthy_param?(req.params["live"]), cwd: cwd, limit: sanitize_limit(req.params["limit"]),
134
- include_tests: !%w[0 false no].include?(req.params["tests"].to_s.strip.downcase),
135
- project_root: dir && ProjectScope.root_for(dir), include_archived: truthy_param?(req.params["archived"]),
136
- sort: sanitize_sort(req.params["sort"]), order: sanitize_order(req.params["order"])
135
+ live: truthy_param?(req.GET["live"]), cwd: cwd, limit: sanitize_limit(req.GET["limit"]),
136
+ include_tests: !%w[0 false no].include?(req.GET["tests"].to_s.strip.downcase),
137
+ project_root: dir && ProjectScope.root_for(dir), include_archived: truthy_param?(req.GET["archived"]),
138
+ sort: sanitize_sort(req.GET["sort"]), order: sanitize_order(req.GET["order"])
137
139
  )
138
140
  json_response(200, rows.map(&:to_summary_h))
139
141
  end
@@ -465,7 +467,7 @@ module Samagotchi
465
467
  # which an older Remote reads as not_push, nor "continued", which it
466
468
  # reads as a continue's refusal); 400 invalid_text.
467
469
  def handle_context_push(req, id, name)
468
- body = body_hash(req) or return error_response(400, "invalid_json", "invalid JSON body")
470
+ body = body_hash(req, RequestBody::CONTEXT_PUSH_BODY_LIMIT) or return error_response(400, "invalid_json", "invalid JSON body")
469
471
  return error_response(400, "missing_fields", "text is required") unless body["text"].is_a?(String)
470
472
 
471
473
  fetched = begin