samagotchi 0.172.1 → 0.174.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 (143) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +61 -1
  3. data/docs/architecture.md +16 -5
  4. data/docs/cli.md +11 -3
  5. data/docs/configuration.md +1 -1
  6. data/docs/internals/background-tasks.md +16 -6
  7. data/docs/internals/bridge.md +2 -2
  8. data/docs/internals/engine.md +2 -1
  9. data/docs/internals/participants.md +69 -9
  10. data/docs/internals/remote-sessions.md +9 -1
  11. data/docs/internals/web-frontend.md +34 -8
  12. data/docs/plugins.md +1 -1
  13. data/docs/scheduling.md +9 -3
  14. data/docs/sessions.md +5 -3
  15. data/docs/testing.md +32 -10
  16. data/lib/samagotchi/bridge.rb +4 -3
  17. data/lib/samagotchi/bundle_command/try/sandbox.rb +2 -2
  18. data/lib/samagotchi/bundles/core/manifest.yml +2 -2
  19. data/lib/samagotchi/bundles/slow-commands/manifest.yml +3 -3
  20. data/lib/samagotchi/bundles/slow-commands/plugin.rb +3 -3
  21. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  22. data/lib/samagotchi/child_move.rb +11 -4
  23. data/lib/samagotchi/continued_from.rb +51 -0
  24. data/lib/samagotchi/engine/participants.rb +2 -2
  25. data/lib/samagotchi/engine.rb +1 -2
  26. data/lib/samagotchi/file_ref.rb +3 -5
  27. data/lib/samagotchi/guardrails/participant_refusal.rb +1 -1
  28. data/lib/samagotchi/memory_usage.rb +2 -1
  29. data/lib/samagotchi/message_parts.rb +5 -3
  30. data/lib/samagotchi/note_move.rb +11 -4
  31. data/lib/samagotchi/objectives_backing.rb +6 -10
  32. data/lib/samagotchi/parent_report.rb +1 -1
  33. data/lib/samagotchi/participant_prompts.rb +101 -0
  34. data/lib/samagotchi/participant_turn_mode.rb +1 -1
  35. data/lib/samagotchi/project_env.rb +7 -5
  36. data/lib/samagotchi/prompt_history.rb +2 -2
  37. data/lib/samagotchi/schedules.rb +13 -16
  38. data/lib/samagotchi/send_command/parent_gate.rb +2 -2
  39. data/lib/samagotchi/send_command.rb +4 -4
  40. data/lib/samagotchi/session_access/contract.rb +1 -0
  41. data/lib/samagotchi/session_access/local.rb +9 -1
  42. data/lib/samagotchi/session_access/remote.rb +26 -3
  43. data/lib/samagotchi/session_chain/delete.rb +405 -0
  44. data/lib/samagotchi/session_chain/delete_preview.rb +96 -0
  45. data/lib/samagotchi/session_chain/links.rb +38 -0
  46. data/lib/samagotchi/session_command_catalog.rb +210 -0
  47. data/lib/samagotchi/session_commands.rb +6 -187
  48. data/lib/samagotchi/session_continue.rb +51 -13
  49. data/lib/samagotchi/session_delete_command.rb +82 -17
  50. data/lib/samagotchi/session_manager/lifecycle.rb +5 -4
  51. data/lib/samagotchi/session_manager/removal.rb +137 -31
  52. data/lib/samagotchi/session_manager.rb +2 -1
  53. data/lib/samagotchi/session_stores.rb +4 -0
  54. data/lib/samagotchi/spawn_env.rb +75 -0
  55. data/lib/samagotchi/task_files.rb +51 -0
  56. data/lib/samagotchi/task_transcript.rb +67 -0
  57. data/lib/samagotchi/task_watch.rb +8 -6
  58. data/lib/samagotchi/terminal_ui/attached_loop/composer.rb +3 -3
  59. data/lib/samagotchi/terminal_ui/attached_loop/exit_commands.rb +2 -2
  60. data/lib/samagotchi/terminal_ui/attached_loop/questions.rb +2 -2
  61. data/lib/samagotchi/terminal_ui/attached_loop.rb +4 -4
  62. data/lib/samagotchi/terminal_ui/exit_lines.rb +16 -0
  63. data/lib/samagotchi/terminal_ui/input_support.rb +1 -1
  64. data/lib/samagotchi/terminal_ui/local_link.rb +7 -1
  65. data/lib/samagotchi/terminal_ui.rb +3 -3
  66. data/lib/samagotchi/testing/boundary.rb +2 -2
  67. data/lib/samagotchi/testing/bundle.rb +1 -1
  68. data/lib/samagotchi/tool_activity.rb +63 -79
  69. data/lib/samagotchi/tool_names.rb +179 -0
  70. data/lib/samagotchi/tool_view.rb +3 -5
  71. data/lib/samagotchi/tools/ask_user_question.rb +2 -1
  72. data/lib/samagotchi/tools/builtins.rb +1 -1
  73. data/lib/samagotchi/tools/cancel_reminder.rb +2 -1
  74. data/lib/samagotchi/tools/cancel_schedule.rb +3 -1
  75. data/lib/samagotchi/tools/context_read.rb +2 -1
  76. data/lib/samagotchi/tools/delegate.rb +2 -1
  77. data/lib/samagotchi/tools/delegate_result.rb +2 -1
  78. data/lib/samagotchi/tools/edit.rb +2 -1
  79. data/lib/samagotchi/tools/execute.rb +22 -28
  80. data/lib/samagotchi/tools/forget_outputs.rb +2 -1
  81. data/lib/samagotchi/tools/list_reminders.rb +2 -1
  82. data/lib/samagotchi/tools/list_schedules.rb +3 -1
  83. data/lib/samagotchi/tools/list_sessions.rb +2 -1
  84. data/lib/samagotchi/tools/memory.rb +3 -2
  85. data/lib/samagotchi/tools/objectives_tool.rb +5 -4
  86. data/lib/samagotchi/tools/read.rb +2 -1
  87. data/lib/samagotchi/tools/register_reminder.rb +2 -1
  88. data/lib/samagotchi/tools/schedule_task.rb +3 -1
  89. data/lib/samagotchi/tools/send_note.rb +2 -1
  90. data/lib/samagotchi/tools/task_create.rb +2 -1
  91. data/lib/samagotchi/tools/task_get.rb +2 -1
  92. data/lib/samagotchi/tools/task_list.rb +2 -1
  93. data/lib/samagotchi/tools/task_runtime.rb +29 -154
  94. data/lib/samagotchi/tools/task_stop.rb +2 -1
  95. data/lib/samagotchi/tools/task_wait.rb +3 -2
  96. data/lib/samagotchi/tools/web_fetch.rb +2 -1
  97. data/lib/samagotchi/tools/write.rb +2 -1
  98. data/lib/samagotchi/turn_checkpoint.rb +1 -1
  99. data/lib/samagotchi/version.rb +1 -1
  100. data/lib/samagotchi/web/app.rb +45 -37
  101. data/lib/samagotchi/web/message_display.rb +1 -7
  102. data/lib/samagotchi/web/participant_access.rb +12 -4
  103. data/lib/samagotchi/web/participant_history.rb +68 -0
  104. data/lib/samagotchi/web/participant_images.rb +2 -1
  105. data/lib/samagotchi/web/participant_show.rb +5 -5
  106. data/lib/samagotchi/web/participants_admin.rb +1 -1
  107. data/lib/samagotchi/web/public/app.js +24 -12
  108. data/lib/samagotchi/web/public/card_registry.js +248 -0
  109. data/lib/samagotchi/web/public/cards_offscreen.js +3 -3
  110. data/lib/samagotchi/web/public/cards_place.js +8 -2
  111. data/lib/samagotchi/web/public/chains.js +3 -3
  112. data/lib/samagotchi/web/public/data.js +12 -0
  113. data/lib/samagotchi/web/public/delete_sheet.js +344 -0
  114. data/lib/samagotchi/web/public/format.js +1 -1
  115. data/lib/samagotchi/web/public/history_shape.js +1 -2
  116. data/lib/samagotchi/web/public/index.html +27 -0
  117. data/lib/samagotchi/web/public/info_bar.js +3 -2
  118. data/lib/samagotchi/web/public/lists_view.js +2 -2
  119. data/lib/samagotchi/web/public/more_sheet.js +42 -5
  120. data/lib/samagotchi/web/public/participant_history.js +27 -0
  121. data/lib/samagotchi/web/public/question_cards.js +1 -15
  122. data/lib/samagotchi/web/public/reload_check.js +90 -72
  123. data/lib/samagotchi/web/public/session_actions.js +50 -6
  124. data/lib/samagotchi/web/public/session_view.js +6 -1
  125. data/lib/samagotchi/web/public/stage_asking.js +6 -20
  126. data/lib/samagotchi/web/public/stage_view.js +2 -2
  127. data/lib/samagotchi/web/public/stage_waiting.js +4 -10
  128. data/lib/samagotchi/web/public/task_stop.js +1 -1
  129. data/lib/samagotchi/web/push_routes.rb +1 -1
  130. data/lib/samagotchi/web/reload_check_route.rb +5 -2
  131. data/lib/samagotchi/web/request_body.rb +72 -0
  132. data/lib/samagotchi/web/server.rb +70 -0
  133. data/lib/samagotchi/web/session_access_routes.rb +13 -11
  134. data/lib/samagotchi/web/session_control.rb +79 -20
  135. data/lib/samagotchi/web/session_create.rb +2 -1
  136. data/lib/samagotchi/web/session_show.rb +8 -8
  137. data/lib/samagotchi/web/viewer.rb +7 -2
  138. data/lib/samagotchi/web/working_set_routes.rb +3 -3
  139. data/lib/samagotchi/worker.rb +49 -182
  140. data/lib/samagotchi/worker_exit_claim.rb +102 -0
  141. data/lib/samagotchi/worker_participant_gate.rb +156 -0
  142. data/lib/samagotchi/worker_task_wakes.rb +2 -2
  143. metadata +17 -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
  }
@@ -2,6 +2,7 @@ import { continueRefusal, continuedText, openChildrenTemplate, openerText } from
2
2
  import { cantText, deleteConfirmText, goneSessionNotice } from "./format.js";
3
3
  import { sessionHash } from "./route.js";
4
4
  import { inTree } from "./sessions_list.js";
5
+ import { isChained, listAfterDelete, deleteToast, runDeleteFlow } from "./delete_sheet.js";
5
6
 
6
7
  // What the page does to a whole session (used by app.js): Continue, Archive
7
8
  // and Unarchive, Delete and Stop, from the info bar's buttons, a card's or a
@@ -13,7 +14,8 @@ import { inTree } from "./sessions_list.js";
13
14
  // +setSessions(list)+ the page's list (the store's: a new list redraws the
14
15
  // lists and the bar);
15
16
  // +api+: {continueSession, archiveSession, unarchiveSession,
16
- // deleteSession, stopSession, sessionHolds, stopSessionHolds} (data.js);
17
+ // deleteSession, deleteChain, deletePlan, stopSession, sessionHolds,
18
+ // stopSessionHolds} (data.js);
17
19
  // +eventsLive()+ the hub's stream is open (else
18
20
  // +refresh()+ fetches the list);
19
21
  // +select(id)+, +clearSelection()+, +showNotice(text)+,
@@ -31,20 +33,62 @@ export function createSessionActions({
31
33
  // true; nothing to stop (or no sheet wired) is false, and Stop is the
32
34
  // confirm.
33
35
  stopSheet = { open: () => false },
36
+ // A card's delete sheet (delete_sheet.js createDeleteSheet): +host(anchor)+
37
+ // draws a chained session's choices at it.
38
+ deleteSheet = null,
34
39
  }) {
35
40
  // The session this tab is stopping: its stream may close before the stop
36
41
  // request returns (workerGone reads it).
37
42
  let stoppingId = null;
38
43
 
39
- // Delete a session (the info bar's button, an all-sessions card's ✕) after
40
- // a confirm; the list drops it without a reload. The server stops a live
41
- // worker first and refuses a session a terminal chi has open.
42
- async function confirmDelete(id) {
44
+ // Delete a session (the ⋯ More panel's Delete, an all-sessions card's ✕).
45
+ // A chained session gets the delete sheet (delete_sheet.js): in the More
46
+ // panel's place (deleteIn), at the card's ✕ (+anchor+), else at ⋯. Any
47
+ // other keeps today's confirm. The list drops what went without a reload.
48
+ // The server stops a live worker first and refuses a session a terminal
49
+ // chi has open.
50
+ async function confirmDelete(id, { anchor = null } = {}) {
43
51
  const sess = sessions().find((s) => s.id === id) || { id };
44
52
  if (sess.owner === "tui") {
45
53
  alert(`Session ${id.slice(0, 8)} is open in a terminal chi; close it there first.`);
46
54
  return;
47
55
  }
56
+ if (deleteSheet && api.deletePlan && isChained(sess, sessions())) {
57
+ const at = anchor || globalThis.document?.querySelector("#infoMoreBtn");
58
+ if (at) { startDeleteFlow(id, sess, deleteSheet.host(at, id)); return; }
59
+ }
60
+ await plainDelete(id, sess);
61
+ }
62
+
63
+ // The More panel's Delete: true when it took +host+ (a chained session).
64
+ function deleteIn(id, host) {
65
+ const sess = sessions().find((s) => s.id === id);
66
+ if (!sess || sess.owner === "tui" || !api.deletePlan || !isChained(sess, sessions())) return false;
67
+ startDeleteFlow(id, sess, host);
68
+ return true;
69
+ }
70
+
71
+ function startDeleteFlow(id, sess, host) {
72
+ const flow = runDeleteFlow({
73
+ id, session: sess, host, api,
74
+ done: (which, result, plan) => afterDelete(id, which, result, plan),
75
+ plain: () => plainDelete(id, sess),
76
+ failed: (error) => alert(`Could not delete session ${id.slice(0, 8)}: ${error.message}`),
77
+ });
78
+ host.wire(flow);
79
+ }
80
+
81
+ function afterDelete(id, which, result, plan) {
82
+ setSessions(listAfterDelete(sessions(), result));
83
+ const gone = new Set(result.deleted || [id]);
84
+ if (gone.has(selected())) clearSelection();
85
+ if (!eventsLive()) refresh();
86
+ const { text, back } = deleteToast(which, result, plan, id);
87
+ toast(text, back ? { label: `Open ${back.slice(0, 8)}`, run: () => select(back) } : null);
88
+ }
89
+
90
+ // Today's confirm: a session in no chain.
91
+ async function plainDelete(id, sess) {
48
92
  if (!confirm(deleteConfirmText(sess))) return;
49
93
  try {
50
94
  await api.deleteSession(id);
@@ -245,7 +289,7 @@ export function createSessionActions({
245
289
  }
246
290
 
247
291
  return {
248
- confirmDelete, leaveGoneSession, stopSelected, continueSelected, archiveOne, setArchived, toggleArchiveSelected,
292
+ confirmDelete, deleteIn, leaveGoneSession, stopSelected, continueSelected, archiveOne, setArchived, toggleArchiveSelected,
249
293
  // The sessions whose Continue is under way (the info bar's button).
250
294
  continuing: continuingIds,
251
295
  // The session this tab is stopping, or null.
@@ -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 with a body, a successful
95
+ # answer to a large body the app may have left unread (over the small
96
+ # body limit or any Transfer-Encoding), and any answer with
97
+ # Connection: close end the connection: otherwise WEBrick drains the
98
+ # unread body before answering, holding a thread for an unbounded
99
+ # upload. One rule here, not per route. A small body on a 2xx/3xx stays
100
+ # alive; a hijacked stream is left to its own.
101
+ module CloseOnConnectionClose
102
+ def service(req, res)
103
+ super
104
+ return if res.body.respond_to?(:call)
105
+
106
+ content_length = req["content-length"].to_i
107
+ transfer_encoding = !req["transfer-encoding"].nil?
108
+ body = content_length.positive? || transfer_encoding
109
+ large_body = content_length > RequestBody::SMALL_BODY_LIMIT || transfer_encoding
110
+ close_for_body = body && (res.status >= 400 || large_body)
111
+ return unless res["connection"].to_s.casecmp?("close") || close_for_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.