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,27 @@
1
+ // A participant's ↑/↓ list: their own accepted messages in this session,
2
+ // oldest first, as their conversation shows them (redacted), from
3
+ // GET /api/sessions/<id>/prompt_history (Web::ParticipantHistory; the
4
+ // viewer's own_prompt_history). Never the owner's /api/history. A module of
5
+ // its own for the mixed-cache rule (docs/internals/web-frontend.md).
6
+ import { api } from "./data.js";
7
+
8
+ export function fetchOwnHistory(id, opts = {}) {
9
+ return api(`/api/sessions/${encodeURIComponent(id)}/prompt_history`, opts)
10
+ .then((j) => (Array.isArray(j.entries) ? j.entries : []));
11
+ }
12
+
13
+ // The composer's loadHistory for +viewer+: the owner's shared history, a
14
+ // participant's own for the selected session, or null (no ↑ list).
15
+ export function historyLoader(viewer, { fetchHistory, selected }) {
16
+ if (viewer.can("prompt_history")) return fetchHistory;
17
+ if (!viewer.can("own_prompt_history")) return null;
18
+ return () => {
19
+ const id = selected();
20
+ return id ? fetchOwnHistory(id) : Promise.resolve([]);
21
+ };
22
+ }
23
+
24
+ // Whether the delivery line's idle hint names ↑ history.
25
+ export function hasHistory(viewer) {
26
+ return viewer.can("prompt_history") || viewer.can("own_prompt_history");
27
+ }
@@ -24,8 +24,8 @@ import { clientLabel, isOwn } from "./turn_events.js";
24
24
  import { continueLine } from "./commands.js";
25
25
  import { plainText } from "./plain_line.js";
26
26
  import { noContactFill } from "./no_contact_fill.js";
27
- import { removeSession } from "./storage.js";
28
- import { CONTINUE_KEY, foldKey, questionKey } from "./stage_waiting.js";
27
+ import { CONTINUE_KEY, questionKey } from "./stage_waiting.js";
28
+ import { continueWait, questionText, questionWait } from "./card_kinds.js";
29
29
 
30
30
  // A card's text fields' name: not a contact field (no_contact_fill.js).
31
31
  const CARD_NOTE = "chi-card-note";
@@ -53,9 +53,12 @@ const CARD_NOTE = "chi-card-note";
53
53
  // bar's waiting chip, docs/internals/web-frontend.md write -> redraw)
54
54
  // @param answers false for a viewer who may not answer (viewer.js
55
55
  // answer_cards): no question or continue card is drawn at all
56
- // @param onSettled (key) a card stopped waiting (answered, cancelled,
56
+ // @param onArrive (key, info) a card that waits is about to be placed: its
57
+ // stage_waiting.js key and what it waits as (card_kinds.js)
58
+ // @param onSettled (key, opts) a card stopped waiting (answered, cancelled,
57
59
  // replaced or removed; the continue card resolved or dropped), by its
58
- // stage_waiting.js key: the stage's waiting cards as data
60
+ // stage_waiting.js key: the stage's waiting cards as data; {done: true}
61
+ // when answered, cancelled or resolved for good (its kept fold goes)
59
62
  // @return {renderQuestion(pq, {said}), resolveQuestion(id, opts), removeQuestion(),
60
63
  // questionCard() (the live card or null), pendingQuestion() (or null),
61
64
  // isResolved(id) (this page already saw that question answered),
@@ -64,7 +67,7 @@ export function createQuestionCards({
64
67
  sessionId, clientId, place, isNearBottom, scrollToEnd, removeHintIfEmpty, askingText = () => "",
65
68
  renderMarkdown = () => Promise.resolve(null), linkRefs = () => {}, pairRefs = () => {},
66
69
  api = { sendAnswer, dismissQuestion, sendCommand }, doc = globalThis.document,
67
- onPending = () => {}, onSettled = () => {}, answers = true,
70
+ onPending = () => {}, onArrive = () => {}, onSettled = () => {}, answers = true,
68
71
  }) {
69
72
  // Live ask_user_question card, keyed by pending question id. Re-rendered from
70
73
  // pending_question on session select so a reload mid-question restores it.
@@ -136,7 +139,7 @@ export function createQuestionCards({
136
139
  if (relay) card.appendChild(renderDelegateLine(relay));
137
140
  const q = doc.createElement("div");
138
141
  q.className = "question-text";
139
- q.textContent = (relay && pq.relay.asked) || pq.question || "";
142
+ q.textContent = questionText(pq);
140
143
  // A plugin's refs on the question (its step's: one may name a ticket here too).
141
144
  if (!relay) pairRefs(q, questionRefsOf(pq));
142
145
  card.appendChild(q);
@@ -182,6 +185,7 @@ export function createQuestionCards({
182
185
 
183
186
  if (stepLimit) {
184
187
  const follow = isNearBottom();
188
+ onArrive(questionKey(pq.id), questionWait(pq));
185
189
  place(card);
186
190
  questionEl = card;
187
191
  if (follow) scrollToEnd();
@@ -266,6 +270,7 @@ export function createQuestionCards({
266
270
 
267
271
  // Read before the card makes the history taller.
268
272
  const follow = isNearBottom();
273
+ onArrive(questionKey(pq.id), questionWait(pq));
269
274
  const staged = place(card) === true;
270
275
  questionEl = card;
271
276
  if (follow) scrollToEnd();
@@ -524,12 +529,9 @@ export function createQuestionCards({
524
529
  // After the collapse: a card left open by hand renders at once.
525
530
  if (full) renderSaidOnOpen(questionEl, full, asked, refs);
526
531
  resolvedId = pending.id;
527
- // Answered or cancelled for good: the fold this tab kept for it is gone
528
- // (stage_waiting.js). No session id, no key: foldKey(null) is null, and a
529
- // removeItem(null) would delete the key "null".
530
- const fold = foldKey(sessionId());
531
- if (fold) removeSession(fold);
532
- onSettled(questionKey(questionEl.dataset.qid));
532
+ // Answered or cancelled for good: the stage drops the fold this tab kept
533
+ // for it (stage_waiting.js settle).
534
+ onSettled(questionKey(questionEl.dataset.qid), { done: true });
533
535
  setPending(null);
534
536
  }
535
537
 
@@ -677,6 +679,7 @@ export function createQuestionCards({
677
679
  card.appendChild(row);
678
680
  card.appendChild(err);
679
681
  const follow = isNearBottom();
682
+ onArrive(CONTINUE_KEY, continueWait(offer));
680
683
  place(card);
681
684
  continueEl = card;
682
685
  if (follow) scrollToEnd();
@@ -687,9 +690,7 @@ export function createQuestionCards({
687
690
  continueEl = null;
688
691
  if (!card) return;
689
692
  card.classList.add("resolved");
690
- const fold = foldKey(sessionId());
691
- if (fold) removeSession(fold);
692
- onSettled(CONTINUE_KEY);
693
+ onSettled(CONTINUE_KEY, { done: true });
693
694
  card.querySelectorAll("button, input").forEach((el) => { el.disabled = true; });
694
695
  const note = doc.createElement("div");
695
696
  note.className = "question-result";
@@ -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
  }
@@ -88,8 +88,10 @@ export function createSessionSync(deps) {
88
88
  const same = store.selected === id;
89
89
  // Leaving for another session: the fold this tab kept for the one left
90
90
  // has no page to come back to (stage_waiting.js). A reselect of the same
91
- // session keeps it: the page is redrawn, not left.
92
- if (!same) removeSession(foldKey(store.selected));
91
+ // session keeps it: the page is redrawn, not left. No session open (the
92
+ // first select): no key, and a removeItem(null) would delete "null".
93
+ const leftFold = same ? null : foldKey(store.selected);
94
+ if (leftFold) removeSession(leftFold);
93
95
  // Its synchronous part in one batch: the active card, the composer and
94
96
  // the bar redraw once, at its end (never across the await).
95
97
  store.batch(() => {
@@ -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,7 +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
+ import { warnDiffers } from "./card_kinds.js";
12
13
 
13
14
  const COLLAPSE_KEY = "chi_stage_collapsed";
14
15
  // The cards that get a lead-in bubble when their step wrote text: chi's own
@@ -123,13 +124,11 @@ export function createStageAsking({
123
124
  opener.open(handOffOrder({ prompt: promptEl(), block: blockEl, extras: rows }), { follow });
124
125
  }
125
126
 
126
- // The waiting cards as data, checked against the slots (stage_waiting.js
127
- // reconcile, its second feed: it only settles): a card gone from the
128
- // extras and the tail, or no longer waiting, settles, also one answered
129
- // outside question_cards.js's hook.
130
- function reconcileWaiting() {
131
- waiting.reconcile((key) => !!waitingKind(cardIn(extras, key) || cardIn(tail, key)));
132
- }
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() {}
133
132
 
134
133
  // An opened turn's cards that stopped waiting go into the history: one
135
134
  // with a lead-in under it (also after the turn's end, so a card
@@ -158,9 +157,19 @@ export function createStageAsking({
158
157
 
159
158
  // The folded row's text for the docked +card+ (stage_model.js
160
159
  // foldedRowText): a question's text, an approval's summary and its
161
- // command's first line, a plugin card's title; "" for none.
160
+ // command's first line, a plugin card's title; "" for none. From the
161
+ // shown entry's data (stage_waiting.js summary), the card's own read the
162
+ // cross-check, and the fallback for an entry without one.
162
163
  function foldedText(card) {
163
164
  if (!card) return "";
165
+ const key = waitingKey(card);
166
+ const summary = waiting.get(key)?.summary;
167
+ const dom = foldedTextOf(card);
168
+ if (summary == null) return dom;
169
+ if (summary !== dom) warnDiffers("summary", key, summary, dom);
170
+ return summary;
171
+ }
172
+ function foldedTextOf(card) {
164
173
  if (card.matches(".plugin-card")) return card.querySelector(".card-title")?.textContent || "";
165
174
  if (card.dataset.kind !== "approval") return card.querySelector(".question-text")?.textContent || "";
166
175
  // The summary's own words, not its "↑ its reason" link.
@@ -213,10 +222,7 @@ export function createStageAsking({
213
222
  // ── the fold ─────────────────────────────────────────────────────────────
214
223
 
215
224
  // Whether the stage is collapsed now (stage_model.js stageCollapsed).
216
- // The registry is checked against the slots first: a card answered since
217
- // the last refresh no longer holds the fold.
218
225
  function isCollapsed() {
219
- reconcileWaiting();
220
226
  return stageCollapsed({ choice, revealed, asking: askingKey(), askingFold: waiting.folded() });
221
227
  }
222
228
 
@@ -252,7 +258,6 @@ export function createStageAsking({
252
258
  // asking form it folds that question only and writes nothing; else it is
253
259
  // the user's choice, kept.
254
260
  function setCollapsed(value) {
255
- reconcileWaiting();
256
261
  const asking = askingKey();
257
262
  if (asking) {
258
263
  waiting.fold(value ? asking : null);
@@ -0,0 +1,144 @@
1
+ // Where a row or a card goes while the stage holds a turn (stage_view.js's
2
+ // place, wired there): the stage's extras or its tail, its queued slot, the
3
+ // history's end of a turn opened there, or the history itself (false). A card
4
+ // that waits for the user docks: the turn opens in the history (stage_asking.js
5
+ // openTurn), its lead-in lands there in the card's task (stage_opened.js), the
6
+ // card waits in the stage (stage_waiting.js arrive). The step limit's card
7
+ // hands the turn off at once (stage_handoff.js). What a card waits as comes
8
+ // from its data (card_kinds.js, +expect+ right before its place); the node's
9
+ // own read (waitingKind) is the cross-check, and the fallback for a card
10
+ // that came without it (an older question_cards.js, a test's bare card).
11
+ import { placeFor, placeKind } from "./stage_model.js";
12
+ import { askingRefs } from "./turn_model.js";
13
+ import { ASKS, PENDING } from "./stage_cards.js";
14
+ import { isApprovalCard, isBlocking, waitingKey, waitingKind } from "./stage_waiting.js";
15
+ import { warnDiffers } from "./card_kinds.js";
16
+
17
+ // +historyEl+, +extras+, +tail+, +queuedSlot+: the history and the stage's
18
+ // slots; +ensureQueuedSlot()+ puts the queued slot back in the stage.
19
+ // +handoff+ (stage_handoff.js), +quiet+ (stage_quiet_clock.js), +view+ (the
20
+ // turn block), +opener+ (stage_opened.js), +waiting+ (stage_waiting.js) and
21
+ // +ask+ (stage_asking.js, whole: the docking, the lead-in, the opened row).
22
+ // +frame()+: the stage's frame (stage_frame.js); +refresh()+ and
23
+ // +scheduleRefresh()+ the stage's; +holding()+, +opened()+, +endKind()+ and
24
+ // +promptEl()+ the stage's turn; +historyNearBottom()+ the history's follow
25
+ // check.
26
+ export function createStagePlace({
27
+ historyEl, extras, tail, queuedSlot, ensureQueuedSlot, handoff, quiet, view, opener, waiting, ask, frame, refresh,
28
+ scheduleRefresh, holding, opened, endKind, promptEl, historyNearBottom,
29
+ }) {
30
+ // key → what the card about to be placed waits as ({kind, approval,
31
+ // summary}): taken by its place, whatever the outcome (a history card's
32
+ // too), cleared with the stage's slots (reset).
33
+ const expected = new Map();
34
+
35
+ // The card's wait: its data, else the node's read; the two checked
36
+ // against each other.
37
+ function waitOf(el, key) {
38
+ const data = key ? expected.get(key) : undefined;
39
+ if (key) expected.delete(key);
40
+ const dom = { kind: waitingKind(el), approval: isApprovalCard(el) };
41
+ if (!data) return { ...dom, summary: null };
42
+ if ((data.kind ?? null) !== dom.kind || !!data.approval !== dom.approval) warnDiffers("kind", key, data, dom);
43
+ return { kind: data.kind ?? null, approval: !!data.approval, summary: data.summary ?? null };
44
+ }
45
+
46
+ // The stage's extras while it holds a turn (a card, a prompt for its
47
+ // next step, a command, a note, the end line), its queued slot for a
48
+ // line queued for after it; false: the history takes it.
49
+ function place(el) {
50
+ // A turn still sliding away goes into the history first: what comes
51
+ // now comes after it.
52
+ handoff.settle();
53
+ const key = waitingKey(el);
54
+ const wait = waitOf(el, key);
55
+ const waits = !!(el.matches?.(PENDING) || el.querySelector?.(ASKS));
56
+ const kind = placeKind(el);
57
+ const isOpened = opened();
58
+ const ended = endKind();
59
+ const where = placeFor({ live: holding(), handingOff: false, kind, opened: isOpened && !ended });
60
+ // A late recap (idle-only, it describes the chat before this turn)
61
+ // goes above an opened turn, not inside it.
62
+ const above = kind === "recap" && isOpened ? [promptEl(), view.current().blockEl].find((x) => x?.parentElement === historyEl) : null;
63
+ if (above) {
64
+ historyEl.insertBefore(el, above);
65
+ return true;
66
+ }
67
+ if (where === "history") return false;
68
+ quiet.alive();
69
+ if (where === "queued") {
70
+ ensureQueuedSlot();
71
+ queuedSlot.appendChild(el);
72
+ scheduleRefresh();
73
+ return true;
74
+ }
75
+ // An opened turn's row: the history's end, in arrival order; a card
76
+ // that stopped waiting before it (a replay answers it and steers in
77
+ // one task, before the refresh) goes there first.
78
+ if (where === "opened") {
79
+ ask.settleCards();
80
+ opener.add(el);
81
+ scheduleRefresh();
82
+ return true;
83
+ }
84
+ // A card that waits for the user docks: the turn opens in the
85
+ // history, a lead-in lands there in this task, the card stays here.
86
+ const docked = ask.docks(el);
87
+ // A card drawn again with its key (the same question) keeps its lead-in.
88
+ const kept = docked && opener.has(key);
89
+ const reason = docked && !kept ? ask.leadInText(el) : "";
90
+ // Read before the turn's pieces make the history taller: with no
91
+ // lead-in to read, a reader at the end follows the turn's move.
92
+ const atEnd = docked ? historyNearBottom() : false;
93
+ if (docked) ask.openTurn({ follow: atEnd && !reason });
94
+ const slot = ended ? tail : extras;
95
+ const stick = slot.scrollHeight - slot.scrollTop - slot.clientHeight < 24;
96
+ // The stage's order (stage_waiting.js): a card that blocks goes before
97
+ // the asking ones, as a reload places them.
98
+ const behind = isBlocking(wait.kind) ? [...slot.children].find((x) => waiting.get(waitingKey(x))?.kind === "asks") : null;
99
+ slot.insertBefore(el, behind || null);
100
+ slot.hidden = false;
101
+ // The card is the stage's to keep (stage_waiting.js): docked when it
102
+ // waits for the user (its lead-in is the opener's, by the same key).
103
+ const waitKind = wait.kind;
104
+ if (waitKind) waiting.arrive(key, { kind: waitKind, docked, approval: wait.approval, summary: wait.summary });
105
+ if (stick || waits) slot.scrollTop = slot.scrollHeight;
106
+ if (kept) opener.relink(key, el);
107
+ if (reason) {
108
+ const { turn } = view.current();
109
+ opener.ask({
110
+ card: el, key, text: reason, refs: askingRefs(turn) || ask.askingGen(ask.asksOf(el))?.refs || null, step: turn?.gens.length || 0,
111
+ turnId: promptEl()?.dataset.turnId || null, questionId: el.dataset.qid ?? null, follow: atEnd,
112
+ });
113
+ }
114
+ // The step limit: its card goes under its ended turn in the
115
+ // conversation at once, as a reload draws it (the hand-off: its fold,
116
+ // the history's follow and the reload check as for any finished turn;
117
+ // the in-use watch and the end read don't hold it).
118
+ if (ended && waitKind === "continue") {
119
+ handoff.handOff();
120
+ return true;
121
+ }
122
+ // A waiting card and the asking form (refresh) land in one task.
123
+ if (waits) refresh();
124
+ else scheduleRefresh();
125
+ // The asking form: the stage shrinks to the card; an answer can also
126
+ // shrink it to a remaining card, or release it at the next step.
127
+ if (docked) frame().forgetContent();
128
+ if (waits && el.matches?.(".bubble.question")) ask.askedFor(el);
129
+ // A card that waits for the user is brought into the stage's view: in
130
+ // a short window the prompt and headline fill it and the card sat
131
+ // below, out of sight (once the stage has grown for it).
132
+ if (waits) frame().afterGrowth(() => frame().reveal(slot));
133
+ return true;
134
+ }
135
+
136
+ return {
137
+ place,
138
+ // +key+'s card is placed next; +info+: card_kinds.js's wait.
139
+ expect(key, info) {
140
+ if (key && info) expected.set(key, info);
141
+ },
142
+ reset: () => expected.clear(),
143
+ };
144
+ }