samagotchi 0.167.0 → 0.169.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 (54) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +64 -1
  3. data/docs/architecture.md +1 -1
  4. data/docs/cli.md +14 -10
  5. data/docs/configuration.md +1 -1
  6. data/docs/guardrails.md +2 -3
  7. data/docs/hooks.md +2 -2
  8. data/docs/internals/block-renderers.md +1 -1
  9. data/docs/internals/bridge.md +16 -4
  10. data/docs/internals/inline-widgets.md +1 -1
  11. data/docs/internals/objectives.md +2 -1
  12. data/docs/internals/remote-sessions.md +1 -1
  13. data/docs/internals/web-frontend.md +99 -19
  14. data/docs/plugins.md +1 -1
  15. data/docs/releasing.md +10 -6
  16. data/docs/testing.md +14 -3
  17. data/lib/samagotchi/bridge.rb +12 -2
  18. data/lib/samagotchi/bundle_command.rb +19 -4
  19. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  20. data/lib/samagotchi/client_id.rb +3 -0
  21. data/lib/samagotchi/command_intake.rb +7 -7
  22. data/lib/samagotchi/compat.rb +12 -7
  23. data/lib/samagotchi/engine/objectives.rb +10 -1
  24. data/lib/samagotchi/guardrails/approvals.rb +10 -29
  25. data/lib/samagotchi/session_continue.rb +8 -11
  26. data/lib/samagotchi/session_manager/removal.rb +3 -3
  27. data/lib/samagotchi/session_stores.rb +79 -0
  28. data/lib/samagotchi/turn_stages/objectives.rb +6 -8
  29. data/lib/samagotchi/version.rb +1 -1
  30. data/lib/samagotchi/web/public/app.js +3 -1
  31. data/lib/samagotchi/web/public/block_watch.js +1 -1
  32. data/lib/samagotchi/web/public/cards_place.js +5 -1
  33. data/lib/samagotchi/web/public/dock_reserve.js +12 -2
  34. data/lib/samagotchi/web/public/history_end.js +16 -0
  35. data/lib/samagotchi/web/public/index.html +89 -44
  36. data/lib/samagotchi/web/public/markdown_place.js +1 -1
  37. data/lib/samagotchi/web/public/question_cards.js +21 -7
  38. data/lib/samagotchi/web/public/refs.js +4 -1
  39. data/lib/samagotchi/web/public/reload_check.js +5 -4
  40. data/lib/samagotchi/web/public/stage_asking.js +283 -0
  41. data/lib/samagotchi/web/public/stage_cards.js +20 -0
  42. data/lib/samagotchi/web/public/stage_frame.js +17 -23
  43. data/lib/samagotchi/web/public/stage_model.js +48 -15
  44. data/lib/samagotchi/web/public/stage_opened.js +239 -0
  45. data/lib/samagotchi/web/public/stage_slots.js +13 -90
  46. data/lib/samagotchi/web/public/stage_view.js +339 -225
  47. data/lib/samagotchi/web/public/stage_waiting.js +180 -0
  48. data/lib/samagotchi/web/public/stage_watch.js +8 -4
  49. data/lib/samagotchi/web/public/stream_handlers.js +1 -1
  50. data/lib/samagotchi/web/public/turn_block.js +14 -2
  51. data/lib/samagotchi/web/public/turn_model.js +1 -1
  52. data/lib/samagotchi/web/session_show.rb +14 -4
  53. data/lib/samagotchi/worker.rb +3 -4
  54. metadata +7 -1
@@ -10,24 +10,36 @@
10
10
  // newest step first while the turn runs. When the turn has ended and the stage is not
11
11
  // in use, everything moves into the history in the turn block's order (the
12
12
  // hand-off), so a handed-off turn reads like its reload. Slots are patched in place, never rebuilt from HTML: a selection
13
- // and annotate survive. The rules are pure in stage_model.js; the live
14
- // slots are drawn by stage_slots.js, the cap and the held height are
15
- // stage_frame.js's, and the in-use watch that times the hand-off is
16
- // stage_watch.js's.
13
+ // and annotate survive. When a card waits for the user (a question, an
14
+ // approval, a delegate's relayed card, a hook's question, check-in), the
15
+ // turn opens in the history (stage_opened.js): the prompt, the block and the
16
+ // rows so far go there (chi's line before its own question or approval as a
17
+ // lead-in bubble), and the stage docks the card alone (the asking form)
18
+ // until the answer. The step limit's card goes under its ended turn. The
19
+ // rules are pure in stage_model.js; the live slots are drawn by
20
+ // stage_slots.js, the cap and the held height are stage_frame.js's, the
21
+ // in-use watch that times the hand-off is stage_watch.js's, the docked card
22
+ // and the fold are stage_asking.js's, and the waiting cards as data are
23
+ // stage_waiting.js's.
17
24
  import { createTurnBlock } from "./turn_block.js";
18
25
  import { openAfterEnd } from "./block_open.js";
19
- import { chipLabelText, flashOf, handOffDue, handOffOrder, headlineOf, isPlain, liveSlots, MARKS, miniToolText, placeFor, placeKind, QUEUED_CHILDREN, stepSlotText } from "./stage_model.js";
26
+ import { chipLabelText, flashOf, handOffDue, handOffOrder, headlineOf, isPlain, liveSlots, MARKS, foldedRowText, phaseLabel, placeFor, placeKind, QUEUED_CHILDREN, stepSlotText } from "./stage_model.js";
20
27
  import { createStageSlots, node } from "./stage_slots.js";
21
28
  import { createStageFrame, reducedMotion } from "./stage_frame.js";
22
29
  import { createInUseWatch } from "./stage_watch.js";
23
30
  import { createStageStall, GRACE_MS, stallState } from "./stage_stall.js";
24
31
  import { formatDuration } from "./timing.js";
25
32
  import { easeScrollTo } from "./scroll.js";
26
- import { readStored, writeStored } from "./storage.js";
27
33
  import { createWorkingSetRail } from "./working_set_rail.js";
34
+ import { moveToHistoryEnd } from "./history_end.js";
35
+ import { turnElements } from "./turn_range.js";
36
+ import { createOpenedTurn } from "./stage_opened.js";
37
+ import { askingRefs } from "./turn_model.js";
38
+ import { ASKS, PENDING } from "./stage_cards.js";
39
+ import { createStageAsking } from "./stage_asking.js";
40
+ import { createStageWaiting, isApprovalCard, isBlocking, waitingKey, waitingKind } from "./stage_waiting.js";
28
41
  import { stampRows } from "./working_set_view.js";
29
42
 
30
- const COLLAPSE_KEY = "chi_stage_collapsed";
31
43
  // The turn-end read (markdown, answer_display) settles within this, or the
32
44
  // hand-off stops waiting for it.
33
45
  const SETTLE_CAP_MS = 8000;
@@ -42,29 +54,15 @@ const ANSWER_CUT = 12;
42
54
  const ANSWERED_LINE = 40;
43
55
  // That line brought back sits this far under the scroller's edge.
44
56
  const ANSWERED_GAP = 8;
45
- const PENDING = ".bubble.question:not(.answered):not(.cancelled), .bubble.continue:not(.resolved)";
46
- // A running turn's card with actions (check-in's Nudge / Keep going / Stop)
47
- // asks the user too, but the turn goes on: it waits only while the turn runs
48
- // and never holds the hand-off (a turn cut short can leave it open).
49
- const ASKS = ".plugin-card[data-in-turn] .card-action";
50
- // The model's own question (question_cards.js data-kind; not an approval,
51
- // the step limit, a hook's question or a delegate's relayed one): the one
52
- // card whose long asking text gets the question room.
53
- const ASK_CARD = '.bubble.question[data-kind="question"]:not([data-relay])';
54
- // A blocking approval, a delegate's relayed one too: too tall for the stage's
55
- // view, it gets the question room's raised cap (raiseForApproval).
56
- const APPROVAL_CARD = '.bubble.question[data-kind="approval"]';
57
-
58
- function readCollapsed() {
59
- return readStored(COLLAPSE_KEY) === "1";
60
- }
57
+ // What opens a turn in the history (reload_check.js's OPENING).
58
+ const OPENING = "[data-turn-id], [data-opening-id]";
61
59
 
62
60
  // +historyNearBottom+: the history's own follow check (the hand-off scrolls
63
61
  // the history only for a reader at its end). +dockEl+ and +centerEl+ size
64
62
  // the stage's cap.
65
63
  // +taskStop+: the page's stopper (task_stop.js), for the stop-task button
66
- // on a running task_wait. +renderMarkdown+ and +linkRefs+: the asking
67
- // slot's markdown read and ref pass (stage_slots.js). +workingSet+: the
64
+ // on a running task_wait. +renderMarkdown+ and +linkRefs+: a lead-in
65
+ // bubble's markdown read and ref pass (stage_opened.js). +workingSet+: the
68
66
  // page's working set (working_set_view.js, web.working_set; null: off): its
69
67
  // rail in the live slots, its footprint at the hand-off. +onCancel+: the
70
68
  // status row's Stop turn (a promise of the cancel request; the button is
@@ -93,6 +91,18 @@ export function createStageView({
93
91
  const status = node("div", "ts-status", stage);
94
92
  const mark = node("span", "ts-mark", status);
95
93
  const phaseEl = node("span", "ts-phase", status);
94
+ // Two cards docked: one at a time, "‹ 1 of 2 ›" (stage_waiting.js shown).
95
+ const pager = node("span", "ts-pager", status);
96
+ pager.hidden = true;
97
+ const pagePrev = node("button", "ts-page", pager);
98
+ pagePrev.type = "button";
99
+ pagePrev.textContent = "‹";
100
+ pagePrev.setAttribute("aria-label", "The card before");
101
+ const pageLabel = node("span", "ts-page-label", pager);
102
+ const pageNext = node("button", "ts-page", pager);
103
+ pageNext.type = "button";
104
+ pageNext.textContent = "›";
105
+ pageNext.setAttribute("aria-label", "The next card");
96
106
  const stepEl = node("span", "ts-step", status);
97
107
  const timingSlot = node("span", "ts-timing", status);
98
108
  const miniTool = node("span", "ts-mini", status);
@@ -125,11 +135,6 @@ export function createStageView({
125
135
  headline.tabIndex = 0;
126
136
  headline.setAttribute("role", "button");
127
137
  headline.title = "Show this step's reasoning";
128
- // While a question or approval waits: the whole reply that asked it, in
129
- // the headline's place (the card says what to answer, this says why),
130
- // as markdown when web.markdown is on.
131
- const asking = node("div", "ts-asking", live);
132
- asking.hidden = true;
133
138
  const now = node("div", "ts-now", live);
134
139
  const trail = node("div", "ts-trail", live);
135
140
  // The working set's rail: out of the live slots' flow on their right (a
@@ -143,6 +148,11 @@ export function createStageView({
143
148
  workingSet.onServer(() => scheduleRefresh());
144
149
  }
145
150
  const extras = node("div", "ts-extras", scroller);
151
+ // While check-in's card is docked: the live step's text, streamed under
152
+ // the card (the steps are in the history then). The answer's own slot
153
+ // takes it over at the turn's end (placeAnswer, in one task).
154
+ const asksText = node("div", "ts-asks-text", scroller);
155
+ asksText.hidden = true;
146
156
  const answer = node("div", "ts-answer", scroller);
147
157
  const tail = node("div", "ts-tail", scroller);
148
158
  // The cloud's steps, the scroller's last slot, right above the chip.
@@ -162,21 +172,13 @@ export function createStageView({
162
172
  chip.type = "button";
163
173
  const chipLabel = node("span", "ts-chip-label", chip);
164
174
  const ticks = node("span", "ts-ticks", chip);
165
- // The question room's jump pill, at the scroller's bottom edge (absolute,
166
- // above the chip): while the room's card is out of the stage's view it
167
- // eases the stage to it (drawPill).
168
- const pill = node("button", "ts-room-pill", cloud);
169
- pill.type = "button";
170
- pill.setAttribute("aria-label", "Go to the question");
171
- pill.hidden = true;
172
- pill.textContent = "❓ Answer ↓";
173
175
  // Below the turn's card: the lines queued for after it (placeKind
174
176
  // "queued"), each to run as a turn of its own; they hand off last.
175
177
  const queuedSlot = node("div", "ts-queued", stage);
176
178
  // The quiet signal: its span in the now row, its head after the timing line.
177
179
  const stall = createStageStall({ stage, nowEl: now, timingSlot });
178
180
  const slotsView = createStageSlots({
179
- headline, asking, now, trail, ticks, taskStop, renderMarkdown, linkRefs,
181
+ headline, now, trail, ticks, taskStop,
180
182
  gens: () => view.current().turn?.gens,
181
183
  onChange: () => scheduleRefresh(),
182
184
  });
@@ -193,37 +195,42 @@ export function createStageView({
193
195
  let thinkingLine = null; // { step, text } from the live step's ticker
194
196
  let flash = null; // { kind, text, until } a notice or nudge in the trail
195
197
  let flashTimer = null; // its end's redraw
196
- let collapsed = readCollapsed();
197
198
  let cloudOpen = false;
198
- // A ref's "show in turn" opened a collapsed stage (not kept).
199
- let revealed = false;
200
199
  let rafPending = false;
201
200
  // A turn the page knows runs (the session says running) with none in the
202
201
  // stage to show (a join without its current_turn): the status row alone,
203
202
  // so Stop turn stays in reach (runningWithoutTurn).
204
203
  let bare = false;
205
204
  let foldTimer = null;
206
- // The question room (drawRoom): the pending ask card whose asking text
207
- // overflowed its cap; and the raised cap (stage_frame.js), which an
208
- // approval too tall for the stage gets too (raiseForApproval), kept until
209
- // the next step (releaseHeldWait).
210
- let roomCard = null;
205
+ // The raised cap (stage_frame.js) of an approval too tall for the stage
206
+ // (raiseForApproval), kept until the next step (releaseHeldWait).
211
207
  let roomCap = false;
212
- // What the overflow was measured for ({ card, text }): measured once the
213
- // asking text shows in its final form (its markdown, or the raw text when
214
- // there is none: the raw text is taller, and a short question's could
215
- // overflow where its markdown fits), again only for a new card or text,
216
- // never at a cap's change (a phone's keyboard).
217
- let measured = null;
218
- // The ask card whose arrival reveal has run (no pill while the stage
219
- // grows to it), and whether the room's card is in the stage's view.
220
- let arrived = null;
221
- let cardInSight = true;
222
208
  // The quiet signal's clocks: the turn's last event, since when the stream
223
209
  // isn't live (null: it is), the grace after the page shows again.
224
210
  let lastEventAt = 0;
225
211
  let downSince = null;
226
212
  let graceUntil = 0;
213
+ // Where the turn's prompt and block are: the stage (its prompt slot, the
214
+ // cloud or a plain turn's answer slot), or the history once the turn is
215
+ // opened there (+opened+). Read through blockPlace and promptEl, never
216
+ // the DOM parent alone.
217
+ let opened = false;
218
+ let promptEl = null;
219
+
220
+ // The stage says where its turn's block is (refs.js turnBlockOf: a row in
221
+ // the stage belongs to the block in the history then).
222
+ function setOpened(value) {
223
+ opened = value;
224
+ if (value) stage.dataset.block = "history";
225
+ else delete stage.dataset.block;
226
+ }
227
+
228
+ // The turn opened in the history while the model's own question waits
229
+ // (stage_opened.js): its reasons, and the moves there.
230
+ const opener = createOpenedTurn({
231
+ historyEl, atHistoryEnd: historyNearBottom, renderMarkdown, linkRefs, reduce: reducedMotion,
232
+ afterSettle: (fn) => frame.afterGrowth(fn),
233
+ });
227
234
 
228
235
  const view = createTurnBlock({
229
236
  historyEl,
@@ -238,6 +245,7 @@ export function createStageView({
238
245
  blockHost: (el) => cloudBody.appendChild(el),
239
246
  placeAnswer: (pieces, { plain, blockEl }) => {
240
247
  if (plain) blockEl.remove();
248
+ drawAsksText("");
241
249
  answer.append(...pieces);
242
250
  showAnswerTop();
243
251
  },
@@ -250,95 +258,107 @@ export function createStageView({
250
258
  },
251
259
  });
252
260
 
261
+ // The cards that wait in the stage, as data (stage_waiting.js): the
262
+ // docked card, its fold, what blocks, the approval's cap read them.
263
+ const waiting = createStageWaiting();
264
+ // The asking form and the stage's fold (stage_asking.js).
265
+ const ask = createStageAsking({
266
+ stage, extras, tail, scroller, fold, view, opener, frame: () => frame, isOpened: () => opened, setOpened,
267
+ isEnded: () => !!endKind, promptEl: () => promptEl, setCloud, scheduleRefresh, pendingCard, waiting,
268
+ });
269
+ const {
270
+ askingGen, asksOf, askedFor, askedText, docks, leadInText, openTurn, settleCards, askingCard, cardOf, foldedText, markOwnToggles,
271
+ isCollapsed, drawCollapsed, applyCollapsed, setCollapsed,
272
+ } = ask;
273
+
253
274
  // ── slots ────────────────────────────────────────────────────────────────
254
275
 
276
+ // "history" (an opened turn's), "cloud", "answer" (a plain turn's in
277
+ // the stage), null: no block.
278
+ function blockPlace(blockEl = view.current().blockEl) {
279
+ if (!blockEl) return null;
280
+ if (opened) return "history";
281
+ return blockEl.parentNode === cloudBody ? "cloud" : "answer";
282
+ }
283
+
255
284
  function scheduleRefresh() {
256
285
  if (rafPending) return;
257
286
  rafPending = true;
258
287
  requestAnimationFrame(refresh);
259
288
  }
260
289
 
290
+ // A card that blocks the turn waits (stage_waiting.js, checked against
291
+ // the slots first: a replay answers a card and starts the next step in one
292
+ // task, before the refresh).
261
293
  function pendingCard() {
262
- return !!(extras.querySelector(PENDING) || tail.querySelector(PENDING));
263
- }
264
-
265
- // The pending card in the extras when it is the model's own question
266
- // (never the tail's: a post-end card, the step limit; asking is empty then).
267
- function askCard() {
268
- const card = extras.querySelector(PENDING);
269
- return card?.matches(ASK_CARD) ? card : null;
270
- }
271
-
272
- // The asking text overflows its cap (+1 px of rounding), measured with
273
- // the room's class off.
274
- function askingOverflows() {
275
- return !asking.hidden && asking.scrollHeight > asking.clientHeight + 1;
276
- }
277
-
278
- // The question room: while a model's own question waits and its asking
279
- // text didn't fit its cap, the slot loses its cap and the stage's one
280
- // scroll reads the whole reply (index.html .question-room); the cap rises
281
- // until the next step. The card keeps the room until it stops pending
282
- // (+text+: the asking text drawn).
283
- function drawRoom(blocked, text) {
284
- const ask = blocked ? askCard() : null;
285
- if (roomCard && ask === roomCard) return;
286
- if (roomCard) {
287
- cardSight.unobserve(roomCard);
288
- stage.classList.remove("question-room");
289
- roomCard = null;
290
- }
291
- if (!ask || !slotsView.askingSettled() || (measured && measured.card === ask && measured.text === text)) return;
292
- measured = { card: ask, text };
293
- if (!askingOverflows()) return;
294
- roomCard = ask;
295
- stage.classList.add("question-room");
296
- cardInSight = true;
297
- cardSight.observe(roomCard);
298
- if (!roomCap) {
299
- roomCap = true;
300
- frame.fitCap();
301
- }
302
- // Decided after the card's arrival reveal (a slow markdown read): the
303
- // reply reads from its start now, the pill only after that.
304
- if (arrived === ask) {
305
- arrived = null;
306
- frame.afterGrowth(() => {
307
- if (roomCard !== ask) return;
308
- frame.reveal(extras, { fromStart: true });
309
- arrived = ask;
310
- drawPill();
311
- });
312
- }
294
+ ask.reconcileWaiting();
295
+ return waiting.count() > 0;
313
296
  }
314
297
 
315
- // A blocking approval too tall for the stage's view: the same raised cap,
316
- // the stage takes what the page has. The card still opens at its question
317
- // and command (stage_frame.js revealTop), so no room class and no pill. The
318
- // cap is a ceiling: a card that fits never gets here.
298
+ // A blocking approval too tall for the stage's view: a raised cap, the
299
+ // stage takes what the page has. The card still opens at its question and
300
+ // command (stage_frame.js revealTop). The cap is a ceiling: a card that
301
+ // fits never gets here.
319
302
  function raiseForApproval(blocked) {
320
303
  if (!blocked || roomCap) return;
321
- const card = extras.querySelector(PENDING) || tail.querySelector(PENDING);
322
- if (!card?.matches(APPROVAL_CARD) || frame.fitsCap(card)) return;
304
+ const front = waiting.get(waiting.front());
305
+ const card = front?.approval ? cardOf(front.key) : null;
306
+ if (!card || frame.fitsCap(card)) return;
323
307
  roomCap = true;
324
308
  frame.fitCap();
325
309
  }
326
310
 
327
- // The pill: the room's card out of the stage's view, once its arrival
328
- // reveal has run, the stage open.
329
- function drawPill() {
330
- pill.hidden = !(roomCard && !collapsed && arrived === roomCard && !cardInSight);
311
+ // An asking card (check-in) waits while the turn runs.
312
+ function asksCard() {
313
+ return !endKind && waiting.count({ asks: true }) > waiting.count();
331
314
  }
332
315
 
333
- // The room's card in the stage's view: ~40 px of it shows above the
334
- // scroller's bottom edge (where the pill sits).
335
- const cardSight = new IntersectionObserver((entries) => {
336
- for (const entry of entries) if (entry.target === roomCard) cardInSight = entry.isIntersecting;
337
- drawPill();
338
- }, { root: scroller, rootMargin: "0px 0px -40px 0px", threshold: 0 });
316
+ // One docked card at a time: the others wait behind it (.ts-behind) and
317
+ // the pager says where the shown one is.
318
+ function drawDocked(shownCard) {
319
+ const keys = waiting.docked();
320
+ for (const key of keys) cardOf(key)?.classList.toggle("ts-behind", !!shownCard && cardOf(key) !== shownCard);
321
+ for (const el of extras.querySelectorAll(":scope > .ts-behind")) if (!keys.includes(waitingKey(el))) el.classList.remove("ts-behind");
322
+ // Focus in a card that went behind (a new card came in front of it):
323
+ // to the card that shows now.
324
+ const focused = document.activeElement;
325
+ if (shownCard && focused && [...extras.querySelectorAll(":scope > .ts-behind")].some((el) => el.contains(focused))) focusIn(shownCard);
326
+ const at = shownCard ? keys.indexOf(waitingKey(shownCard)) : -1;
327
+ pager.hidden = keys.length < 2 || at < 0;
328
+ if (pager.hidden) return;
329
+ const label = `${at + 1} of ${keys.length}`;
330
+ if (pageLabel.textContent !== label) pageLabel.textContent = label;
331
+ pagePrev.disabled = at === 0;
332
+ pageNext.disabled = at === keys.length - 1;
333
+ // A pager button the page just disabled keeps no focus: the other one has it.
334
+ if (document.activeElement === pagePrev && pagePrev.disabled) pageNext.focus();
335
+ else if (document.activeElement === pageNext && pageNext.disabled) pagePrev.focus();
336
+ }
339
337
 
340
- function asksCard() {
341
- return !endKind && !!extras.querySelector(ASKS);
338
+ // +card+'s first control takes the focus (its summary is out of the tab
339
+ // order while it waits), else the card.
340
+ function focusIn(card) {
341
+ const control = card.querySelector('input:not([type="hidden"]), textarea, select, button:not([disabled]), a[href]');
342
+ if (control) control.focus();
343
+ else {
344
+ if (!card.hasAttribute("tabindex")) card.tabIndex = -1;
345
+ card.focus();
346
+ }
347
+ }
348
+ for (const [button, by] of [[pagePrev, -1], [pageNext, 1]]) {
349
+ button.addEventListener("click", (e) => {
350
+ e.stopPropagation();
351
+ waiting.page(by);
352
+ refresh();
353
+ const shown = askingCard();
354
+ if (shown) frame.afterGrowth(() => frame.reveal(shown.parentElement));
355
+ });
356
+ }
357
+
358
+ // The text under a docked check-in card, patched only when it changes.
359
+ function drawAsksText(text) {
360
+ if (asksText.textContent !== text) asksText.textContent = text;
361
+ asksText.hidden = !text;
342
362
  }
343
363
  // A card answered or redrawn in place (its buttons gone) changes the
344
364
  // status without a turn event: at once (a microtask), so the slots swap in
@@ -353,18 +373,33 @@ export function createStageView({
353
373
  // Plain once text streams without thinking or tools; until the first
354
374
  // chunk the live slots show (a slow first token leaves the height alone).
355
375
  const plain = !endKind && isPlain(turn) && !!gen?.text;
356
- if (blockEl && !endKind) {
376
+ // The stage hosts the block (an opened turn's is in the history).
377
+ if (blockEl && !endKind && !opened) {
357
378
  const host = plain ? answer : cloudBody;
358
379
  if (blockEl.parentNode !== host) host.appendChild(blockEl);
359
380
  }
381
+ const place = blockPlace(blockEl);
360
382
  // The turn block closes at the end; the cloud shows its steps.
361
- if (blockEl && blockEl.parentNode === cloudBody) blockEl.open = true;
383
+ if (place === "cloud") blockEl.open = true;
362
384
  const narration = gen?.text ? headlineOf(gen.text, gen.textDone || gen.closed) : "";
363
385
  const thinking = thinkingLine && thinkingLine.step === turn.gens.length ? thinkingLine.text : "";
364
386
  // A question blocks the turn: its card takes the live slots' room. An
365
387
  // asking card's turn goes on: the status waits, the slots stay.
388
+ ask.reconcileWaiting();
389
+ settleCards();
390
+ markOwnToggles();
366
391
  const blocked = pendingCard();
367
- const slots = liveSlots(turn, { narration, thinking, pending: blocked || asksCard(), blocked, ended: endKind, emptyAnswer });
392
+ // The asking form: a docked card waits (the card alone in the stage;
393
+ // its turn is in the history, a reply before it the lead-in bubble).
394
+ const asking = askingCard();
395
+ const askingForm = !!asking;
396
+ stage.classList.toggle("asking-form", askingForm);
397
+ // Its fold (stage_asking.js trackFold): that card's only.
398
+ ask.trackFold();
399
+ drawDocked(asking);
400
+ const collapsed = isCollapsed();
401
+ drawCollapsed();
402
+ const slots = liveSlots(turn, { narration, thinking, pending: blocked || asksCard(), ended: endKind, emptyAnswer });
368
403
 
369
404
  // The live slots keep their height while the turn waits and until its
370
405
  // next step (held-wait, set with waiting): the card under them never
@@ -379,16 +414,19 @@ export function createStageView({
379
414
  cancel.hidden = !onCancel || !!endKind;
380
415
  stage.classList.toggle("waiting", blocked);
381
416
  if (!blocked && wasWaiting) settleAnsweredCard();
382
- stage.classList.toggle("asking", !!slots.asking);
383
417
  stage.dataset.phase = slots.phase;
384
418
  mark.textContent = MARKS[slots.phase] || "";
385
- phaseEl.textContent = slots.phase;
419
+ // check-in docked, nothing blocking: the row says what chi does now (the
420
+ // running call, "writing" while text streams) and the text streams
421
+ // under the card.
422
+ const asksFront = !!asking && !blocked && !endKind && waiting.get(waiting.front())?.kind === "asks";
423
+ const streaming = asksFront ? liveSlots(turn).phase : "";
424
+ phaseEl.textContent = phaseLabel({ phase: slots.phase, asksFront, streaming });
425
+ stage.classList.toggle("asks-live", asksFront);
426
+ drawAsksText(asksFront && gen?.text && !gen.answer ? String(gen.text).trim() : "");
386
427
 
387
428
  slotsView.drawHeadline(slots.headline);
388
- slotsView.drawAsking(slots.asking, slots.askingRefs);
389
- drawRoom(blocked, slots.asking);
390
429
  raiseForApproval(blocked);
391
- drawPill();
392
430
  slotsView.drawNow(slots.tool, slots.quiet);
393
431
  drawStall(clock(), blocked);
394
432
  slotsView.drawTrail(slots.trail, flash);
@@ -405,14 +443,19 @@ export function createStageView({
405
443
  // that line is elsewhere (a turn the stage didn't hold from its start).
406
444
  const elapsed = endKind && !timingSlot.firstChild ? formatDuration(endedAt - startedAt) : "";
407
445
  chipLabel.textContent = chipLabelText({ steps: slots.step, calls, elapsed });
408
- const mini = miniToolText({ collapsed, tool: slots.tool });
446
+ // Folded, the row says what the docked card asks (live and after a
447
+ // reload alike: from the card), else the running call.
448
+ const mini = foldedRowText({ collapsed, question: foldedText(asking), tool: slots.tool, running: asksFront });
409
449
  miniTool.textContent = mini.text;
410
450
  miniTool.title = mini.title;
451
+ miniTool.classList.toggle("ts-mini-question", mini.question);
411
452
 
412
453
  // An ended turn's live slots go, unless something under them would move
413
454
  // (a card or a row in the extras): then they stay as they were last.
414
455
  live.hidden = plain || (!!endKind && !extras.firstChild);
415
- cloud.hidden = !blockEl || blockEl.parentNode !== cloudBody;
456
+ // The chip: a block in the cloud. An opened turn's steps line in the
457
+ // history says the count: none here.
458
+ cloud.hidden = place !== "cloud";
416
459
  cloudBody.hidden = !cloudOpen || cloud.hidden;
417
460
  // Running: the step it is on. Ended: the count, unless the chip says it.
418
461
  stepEl.textContent = stepSlotText({ step: slots.step, ended: !!endKind, chipHidden: cloud.hidden });
@@ -441,7 +484,7 @@ export function createStageView({
441
484
  // The prompt's first words (the working set's session tags say whose
442
485
  // turn a step was).
443
486
  function promptWords() {
444
- const text = (promptSlot.querySelector(".user-message")?.textContent || "").replace(/\s+/g, " ").trim();
487
+ const text = (promptEl?.querySelector(".user-message")?.textContent || "").replace(/\s+/g, " ").trim();
445
488
  return text.length > 60 ? `${text.slice(0, 59)}\u2026` : text;
446
489
  }
447
490
 
@@ -450,8 +493,11 @@ export function createStageView({
450
493
  // the wait held goes together: the live slots' waiting height, a raised
451
494
  // cap, the tallest content seen. +held-wait+ says it is due, so a later
452
495
  // step, or a generation with the card still waiting, changes nothing.
496
+ // A card still pending is read from the slots, not the waiting class: a
497
+ // replay (a reload, a resync) runs its answer and the next step in one
498
+ // task, before the refresh that drops the class.
453
499
  function releaseHeldWait() {
454
- if (!stage.classList.contains("held-wait") || stage.classList.contains("waiting")) return;
500
+ if (!stage.classList.contains("held-wait") || pendingCard()) return;
455
501
  stage.classList.remove("held-wait");
456
502
  stage.style.removeProperty("--live-held");
457
503
  roomCap = false;
@@ -508,25 +554,6 @@ export function createStageView({
508
554
 
509
555
  // ── collapse, cloud, peek ────────────────────────────────────────────────
510
556
 
511
- function applyCollapsed() {
512
- stage.classList.toggle("collapsed", collapsed);
513
- scroller.hidden = collapsed;
514
- fold.textContent = collapsed ? "▴" : "▾";
515
- fold.setAttribute("aria-label", collapsed ? "Expand the running turn" : "Collapse the running turn to its status");
516
- fold.setAttribute("aria-expanded", String(!collapsed));
517
- frame.fitCap();
518
- scheduleRefresh();
519
- }
520
-
521
- function setCollapsed(value) {
522
- collapsed = value;
523
- revealed = false;
524
- writeStored(COLLAPSE_KEY, value ? "1" : "0");
525
- applyCollapsed();
526
- // Opened on a waiting card: it shows as it does on arrival.
527
- if (!value && pendingCard()) frame.afterGrowth(() => frame.reveal(tail.querySelector(PENDING) ? tail : extras));
528
- }
529
-
530
557
  function setCloud(open) {
531
558
  cloudOpen = open;
532
559
  cloudBody.hidden = !open || cloud.hidden;
@@ -547,7 +574,13 @@ export function createStageView({
547
574
  function openStep(i, { thinking = false } = {}) {
548
575
  const step = view.step(i);
549
576
  if (!step) return;
550
- if (collapsed) setCollapsed(false);
577
+ // An opened turn's step is in the history: shown there.
578
+ if (opened) {
579
+ if (!step.el.open) step.summary.click();
580
+ opener.reveal(step.el);
581
+ return;
582
+ }
583
+ if (isCollapsed()) setCollapsed(false);
551
584
  setCloud(true);
552
585
  if (!step.el.open) step.summary.click();
553
586
  const wrap = step.thinkingWrap;
@@ -562,10 +595,10 @@ export function createStageView({
562
595
 
563
596
  fold.addEventListener("click", (e) => {
564
597
  e.stopPropagation();
565
- setCollapsed(!collapsed);
598
+ setCollapsed(!isCollapsed());
566
599
  });
567
600
  status.addEventListener("click", (e) => {
568
- if (collapsed && !e.target.closest("button, a")) setCollapsed(false);
601
+ if (isCollapsed() && !e.target.closest("button, a")) setCollapsed(false);
569
602
  });
570
603
  chip.addEventListener("click", (e) => {
571
604
  const tick = e.target.closest(".ts-tick");
@@ -573,13 +606,6 @@ export function createStageView({
573
606
  else setCloud(!cloudOpen);
574
607
  });
575
608
  headline.addEventListener("click", peek);
576
- // To the card: its end in sight (the arrival's rule), or back up to it
577
- // for a reader below it (the cloud open under the card).
578
- pill.addEventListener("click", () => {
579
- if (!roomCard) return;
580
- if (roomCard.offsetTop < scroller.scrollTop) frame.easeStage(Math.max(0, roomCard.offsetTop - 8));
581
- else frame.reveal(extras);
582
- });
583
609
  // A ref's "show in turn" (refs.js) names a row in the cloud: open the
584
610
  // stage and the cloud to it, as a hand toggle would.
585
611
  // A collapsed stage opens for this turn only: the kept choice
@@ -591,11 +617,7 @@ export function createStageView({
591
617
  if (!cloudBody.contains(e.target)) return;
592
618
  if (folding) return finishFold();
593
619
  if (!holding) return;
594
- if (collapsed) {
595
- collapsed = false;
596
- revealed = true;
597
- applyCollapsed();
598
- }
620
+ if (isCollapsed()) ask.reveal();
599
621
  setCloud(true);
600
622
  if (e.detail) e.detail.until = new Promise((resolve) => frame.afterGrowth(resolve));
601
623
  });
@@ -614,19 +636,21 @@ export function createStageView({
614
636
  // The cap and the frame (stage_frame.js): the stage's height, held while
615
637
  // it holds a turn, and its own scrolls.
616
638
  const frame = createStageFrame({
617
- stage, scroller, status, cloud, queuedSlot, holdEl, asking, extras, dockEl, centerEl,
618
- observed: [status, promptSlot, live, extras, answer, tail, cloudBody, cloud, queuedSlot],
639
+ stage, scroller, status, cloud, queuedSlot, holdEl, extras, dockEl, centerEl,
640
+ observed: [status, promptSlot, live, extras, asksText, answer, tail, cloudBody, cloud, queuedSlot],
619
641
  isHolding: () => holding,
620
- isCollapsed: () => collapsed,
642
+ isCollapsed,
621
643
  isCloudOpen: () => cloudOpen,
622
644
  isRoomCap: () => roomCap,
623
- waitingCard: () => (stage.classList.contains("waiting") ? extras.querySelector(PENDING) || tail.querySelector(PENDING) : null),
645
+ waitingCard: () => (stage.classList.contains("waiting") ? cardOf(waiting.front()) : null),
624
646
  });
625
647
 
626
648
  // The in-use watch (stage_watch.js): an ended turn hands off once the
627
649
  // stage has not been in use for a while and nothing is pending.
628
650
  const watch = createInUseWatch({
629
651
  stage,
652
+ // An opened turn's reasons in the history: read there, they hold it too.
653
+ alsoWatched: () => opener.watched(),
630
654
  watching: () => holding && !!endKind,
631
655
  onTick: ({ inUse, quietSinceMs, nowMs }) => handOffDue({ ended: true, pending: !settled || pendingCard(), inUse, quietSinceMs, nowMs }),
632
656
  onDue: () => handOff(),
@@ -659,6 +683,9 @@ export function createStageView({
659
683
 
660
684
  function emptySlots() {
661
685
  for (const slot of [promptSlot, extras, answer, tail, cloudBody, queuedSlot, timingSlot]) slot.replaceChildren();
686
+ drawAsksText("");
687
+ setOpened(false);
688
+ promptEl = null;
662
689
  // The turn left the stage: the status row and the chip say nothing until
663
690
  // the next one. Kept as they were, a hidden stage still reads "thinking ·
664
691
  // step 1" — the stale stage of a turn the page stopped following.
@@ -676,14 +703,14 @@ export function createStageView({
676
703
  thinkingLine = null;
677
704
  flash = null;
678
705
  clearTimeout(flashTimer);
679
- if (roomCard) cardSight.unobserve(roomCard);
680
- roomCard = null;
681
706
  roomCap = false;
682
- measured = null;
683
- arrived = null;
684
- pill.hidden = true;
707
+ markOwnToggles();
708
+ opener.reset();
709
+ waiting.reset();
710
+ miniTool.classList.remove("ts-mini-question");
685
711
  setCloud(false);
686
- stage.classList.remove("plain", "ended", "waiting", "held-wait", "asking", "in-use", "question-room");
712
+ stage.classList.remove("plain", "ended", "waiting", "held-wait", "in-use", "asking-form", "asks-live");
713
+ pager.hidden = true;
687
714
  stage.style.removeProperty("--live-held");
688
715
  }
689
716
 
@@ -709,11 +736,7 @@ export function createStageView({
709
736
  emptySlots();
710
737
  stage.hidden = true;
711
738
  frame.frameFree();
712
- if (revealed) {
713
- revealed = false;
714
- collapsed = readCollapsed();
715
- applyCollapsed();
716
- }
739
+ ask.unreveal();
717
740
  }
718
741
 
719
742
  function release() {
@@ -737,22 +760,29 @@ export function createStageView({
737
760
  if (!holding || !endKind) return;
738
761
  const { blockEl } = view.current();
739
762
  view.chronological();
740
- const block = blockEl && blockEl.parentNode === cloudBody ? blockEl : null;
763
+ const place = blockPlace(blockEl);
764
+ // A finished turn's block draws as a reload draws it.
765
+ if (blockEl) delete blockEl.dataset.openedTurn;
766
+ // The block moves with the pieces from the cloud; an opened turn's is
767
+ // in the history already.
768
+ const block = place === "cloud" ? blockEl : null;
741
769
  // The turn's set joins the page's turns (a plain one's too: the turns
742
- // keep their places); its footprint takes the block's summary line.
770
+ // keep their places); its footprint takes the block's summary line,
771
+ // wherever the block is.
743
772
  const footprint = workingSet ? workingSet.handOff(view.current().turn, promptWords()) : null;
744
- if (block && footprint) block.querySelector(":scope > summary > .tw-sum")?.prepend(footprint);
773
+ if ((place === "cloud" || place === "history") && footprint) blockEl.querySelector(":scope > summary > .tw-sum")?.prepend(footprint);
745
774
  const pieces = handOffOrder({
746
- prompt: promptSlot.firstElementChild,
775
+ // The prompt still in its slot (an opened turn's is in the history).
776
+ prompt: !opened && promptEl?.parentNode === promptSlot ? promptEl : null,
747
777
  block,
748
- extras: [...extras.children],
778
+ extras: [...extras.children].map((el) => { el.classList.remove("ts-behind"); return el; }),
749
779
  answer: [...answer.children],
750
780
  timing: timingSlot.firstElementChild,
751
781
  kept: [...tail.children],
752
782
  queued: [...queuedSlot.children],
753
783
  });
754
- const animate = !immediate && !reducedMotion() && !document.hidden && !collapsed;
755
- folding = { pieces, block: blockEl, endKind, wasAtEnd: historyNearBottom(), animate, immediate };
784
+ const animate = !immediate && !reducedMotion() && !document.hidden && !isCollapsed();
785
+ folding = { pieces, block: blockEl, endKind, wasAtEnd: historyNearBottom(), animate, immediate, opened, prompt: promptEl };
756
786
  releaseTurn();
757
787
  if (!animate) return finishFold();
758
788
  stage.classList.add("leaving");
@@ -768,19 +798,37 @@ export function createStageView({
768
798
  // The stage held it open; here it takes its place in the history:
769
799
  // closed, unless the turn was cut short with an outline (block_open.js).
770
800
  if (fold.block) fold.block.open = openAfterEnd(fold.endKind, fold.block.classList.contains("outline"));
771
- historyEl.querySelector(":scope > .hint")?.remove();
772
- for (const el of fold.pieces) {
773
- historyEl.appendChild(el);
774
- if (fold.animate) {
775
- el.classList.add("ts-arrive");
776
- el.addEventListener("animationend", () => el.classList.remove("ts-arrive"), { once: true });
777
- }
778
- }
801
+ // A piece removed while it slid (the old continue card the step-limit
802
+ // question replaces) stays gone.
803
+ fold.pieces = fold.pieces.filter((el) => el.isConnected);
804
+ moveToHistoryEnd(historyEl, fold.pieces, { animate: fold.animate });
805
+ // An opened turn's reasons go in the pieces' task (after them: the
806
+ // history is as tall as it gets, room to keep the reader's rows in
807
+ // place): each answered card's clamp says it now, as the turn reloads.
808
+ opener.end();
779
809
  clearStage();
780
810
  if (fold.wasAtEnd) easeScrollTo(historyEl, () => historyEl.scrollHeight - historyEl.clientHeight, { reduce: !fold.animate || reducedMotion() });
781
811
  // The turn's pieces are in the history now (the opt-in reload check,
782
- // reload_check.js); +immediate+: another turn took the stage.
783
- onHandedOff?.({ pieces: fold.pieces, immediate: fold.immediate });
812
+ // reload_check.js), the whole turn from its opening: an opened turn's
813
+ // earlier pieces went before, and a wake's or a reminder's turn has no
814
+ // prompt (its note opens it); +immediate+: another turn took the stage.
815
+ onHandedOff?.({ pieces: wholeTurn(fold), immediate: fold.immediate });
816
+ }
817
+
818
+ // A handed-off turn from its opening: its prompt, else the wake's note
819
+ // (data-opening-id) right before its first piece; the pieces as they are
820
+ // when the first is its opening, or nothing opens it.
821
+ function wholeTurn(fold) {
822
+ const first = fold.pieces[0];
823
+ if (first?.matches?.(OPENING) && !fold.opened) return fold.pieces;
824
+ let opening = fold.prompt?.isConnected && fold.prompt.parentElement === historyEl ? fold.prompt : null;
825
+ for (let el = (fold.block || first)?.previousElementSibling; !opening && el; el = el.previousElementSibling) {
826
+ if (el.matches("[data-turn-id]")) break;
827
+ if (el.matches("[data-opening-id]")) opening = el;
828
+ }
829
+ if (!opening) return fold.pieces;
830
+ // Its rows, notes too (a note that reached the history mid-turn is the turn's).
831
+ return [opening, ...turnElements(opening, { container: historyEl, boundary: null })];
784
832
  }
785
833
 
786
834
  function dropBare() {
@@ -801,7 +849,12 @@ export function createStageView({
801
849
  const waiting = [...queuedSlot.children].filter((el) => el !== data?.promptBubble);
802
850
  if (holding) {
803
851
  if (endKind) handOff({ immediate: true });
804
- else release();
852
+ else {
853
+ // A turn that never ended (its end lost): its reasons, still
854
+ // "asking you", go; what it moved into the history stays.
855
+ opener.drop();
856
+ release();
857
+ }
805
858
  }
806
859
  holding = true;
807
860
  frame.resetHeld();
@@ -814,7 +867,8 @@ export function createStageView({
814
867
  lastEventAt = clock();
815
868
  // The turn's prompt bubble (app.js found or drew it) sits in the prompt
816
869
  // line until the hand-off takes it back first.
817
- if (data?.promptBubble) promptSlot.appendChild(data.promptBubble);
870
+ promptEl = data?.promptBubble || null;
871
+ if (promptEl) promptSlot.appendChild(promptEl);
818
872
  // The lines still queued behind this turn went into the history with
819
873
  // the turn before (the hand-off at this turn_started, or an earlier
820
874
  // one): back below this turn's card, as a reload places them.
@@ -855,7 +909,10 @@ export function createStageView({
855
909
  // The warn cards the extras kept in sight leave the turn with the
856
910
  // block's (card.js leavesBlock): after the end line, as a reload has them.
857
911
  const warn = [...extras.querySelectorAll(":scope > .plugin-card.warn")];
858
- warn.forEach((el) => el.remove());
912
+ warn.forEach((el) => {
913
+ el.remove();
914
+ waiting.settle(waitingKey(el), { only: "warn" });
915
+ });
859
916
  kept.push(...warn);
860
917
  view.chronological();
861
918
  endKind = args.kind;
@@ -896,8 +953,10 @@ export function createStageView({
896
953
  clearTimeout(settleTimer);
897
954
  },
898
955
  containsLive: (el) => view.containsLive(el),
899
- askingText: () => view.askingText(),
900
- // The asking slot pairs them on its next draw.
956
+ // The reply that asked (question_cards.js keeps it for the answered
957
+ // card's two lines), a replayed question's too.
958
+ askingText: (pq) => askedText(pq),
959
+ // A lead-in bubble drawn after this pairs them (askingRefs).
901
960
  questionRefs(refs) {
902
961
  alive();
903
962
  view.questionRefs(refs);
@@ -906,7 +965,9 @@ export function createStageView({
906
965
  // The turn model and its live phase as the status row reads it (the
907
966
  // composer's delivery line).
908
967
  current: () => view.current(),
909
- phase: () => liveSlots(view.current().turn, { pending: pendingCard() || asksCard() }).phase,
968
+ // Only a card that blocks says "goes in once the card above is
969
+ // answered": check-in leaves the composer free.
970
+ phase: () => liveSlots(view.current().turn, { pending: pendingCard() }).phase,
910
971
  // Another session opens, or this one renders again: a turn still
911
972
  // sliding away is dropped (its history is about to be drawn anew),
912
973
  // never moved into whatever history shows now.
@@ -921,7 +982,16 @@ export function createStageView({
921
982
  // A turn still sliding away goes into the history first: what comes
922
983
  // now comes after it.
923
984
  if (folding) finishFold();
924
- const where = placeFor({ live: holding, handingOff: false, kind: placeKind(el) });
985
+ const waits = !!(el.matches?.(PENDING) || el.querySelector?.(ASKS));
986
+ const kind = placeKind(el);
987
+ const where = placeFor({ live: holding, handingOff: false, kind, opened: opened && !endKind });
988
+ // A late recap (idle-only, it describes the chat before this turn)
989
+ // goes above an opened turn, not inside it.
990
+ const above = kind === "recap" && opened ? [promptEl, view.current().blockEl].find((x) => x?.parentElement === historyEl) : null;
991
+ if (above) {
992
+ historyEl.insertBefore(el, above);
993
+ return true;
994
+ }
925
995
  if (where === "history") return false;
926
996
  alive();
927
997
  if (where === "queued") {
@@ -930,28 +1000,66 @@ export function createStageView({
930
1000
  scheduleRefresh();
931
1001
  return true;
932
1002
  }
1003
+ // An opened turn's row: the history's end, in arrival order; a card
1004
+ // that stopped waiting before it (a replay answers it and steers in
1005
+ // one task, before the refresh) goes there first.
1006
+ if (where === "opened") {
1007
+ ask.reconcileWaiting();
1008
+ settleCards();
1009
+ opener.add(el);
1010
+ scheduleRefresh();
1011
+ return true;
1012
+ }
1013
+ // A card that waits for the user docks: the turn opens in the
1014
+ // history, a lead-in lands there in this task, the card stays here.
1015
+ const docked = docks(el);
1016
+ const key = waitingKey(el);
1017
+ // A card drawn again with its key (the same question) keeps its lead-in.
1018
+ const kept = docked && opener.has(key);
1019
+ const reason = docked && !kept ? leadInText(el) : "";
1020
+ // Read before the turn's pieces make the history taller: with no
1021
+ // lead-in to read, a reader at the end follows the turn's move.
1022
+ const atEnd = docked ? historyNearBottom() : false;
1023
+ if (docked) openTurn({ follow: atEnd && !reason });
933
1024
  const slot = endKind ? tail : extras;
934
1025
  const stick = slot.scrollHeight - slot.scrollTop - slot.clientHeight < 24;
935
- slot.appendChild(el);
1026
+ // The stage's order (stage_waiting.js): a card that blocks goes before
1027
+ // the asking ones, as a reload places them.
1028
+ const behind = isBlocking(waitingKind(el)) ? [...slot.children].find((x) => waitingKind(x) === "asks") : null;
1029
+ slot.insertBefore(el, behind || null);
936
1030
  slot.hidden = false;
937
- const waits = el.matches?.(PENDING) || el.querySelector?.(ASKS);
1031
+ // The card is the stage's to keep (stage_waiting.js): docked when it
1032
+ // waits for the user (its lead-in is the opener's, by the same key).
1033
+ const waitKind = waitingKind(el);
1034
+ if (waitKind) waiting.arrive(key, { kind: waitKind, docked, approval: isApprovalCard(el) });
938
1035
  if (stick || waits) slot.scrollTop = slot.scrollHeight;
939
- // A waiting card and the asking text (refresh) land in one task.
1036
+ if (kept) opener.relink(key, el);
1037
+ if (reason) {
1038
+ const { turn } = view.current();
1039
+ opener.ask({
1040
+ card: el, key, text: reason, refs: askingRefs(turn) || askingGen(asksOf(el))?.refs || null, step: turn?.gens.length || 0,
1041
+ turnId: promptEl?.dataset.turnId || null, questionId: el.dataset.qid ?? null, follow: atEnd,
1042
+ });
1043
+ }
1044
+ // The step limit: its card goes under its ended turn in the
1045
+ // conversation at once, as a reload draws it (the hand-off: its fold,
1046
+ // the history's follow and the reload check as for any finished turn;
1047
+ // the in-use watch and the end read don't hold it).
1048
+ if (endKind && waitKind === "continue") {
1049
+ handOff();
1050
+ return true;
1051
+ }
1052
+ // A waiting card and the asking form (refresh) land in one task.
940
1053
  if (waits) refresh();
941
1054
  else scheduleRefresh();
1055
+ // The asking form: the stage shrinks to the card (one of its two
1056
+ // allowed shrinks, stage_frame.js; the other is releaseHeldWait).
1057
+ if (docked) frame.forgetContent();
1058
+ if (waits && el.matches?.(".bubble.question")) askedFor(el);
942
1059
  // A card that waits for the user is brought into the stage's view: in
943
1060
  // a short window the prompt and headline fill it and the card sat
944
- // below, out of sight (once the stage has grown for it). A question
945
- // with the room reads from the reply's start instead (its pill leads
946
- // to the card); its pill shows from here on.
947
- if (waits) {
948
- frame.afterGrowth(() => {
949
- const ask = askCard();
950
- frame.reveal(slot, { fromStart: !!ask && ask === roomCard });
951
- arrived = ask;
952
- drawPill();
953
- });
954
- }
1061
+ // below, out of sight (once the stage has grown for it).
1062
+ if (waits) frame.afterGrowth(() => frame.reveal(slot));
955
1063
  return true;
956
1064
  },
957
1065
  // Where the live timing line goes (the status row), null: the history.
@@ -987,6 +1095,12 @@ export function createStageView({
987
1095
  drawStall(nowMs);
988
1096
  },
989
1097
  handOff,
1098
+ // A card stopped waiting (stage_waiting.js keys; +only+: when it is that
1099
+ // kind): question_cards.js's resolve path, cards_place.js upsertCard.
1100
+ // The stage's redraw comes from the card's own change.
1101
+ settleWaiting: (key, opts) => waiting.settle(key, opts),
1102
+ // The waiting cards as data (the tests' and the harness's read).
1103
+ waiting: { list: () => waiting.list(), front: () => waiting.front(), docked: () => waiting.docked(), folded: () => waiting.folded(), count: (o) => waiting.count(o) },
990
1104
  root: stage,
991
1105
  scrollEl: scroller,
992
1106
  };