samagotchi 0.168.0 → 0.170.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 (53) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +53 -1
  3. data/docs/architecture.md +1 -1
  4. data/docs/configuration.md +1 -1
  5. data/docs/guardrails.md +2 -2
  6. data/docs/hooks.md +2 -2
  7. data/docs/internals/block-renderers.md +1 -1
  8. data/docs/internals/bridge.md +19 -4
  9. data/docs/internals/inline-widgets.md +1 -1
  10. data/docs/internals/objectives.md +2 -1
  11. data/docs/internals/remote-sessions.md +1 -1
  12. data/docs/internals/web-frontend.md +72 -29
  13. data/docs/internals/working-set.md +2 -1
  14. data/docs/plugins.md +1 -1
  15. data/docs/releasing.md +13 -7
  16. data/docs/testing.md +22 -5
  17. data/lib/samagotchi/bridge.rb +25 -2
  18. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  19. data/lib/samagotchi/client_id.rb +3 -0
  20. data/lib/samagotchi/command_intake.rb +7 -7
  21. data/lib/samagotchi/compat.rb +14 -5
  22. data/lib/samagotchi/engine/events.rb +9 -0
  23. data/lib/samagotchi/engine/objectives.rb +10 -1
  24. data/lib/samagotchi/engine.rb +1 -1
  25. data/lib/samagotchi/event_fanout.rb +4 -7
  26. data/lib/samagotchi/guardrails/approvals.rb +8 -3
  27. data/lib/samagotchi/session_continue.rb +8 -11
  28. data/lib/samagotchi/session_manager/removal.rb +3 -3
  29. data/lib/samagotchi/session_stores.rb +79 -0
  30. data/lib/samagotchi/turn_stages/objectives.rb +6 -8
  31. data/lib/samagotchi/version.rb +1 -1
  32. data/lib/samagotchi/web/app.rb +17 -2
  33. data/lib/samagotchi/web/public/app.js +4 -1
  34. data/lib/samagotchi/web/public/block_watch.js +1 -1
  35. data/lib/samagotchi/web/public/cards_place.js +5 -1
  36. data/lib/samagotchi/web/public/index.html +67 -39
  37. data/lib/samagotchi/web/public/live_timing.js +5 -3
  38. data/lib/samagotchi/web/public/markdown_place.js +1 -1
  39. data/lib/samagotchi/web/public/question_cards.js +30 -7
  40. data/lib/samagotchi/web/public/stage_asking.js +283 -0
  41. data/lib/samagotchi/web/public/stage_frame.js +8 -12
  42. data/lib/samagotchi/web/public/stage_model.js +47 -14
  43. data/lib/samagotchi/web/public/stage_opened.js +33 -20
  44. data/lib/samagotchi/web/public/stage_slots.js +13 -89
  45. data/lib/samagotchi/web/public/stage_view.js +235 -170
  46. data/lib/samagotchi/web/public/stage_waiting.js +180 -0
  47. data/lib/samagotchi/web/public/stream_handlers.js +1 -1
  48. data/lib/samagotchi/web/public/turn_model.js +1 -1
  49. data/lib/samagotchi/web/session_control.rb +3 -1
  50. data/lib/samagotchi/web/session_hub.rb +16 -0
  51. data/lib/samagotchi/web/session_show.rb +14 -4
  52. data/lib/samagotchi/worker.rb +3 -4
  53. metadata +4 -1
@@ -10,33 +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. When the model's own question blocks the turn
14
- // after a reply, the turn opens in the history (stage_opened.js): the
15
- // reply becomes a conversation bubble, the prompt, the block and the rows
16
- // so far go there, and the stage shows its asking form (the card alone)
17
- // until the answer. The rules are pure in stage_model.js; the live
18
- // slots are drawn by stage_slots.js, the cap and the held height are
19
- // stage_frame.js's, and the in-use watch that times the hand-off is
20
- // 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.
21
24
  import { createTurnBlock } from "./turn_block.js";
22
25
  import { openAfterEnd } from "./block_open.js";
23
- 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";
24
27
  import { createStageSlots, node } from "./stage_slots.js";
25
28
  import { createStageFrame, reducedMotion } from "./stage_frame.js";
26
29
  import { createInUseWatch } from "./stage_watch.js";
27
30
  import { createStageStall, GRACE_MS, stallState } from "./stage_stall.js";
28
31
  import { formatDuration } from "./timing.js";
29
32
  import { easeScrollTo } from "./scroll.js";
30
- import { readStored, writeStored } from "./storage.js";
31
33
  import { createWorkingSetRail } from "./working_set_rail.js";
32
34
  import { moveToHistoryEnd } from "./history_end.js";
33
35
  import { turnElements } from "./turn_range.js";
34
36
  import { createOpenedTurn } from "./stage_opened.js";
35
37
  import { askingRefs } from "./turn_model.js";
36
- import { ASKS, PENDING, waitsInStage } from "./stage_cards.js";
38
+ import { ASKS, PENDING } from "./stage_cards.js";
39
+ import { createStageAsking } from "./stage_asking.js";
40
+ import { cardIn, createStageWaiting, isApprovalCard, isBlocking, waitingKey, waitingKind } from "./stage_waiting.js";
37
41
  import { stampRows } from "./working_set_view.js";
38
42
 
39
- const COLLAPSE_KEY = "chi_stage_collapsed";
40
43
  // The turn-end read (markdown, answer_display) settles within this, or the
41
44
  // hand-off stops waiting for it.
42
45
  const SETTLE_CAP_MS = 8000;
@@ -51,26 +54,15 @@ const ANSWER_CUT = 12;
51
54
  const ANSWERED_LINE = 40;
52
55
  // That line brought back sits this far under the scroller's edge.
53
56
  const ANSWERED_GAP = 8;
54
- // The model's own question (question_cards.js data-kind; not an approval,
55
- // the step limit, a hook's question or a delegate's relayed one): the one
56
- // card whose asking text opens the turn in the history (stage_opened.js).
57
- const ASK_CARD = '.bubble.question[data-kind="question"]:not([data-relay])';
58
- // A blocking approval, a delegate's relayed one too: too tall for the stage's
59
- // view, it gets a raised cap (raiseForApproval).
60
- const APPROVAL_CARD = '.bubble.question[data-kind="approval"]';
61
57
  // What opens a turn in the history (reload_check.js's OPENING).
62
58
  const OPENING = "[data-turn-id], [data-opening-id]";
63
59
 
64
- function readCollapsed() {
65
- return readStored(COLLAPSE_KEY) === "1";
66
- }
67
-
68
60
  // +historyNearBottom+: the history's own follow check (the hand-off scrolls
69
61
  // the history only for a reader at its end). +dockEl+ and +centerEl+ size
70
62
  // the stage's cap.
71
63
  // +taskStop+: the page's stopper (task_stop.js), for the stop-task button
72
- // on a running task_wait. +renderMarkdown+ and +linkRefs+: the asking
73
- // 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
74
66
  // page's working set (working_set_view.js, web.working_set; null: off): its
75
67
  // rail in the live slots, its footprint at the hand-off. +onCancel+: the
76
68
  // status row's Stop turn (a promise of the cancel request; the button is
@@ -99,6 +91,18 @@ export function createStageView({
99
91
  const status = node("div", "ts-status", stage);
100
92
  const mark = node("span", "ts-mark", status);
101
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");
102
106
  const stepEl = node("span", "ts-step", status);
103
107
  const timingSlot = node("span", "ts-timing", status);
104
108
  const miniTool = node("span", "ts-mini", status);
@@ -131,11 +135,6 @@ export function createStageView({
131
135
  headline.tabIndex = 0;
132
136
  headline.setAttribute("role", "button");
133
137
  headline.title = "Show this step's reasoning";
134
- // While a question or approval waits: the whole reply that asked it, in
135
- // the headline's place (the card says what to answer, this says why),
136
- // as markdown when web.markdown is on.
137
- const asking = node("div", "ts-asking", live);
138
- asking.hidden = true;
139
138
  const now = node("div", "ts-now", live);
140
139
  const trail = node("div", "ts-trail", live);
141
140
  // The working set's rail: out of the live slots' flow on their right (a
@@ -149,6 +148,11 @@ export function createStageView({
149
148
  workingSet.onServer(() => scheduleRefresh());
150
149
  }
151
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;
152
156
  const answer = node("div", "ts-answer", scroller);
153
157
  const tail = node("div", "ts-tail", scroller);
154
158
  // The cloud's steps, the scroller's last slot, right above the chip.
@@ -174,7 +178,7 @@ export function createStageView({
174
178
  // The quiet signal: its span in the now row, its head after the timing line.
175
179
  const stall = createStageStall({ stage, nowEl: now, timingSlot });
176
180
  const slotsView = createStageSlots({
177
- headline, asking, now, trail, ticks, taskStop, renderMarkdown, linkRefs,
181
+ headline, now, trail, ticks, taskStop,
178
182
  gens: () => view.current().turn?.gens,
179
183
  onChange: () => scheduleRefresh(),
180
184
  });
@@ -191,10 +195,7 @@ export function createStageView({
191
195
  let thinkingLine = null; // { step, text } from the live step's ticker
192
196
  let flash = null; // { kind, text, until } a notice or nudge in the trail
193
197
  let flashTimer = null; // its end's redraw
194
- let collapsed = readCollapsed();
195
198
  let cloudOpen = false;
196
- // A ref's "show in turn" opened a collapsed stage (not kept).
197
- let revealed = false;
198
199
  let rafPending = false;
199
200
  // A turn the page knows runs (the session says running) with none in the
200
201
  // stage to show (a join without its current_turn): the status row alone,
@@ -244,6 +245,7 @@ export function createStageView({
244
245
  blockHost: (el) => cloudBody.appendChild(el),
245
246
  placeAnswer: (pieces, { plain, blockEl }) => {
246
247
  if (plain) blockEl.remove();
248
+ drawAsksText("");
247
249
  answer.append(...pieces);
248
250
  showAnswerTop();
249
251
  },
@@ -256,6 +258,20 @@ export function createStageView({
256
258
  },
257
259
  });
258
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
+ let dockedAtLastRefresh = [];
265
+ // The asking form and the stage's fold (stage_asking.js).
266
+ const ask = createStageAsking({
267
+ stage, extras, tail, scroller, fold, view, opener, frame: () => frame, isOpened: () => opened, setOpened,
268
+ isEnded: () => !!endKind, promptEl: () => promptEl, setCloud, scheduleRefresh, pendingCard, waiting,
269
+ });
270
+ const {
271
+ askingGen, asksOf, askedFor, askedText, docks, leadInText, openTurn, settleCards, askingCard, cardOf, foldedText, markOwnToggles,
272
+ isCollapsed, drawCollapsed, applyCollapsed, setCollapsed,
273
+ } = ask;
274
+
259
275
  // ── slots ────────────────────────────────────────────────────────────────
260
276
 
261
277
  // "history" (an opened turn's), "cloud", "answer" (a plain turn's in
@@ -272,8 +288,12 @@ export function createStageView({
272
288
  requestAnimationFrame(refresh);
273
289
  }
274
290
 
291
+ // A card that blocks the turn waits (stage_waiting.js, checked against
292
+ // the slots first: a replay answers a card and starts the next step in one
293
+ // task, before the refresh).
275
294
  function pendingCard() {
276
- return !!(extras.querySelector(PENDING) || tail.querySelector(PENDING));
295
+ ask.reconcileWaiting();
296
+ return waiting.count() > 0;
277
297
  }
278
298
 
279
299
  // A blocking approval too tall for the stage's view: a raised cap, the
@@ -282,75 +302,64 @@ export function createStageView({
282
302
  // fits never gets here.
283
303
  function raiseForApproval(blocked) {
284
304
  if (!blocked || roomCap) return;
285
- const card = extras.querySelector(PENDING) || tail.querySelector(PENDING);
286
- if (!card?.matches(APPROVAL_CARD) || frame.fitsCap(card)) return;
305
+ const front = waiting.get(waiting.front());
306
+ const card = front?.approval ? cardOf(front.key) : null;
307
+ if (!card || frame.fitsCap(card)) return;
287
308
  roomCap = true;
288
309
  frame.fitCap();
289
310
  }
290
311
 
291
- // The step that asked the turn's question: live, the step whose call
292
- // runs (turn_model.js askingText); in a replay (a reload, a resync) the
293
- // asking call has already completed when its question_requested comes
294
- // (TurnAccumulator.join_events), so the last step when its last call is
295
- // ask_user_question and no card of this page took its reply yet (+asked+:
296
- // a later card, another kind's, never reuses it). null: none.
297
- function askingGen() {
298
- const { turn } = view.current();
299
- const gen = turn && !turn.ended ? turn.gens[turn.gens.length - 1] : null;
300
- if (!gen?.text) return null;
301
- if (view.askingText()) return gen;
302
- return gen.tools[gen.tools.length - 1]?.tool === "ask_user_question" && !asked.has(gen) ? gen : null;
303
- }
304
- // The steps whose reply a question card took (place: question_cards.js
305
- // reads askingText right before), for askingGen's replay rule.
306
- const asked = new WeakSet();
307
- function askedFor() {
308
- const gen = askingGen();
309
- if (gen) asked.add(gen);
312
+ // An asking card (check-in) waits while the turn runs.
313
+ function asksCard() {
314
+ return !endKind && waiting.count({ asks: true }) > waiting.count();
310
315
  }
311
316
 
312
- // The reply that asked the question, "" for none.
313
- function askedText() {
314
- return String(askingGen()?.text || "").trim();
317
+ // One docked card at a time: the others wait behind it (.ts-behind) and
318
+ // the pager says where the shown one is.
319
+ function drawDocked(shownCard) {
320
+ const keys = waiting.docked();
321
+ for (const key of keys) cardOf(key)?.classList.toggle("ts-behind", !!shownCard && cardOf(key) !== shownCard);
322
+ for (const el of extras.querySelectorAll(":scope > .ts-behind")) if (!keys.includes(waitingKey(el))) el.classList.remove("ts-behind");
323
+ // Focus in a card that went behind (a new card came in front of it):
324
+ // to the card that shows now.
325
+ const focused = document.activeElement;
326
+ if (shownCard && focused && [...extras.querySelectorAll(":scope > .ts-behind")].some((el) => el.contains(focused))) focusIn(shownCard);
327
+ const at = shownCard ? keys.indexOf(waitingKey(shownCard)) : -1;
328
+ pager.hidden = keys.length < 2 || at < 0;
329
+ if (pager.hidden) return;
330
+ const label = `${at + 1} of ${keys.length}`;
331
+ if (pageLabel.textContent !== label) pageLabel.textContent = label;
332
+ pagePrev.disabled = at === 0;
333
+ pageNext.disabled = at === keys.length - 1;
334
+ // A pager button the page just disabled keeps no focus: the other one has it.
335
+ if (document.activeElement === pagePrev && pagePrev.disabled) pageNext.focus();
336
+ else if (document.activeElement === pageNext && pageNext.disabled) pagePrev.focus();
315
337
  }
316
338
 
317
- // The reply that asked +el+ when +el+ is the model's own question and
318
- // there is one (the promotion rule: ASK_CARD, in the extras, a reply
319
- // before it); "" otherwise.
320
- function promotedText(el) {
321
- if (!el.matches?.(ASK_CARD) || !el.matches(PENDING)) return "";
322
- return askedText();
339
+ // +card+'s first control takes the focus (its summary is out of the tab
340
+ // order while it waits), else the card.
341
+ function focusIn(card) {
342
+ const control = card.querySelector('input:not([type="hidden"]), textarea, select, button:not([disabled]), a[href]');
343
+ if (control) control.focus();
344
+ else {
345
+ if (!card.hasAttribute("tabindex")) card.tabIndex = -1;
346
+ card.focus();
347
+ }
323
348
  }
324
-
325
- // The turn opens in the history (once): the prompt, the block (closed;
326
- // its steps in order from now on) and the rows the extras hold, in the
327
- // hand-off's order. What waits stays.
328
- function openTurn() {
329
- if (opened) return;
330
- const { blockEl } = view.current();
331
- view.inOrder?.();
332
- setCloud(false);
333
- if (blockEl) blockEl.open = false;
334
- const rows = [...extras.children].filter((el) => !waitsInStage(el));
335
- setOpened(true);
336
- opener.open(handOffOrder({ prompt: promptEl, block: blockEl, extras: rows }));
349
+ for (const [button, by] of [[pagePrev, -1], [pageNext, 1]]) {
350
+ button.addEventListener("click", (e) => {
351
+ e.stopPropagation();
352
+ waiting.page(by);
353
+ refresh();
354
+ const shown = askingCard();
355
+ if (shown) frame.afterGrowth(() => frame.reveal(shown.parentElement));
356
+ });
337
357
  }
338
358
 
339
- // An opened turn's cards that stopped waiting go into the history: a
340
- // promoted one under its reason (also after the turn's end, so a card
341
- // cancelled by Stop turn sits there), another one at the history's end
342
- // while the turn runs.
343
- function settleCards() {
344
- if (!opened) return;
345
- for (const el of [...extras.children]) {
346
- if (waitsInStage(el)) continue;
347
- if (opener.has(el)) opener.settle(el);
348
- else if (!endKind) opener.add(el);
349
- }
350
- }
351
-
352
- function asksCard() {
353
- return !endKind && !!extras.querySelector(ASKS);
359
+ // The text under a docked check-in card, patched only when it changes.
360
+ function drawAsksText(text) {
361
+ if (asksText.textContent !== text) asksText.textContent = text;
362
+ asksText.hidden = !text;
354
363
  }
355
364
  // A card answered or redrawn in place (its buttons gone) changes the
356
365
  // status without a turn event: at once (a microtask), so the slots swap in
@@ -377,18 +386,29 @@ export function createStageView({
377
386
  const thinking = thinkingLine && thinkingLine.step === turn.gens.length ? thinkingLine.text : "";
378
387
  // A question blocks the turn: its card takes the live slots' room. An
379
388
  // asking card's turn goes on: the status waits, the slots stay.
389
+ ask.reconcileWaiting();
380
390
  settleCards();
391
+ markOwnToggles();
381
392
  const blocked = pendingCard();
382
- // The asking form: a promoted card waits (the card alone in the stage;
383
- // its reply is the reason bubble in the history, not the asking slot).
384
- const askingForm = [...extras.querySelectorAll(PENDING)].some((el) => opener.has(el));
393
+ // The asking form: a docked card waits (the card alone in the stage;
394
+ // its turn is in the history, a reply before it the lead-in bubble).
395
+ const asking = askingCard();
396
+ const askingForm = !!asking;
385
397
  stage.classList.toggle("asking-form", askingForm);
386
- const slots = liveSlots(turn, { narration, thinking, pending: blocked || asksCard(), blocked, ended: endKind, emptyAnswer });
398
+ // Its fold (stage_asking.js trackFold): that card's only.
399
+ ask.trackFold();
400
+ drawDocked(asking);
401
+ const collapsed = isCollapsed();
402
+ drawCollapsed();
403
+ const slots = liveSlots(turn, { narration, thinking, pending: blocked || asksCard(), ended: endKind, emptyAnswer });
387
404
 
388
405
  // The live slots keep their height while the turn waits and until its
389
- // next step (held-wait, set with waiting): the card under them never
390
- // moves at the answer. The waiting height is measured before the swap.
406
+ // next step, unless answering leaves another docked card to fit. The
407
+ // waiting height is measured before the swap.
391
408
  const wasWaiting = stage.classList.contains("waiting");
409
+ const docked = waiting.docked();
410
+ const answeredWithCardLeft = dockedAtLastRefresh.some((key) => !docked.includes(key)) && docked.length > 0;
411
+ dockedAtLastRefresh = docked;
392
412
  if (blocked && !wasWaiting) {
393
413
  stage.classList.add("held-wait");
394
414
  }
@@ -398,13 +418,19 @@ export function createStageView({
398
418
  cancel.hidden = !onCancel || !!endKind;
399
419
  stage.classList.toggle("waiting", blocked);
400
420
  if (!blocked && wasWaiting) settleAnsweredCard();
401
- stage.classList.toggle("asking", !!slots.asking);
421
+ if (answeredWithCardLeft && !blocked) releaseHeldWait();
402
422
  stage.dataset.phase = slots.phase;
403
423
  mark.textContent = MARKS[slots.phase] || "";
404
- phaseEl.textContent = slots.phase;
424
+ // check-in docked, nothing blocking: the row says what chi does now (the
425
+ // running call, "writing" while text streams) and the text streams
426
+ // under the card.
427
+ const asksFront = !!asking && !blocked && !endKind && waiting.get(waiting.front())?.kind === "asks";
428
+ const streaming = asksFront ? liveSlots(turn).phase : "";
429
+ phaseEl.textContent = phaseLabel({ phase: slots.phase, asksFront, streaming });
430
+ stage.classList.toggle("asks-live", asksFront);
431
+ drawAsksText(asksFront && gen?.text && !gen.answer ? String(gen.text).trim() : "");
405
432
 
406
433
  slotsView.drawHeadline(slots.headline);
407
- slotsView.drawAsking(askingForm ? "" : slots.asking, slots.askingRefs);
408
434
  raiseForApproval(blocked);
409
435
  slotsView.drawNow(slots.tool, slots.quiet);
410
436
  drawStall(clock(), blocked);
@@ -422,15 +448,27 @@ export function createStageView({
422
448
  // that line is elsewhere (a turn the stage didn't hold from its start).
423
449
  const elapsed = endKind && !timingSlot.firstChild ? formatDuration(endedAt - startedAt) : "";
424
450
  chipLabel.textContent = chipLabelText({ steps: slots.step, calls, elapsed });
425
- const mini = miniToolText({ collapsed, tool: slots.tool });
426
- miniTool.textContent = mini.text;
451
+ // Folded, the row says what the docked card asks (live and after a
452
+ // reload alike: from the card), else the running call.
453
+ const mini = foldedRowText({ collapsed, question: foldedText(asking), tool: slots.tool, running: asksFront, now: clock() });
454
+ if (mini.clock) {
455
+ miniTool.replaceChildren();
456
+ node("span", "ts-mini-label", miniTool).textContent = mini.text;
457
+ node("span", "ts-mini-clock", miniTool).textContent = ` · ${mini.clock}`;
458
+ miniTool.classList.add("ts-mini-timed");
459
+ } else {
460
+ miniTool.classList.remove("ts-mini-timed");
461
+ miniTool.textContent = mini.text;
462
+ }
427
463
  miniTool.title = mini.title;
464
+ miniTool.classList.toggle("ts-mini-question", mini.question);
428
465
 
429
466
  // An ended turn's live slots go, unless something under them would move
430
467
  // (a card or a row in the extras): then they stay as they were last.
431
468
  live.hidden = plain || (!!endKind && !extras.firstChild);
432
- // The chip: a block in the cloud, or in the history (it reveals it there).
433
- cloud.hidden = place !== "cloud" && place !== "history";
469
+ // The chip: a block in the cloud. An opened turn's steps line in the
470
+ // history says the count: none here.
471
+ cloud.hidden = place !== "cloud";
434
472
  cloudBody.hidden = !cloudOpen || cloud.hidden;
435
473
  // Running: the step it is on. Ended: the count, unless the chip says it.
436
474
  stepEl.textContent = stepSlotText({ step: slots.step, ended: !!endKind, chipHidden: cloud.hidden });
@@ -463,11 +501,11 @@ export function createStageView({
463
501
  return text.length > 60 ? `${text.slice(0, 59)}\u2026` : text;
464
502
  }
465
503
 
466
- // The next step after a blocking card's answer: the one time a turn's
467
- // frame shrinks (stage_frame.js forgetContent; grow-only otherwise). What
468
- // the wait held goes together: the live slots' waiting height, a raised
469
- // cap, the tallest content seen. +held-wait+ says it is due, so a later
470
- // step, or a generation with the card still waiting, changes nothing.
504
+ // The next step after a blocking card's answer, or an answer that leaves
505
+ // another docked card in front: the frame shrinks (stage_frame.js
506
+ // forgetContent; grow-only otherwise). What the wait held goes together:
507
+ // the live slots' waiting height, a raised cap, the tallest content seen.
508
+ // +held-wait+ says it is due, so later steps change nothing.
471
509
  // A card still pending is read from the slots, not the waiting class: a
472
510
  // replay (a reload, a resync) runs its answer and the next step in one
473
511
  // task, before the refresh that drops the class.
@@ -529,25 +567,6 @@ export function createStageView({
529
567
 
530
568
  // ── collapse, cloud, peek ────────────────────────────────────────────────
531
569
 
532
- function applyCollapsed() {
533
- stage.classList.toggle("collapsed", collapsed);
534
- scroller.hidden = collapsed;
535
- fold.textContent = collapsed ? "▴" : "▾";
536
- fold.setAttribute("aria-label", collapsed ? "Expand the running turn" : "Collapse the running turn to its status");
537
- fold.setAttribute("aria-expanded", String(!collapsed));
538
- frame.fitCap();
539
- scheduleRefresh();
540
- }
541
-
542
- function setCollapsed(value) {
543
- collapsed = value;
544
- revealed = false;
545
- writeStored(COLLAPSE_KEY, value ? "1" : "0");
546
- applyCollapsed();
547
- // Opened on a waiting card: it shows as it does on arrival.
548
- if (!value && pendingCard()) frame.afterGrowth(() => frame.reveal(tail.querySelector(PENDING) ? tail : extras));
549
- }
550
-
551
570
  function setCloud(open) {
552
571
  cloudOpen = open;
553
572
  cloudBody.hidden = !open || cloud.hidden;
@@ -574,7 +593,7 @@ export function createStageView({
574
593
  opener.reveal(step.el);
575
594
  return;
576
595
  }
577
- if (collapsed) setCollapsed(false);
596
+ if (isCollapsed()) setCollapsed(false);
578
597
  setCloud(true);
579
598
  if (!step.el.open) step.summary.click();
580
599
  const wrap = step.thinkingWrap;
@@ -589,16 +608,14 @@ export function createStageView({
589
608
 
590
609
  fold.addEventListener("click", (e) => {
591
610
  e.stopPropagation();
592
- setCollapsed(!collapsed);
611
+ setCollapsed(!isCollapsed());
593
612
  });
594
613
  status.addEventListener("click", (e) => {
595
- if (collapsed && !e.target.closest("button, a")) setCollapsed(false);
614
+ if (isCollapsed() && !e.target.closest("button, a")) setCollapsed(false);
596
615
  });
597
616
  chip.addEventListener("click", (e) => {
598
617
  const tick = e.target.closest(".ts-tick");
599
618
  if (tick) openStep(Number(tick.dataset.step));
600
- // An opened turn's block is in the history: the chip shows it there.
601
- else if (opened) opener.reveal(view.current().blockEl);
602
619
  else setCloud(!cloudOpen);
603
620
  });
604
621
  headline.addEventListener("click", peek);
@@ -613,11 +630,7 @@ export function createStageView({
613
630
  if (!cloudBody.contains(e.target)) return;
614
631
  if (folding) return finishFold();
615
632
  if (!holding) return;
616
- if (collapsed) {
617
- collapsed = false;
618
- revealed = true;
619
- applyCollapsed();
620
- }
633
+ if (isCollapsed()) ask.reveal();
621
634
  setCloud(true);
622
635
  if (e.detail) e.detail.until = new Promise((resolve) => frame.afterGrowth(resolve));
623
636
  });
@@ -636,13 +649,13 @@ export function createStageView({
636
649
  // The cap and the frame (stage_frame.js): the stage's height, held while
637
650
  // it holds a turn, and its own scrolls.
638
651
  const frame = createStageFrame({
639
- stage, scroller, status, cloud, queuedSlot, holdEl, asking, extras, dockEl, centerEl,
640
- observed: [status, promptSlot, live, extras, answer, tail, cloudBody, cloud, queuedSlot],
652
+ stage, scroller, status, cloud, queuedSlot, holdEl, extras, dockEl, centerEl,
653
+ observed: [status, promptSlot, live, extras, asksText, answer, tail, cloudBody, cloud, queuedSlot],
641
654
  isHolding: () => holding,
642
- isCollapsed: () => collapsed,
655
+ isCollapsed,
643
656
  isCloudOpen: () => cloudOpen,
644
657
  isRoomCap: () => roomCap,
645
- waitingCard: () => (stage.classList.contains("waiting") ? extras.querySelector(PENDING) || tail.querySelector(PENDING) : null),
658
+ waitingCard: () => (stage.classList.contains("waiting") ? cardOf(waiting.front()) : null),
646
659
  });
647
660
 
648
661
  // The in-use watch (stage_watch.js): an ended turn hands off once the
@@ -683,6 +696,7 @@ export function createStageView({
683
696
 
684
697
  function emptySlots() {
685
698
  for (const slot of [promptSlot, extras, answer, tail, cloudBody, queuedSlot, timingSlot]) slot.replaceChildren();
699
+ drawAsksText("");
686
700
  setOpened(false);
687
701
  promptEl = null;
688
702
  // The turn left the stage: the status row and the chip say nothing until
@@ -703,9 +717,14 @@ export function createStageView({
703
717
  flash = null;
704
718
  clearTimeout(flashTimer);
705
719
  roomCap = false;
720
+ markOwnToggles();
706
721
  opener.reset();
722
+ waiting.reset();
723
+ dockedAtLastRefresh = [];
724
+ miniTool.classList.remove("ts-mini-question");
707
725
  setCloud(false);
708
- stage.classList.remove("plain", "ended", "waiting", "held-wait", "asking", "in-use", "asking-form");
726
+ stage.classList.remove("plain", "ended", "waiting", "held-wait", "in-use", "asking-form", "asks-live");
727
+ pager.hidden = true;
709
728
  stage.style.removeProperty("--live-held");
710
729
  }
711
730
 
@@ -731,11 +750,7 @@ export function createStageView({
731
750
  emptySlots();
732
751
  stage.hidden = true;
733
752
  frame.frameFree();
734
- if (revealed) {
735
- revealed = false;
736
- collapsed = readCollapsed();
737
- applyCollapsed();
738
- }
753
+ ask.unreveal();
739
754
  }
740
755
 
741
756
  function release() {
@@ -760,6 +775,8 @@ export function createStageView({
760
775
  const { blockEl } = view.current();
761
776
  view.chronological();
762
777
  const place = blockPlace(blockEl);
778
+ // A finished turn's block draws as a reload draws it.
779
+ if (blockEl) delete blockEl.dataset.openedTurn;
763
780
  // The block moves with the pieces from the cloud; an opened turn's is
764
781
  // in the history already.
765
782
  const block = place === "cloud" ? blockEl : null;
@@ -772,13 +789,13 @@ export function createStageView({
772
789
  // The prompt still in its slot (an opened turn's is in the history).
773
790
  prompt: !opened && promptEl?.parentNode === promptSlot ? promptEl : null,
774
791
  block,
775
- extras: [...extras.children],
792
+ extras: [...extras.children].map((el) => { el.classList.remove("ts-behind"); return el; }),
776
793
  answer: [...answer.children],
777
794
  timing: timingSlot.firstElementChild,
778
795
  kept: [...tail.children],
779
796
  queued: [...queuedSlot.children],
780
797
  });
781
- const animate = !immediate && !reducedMotion() && !document.hidden && !collapsed;
798
+ const animate = !immediate && !reducedMotion() && !document.hidden && !isCollapsed();
782
799
  folding = { pieces, block: blockEl, endKind, wasAtEnd: historyNearBottom(), animate, immediate, opened, prompt: promptEl };
783
800
  releaseTurn();
784
801
  if (!animate) return finishFold();
@@ -795,6 +812,9 @@ export function createStageView({
795
812
  // The stage held it open; here it takes its place in the history:
796
813
  // closed, unless the turn was cut short with an outline (block_open.js).
797
814
  if (fold.block) fold.block.open = openAfterEnd(fold.endKind, fold.block.classList.contains("outline"));
815
+ // A piece removed while it slid (the old continue card the step-limit
816
+ // question replaces) stays gone.
817
+ fold.pieces = fold.pieces.filter((el) => el.isConnected);
798
818
  moveToHistoryEnd(historyEl, fold.pieces, { animate: fold.animate });
799
819
  // An opened turn's reasons go in the pieces' task (after them: the
800
820
  // history is as tall as it gets, room to keep the reader's rows in
@@ -903,7 +923,10 @@ export function createStageView({
903
923
  // The warn cards the extras kept in sight leave the turn with the
904
924
  // block's (card.js leavesBlock): after the end line, as a reload has them.
905
925
  const warn = [...extras.querySelectorAll(":scope > .plugin-card.warn")];
906
- warn.forEach((el) => el.remove());
926
+ warn.forEach((el) => {
927
+ el.remove();
928
+ waiting.settle(waitingKey(el), { only: "warn" });
929
+ });
907
930
  kept.push(...warn);
908
931
  view.chronological();
909
932
  endKind = args.kind;
@@ -946,8 +969,8 @@ export function createStageView({
946
969
  containsLive: (el) => view.containsLive(el),
947
970
  // The reply that asked (question_cards.js keeps it for the answered
948
971
  // card's two lines), a replayed question's too.
949
- askingText: () => askedText(),
950
- // The asking slot pairs them on its next draw.
972
+ askingText: (pq) => askedText(pq),
973
+ // A lead-in bubble drawn after this pairs them (askingRefs).
951
974
  questionRefs(refs) {
952
975
  alive();
953
976
  view.questionRefs(refs);
@@ -956,7 +979,9 @@ export function createStageView({
956
979
  // The turn model and its live phase as the status row reads it (the
957
980
  // composer's delivery line).
958
981
  current: () => view.current(),
959
- phase: () => liveSlots(view.current().turn, { pending: pendingCard() || asksCard() }).phase,
982
+ // Only a card that blocks says "goes in once the card above is
983
+ // answered": check-in leaves the composer free.
984
+ phase: () => liveSlots(view.current().turn, { pending: pendingCard() }).phase,
960
985
  // Another session opens, or this one renders again: a turn still
961
986
  // sliding away is dropped (its history is about to be drawn anew),
962
987
  // never moved into whatever history shows now.
@@ -989,37 +1014,62 @@ export function createStageView({
989
1014
  scheduleRefresh();
990
1015
  return true;
991
1016
  }
992
- // An opened turn's row: the history's end, in arrival order.
1017
+ // An opened turn's row: the history's end, in arrival order; a card
1018
+ // that stopped waiting before it (a replay answers it and steers in
1019
+ // one task, before the refresh) goes there first.
993
1020
  if (where === "opened") {
1021
+ ask.reconcileWaiting();
1022
+ settleCards();
994
1023
  opener.add(el);
995
1024
  scheduleRefresh();
996
1025
  return true;
997
1026
  }
998
- // The model's own question after a reply: the turn opens in the
999
- // history, the reason lands there in this task, the card stays here.
1000
- const reason = waits && !endKind ? promotedText(el) : "";
1001
- // Read before the turn's pieces make the history taller.
1002
- const atEnd = reason ? historyNearBottom() : false;
1003
- if (reason) openTurn();
1027
+ // A card that waits for the user docks: the turn opens in the
1028
+ // history, a lead-in lands there in this task, the card stays here.
1029
+ const docked = docks(el);
1030
+ const key = waitingKey(el);
1031
+ // A card drawn again with its key (the same question) keeps its lead-in.
1032
+ const kept = docked && opener.has(key);
1033
+ const reason = docked && !kept ? leadInText(el) : "";
1034
+ // Read before the turn's pieces make the history taller: with no
1035
+ // lead-in to read, a reader at the end follows the turn's move.
1036
+ const atEnd = docked ? historyNearBottom() : false;
1037
+ if (docked) openTurn({ follow: atEnd && !reason });
1004
1038
  const slot = endKind ? tail : extras;
1005
1039
  const stick = slot.scrollHeight - slot.scrollTop - slot.clientHeight < 24;
1006
- slot.appendChild(el);
1040
+ // The stage's order (stage_waiting.js): a card that blocks goes before
1041
+ // the asking ones, as a reload places them.
1042
+ const behind = isBlocking(waitingKind(el)) ? [...slot.children].find((x) => waitingKind(x) === "asks") : null;
1043
+ slot.insertBefore(el, behind || null);
1007
1044
  slot.hidden = false;
1045
+ // The card is the stage's to keep (stage_waiting.js): docked when it
1046
+ // waits for the user (its lead-in is the opener's, by the same key).
1047
+ const waitKind = waitingKind(el);
1048
+ if (waitKind) waiting.arrive(key, { kind: waitKind, docked, approval: isApprovalCard(el) });
1008
1049
  if (stick || waits) slot.scrollTop = slot.scrollHeight;
1050
+ if (kept) opener.relink(key, el);
1009
1051
  if (reason) {
1010
1052
  const { turn } = view.current();
1011
1053
  opener.ask({
1012
- card: el, text: reason, refs: askingRefs(turn) || askingGen()?.refs || null, step: turn?.gens.length || 0,
1054
+ card: el, key, text: reason, refs: askingRefs(turn) || askingGen(asksOf(el))?.refs || null, step: turn?.gens.length || 0,
1013
1055
  turnId: promptEl?.dataset.turnId || null, questionId: el.dataset.qid ?? null, follow: atEnd,
1014
1056
  });
1015
1057
  }
1016
- // A waiting card and the asking text (refresh) land in one task.
1058
+ // The step limit: its card goes under its ended turn in the
1059
+ // conversation at once, as a reload draws it (the hand-off: its fold,
1060
+ // the history's follow and the reload check as for any finished turn;
1061
+ // the in-use watch and the end read don't hold it).
1062
+ if (endKind && waitKind === "continue") {
1063
+ handOff();
1064
+ return true;
1065
+ }
1066
+ // A waiting card and the asking form (refresh) land in one task.
1017
1067
  if (waits) refresh();
1018
1068
  else scheduleRefresh();
1019
- // The asking form: the stage shrinks to the card (one of its two
1020
- // allowed shrinks, stage_frame.js; the other is releaseHeldWait).
1021
- if (reason) frame.forgetContent();
1022
- if (waits && el.matches?.(".bubble.question")) askedFor();
1069
+ // The asking form: the stage shrinks to the card; an answer can also
1070
+ // shrink it to a remaining card, or release it at the next step.
1071
+ if (docked) frame.forgetContent();
1072
+ if (waits && el.matches?.(".bubble.question")) askedFor(el);
1023
1073
  // A card that waits for the user is brought into the stage's view: in
1024
1074
  // a short window the prompt and headline fill it and the card sat
1025
1075
  // below, out of sight (once the stage has grown for it).
@@ -1057,8 +1107,23 @@ export function createStageView({
1057
1107
  // quiet signal and the running call's clock.
1058
1108
  tick(nowMs = clock()) {
1059
1109
  drawStall(nowMs);
1110
+ if (holding && asksCard() && liveSlots(view.current().turn).tool?.startedAt != null) scheduleRefresh();
1060
1111
  },
1112
+ callClockActive: () => holding && asksCard() && !!liveSlots(view.current().turn).tool,
1061
1113
  handOff,
1114
+ // A card stopped waiting (stage_waiting.js keys; +only+: when it is that
1115
+ // kind): question_cards.js's resolve path, cards_place.js upsertCard.
1116
+ // The stage's redraw comes from the card's own change.
1117
+ settleWaiting: (key, opts) => {
1118
+ const settled = waiting.settle(key, opts);
1119
+ if (!settled || !opener.has(key)) return settled;
1120
+ const card = cardIn(extras, key) || cardIn(tail, key);
1121
+ card?.classList.remove("ts-behind");
1122
+ opener.settle(key, card);
1123
+ return true;
1124
+ },
1125
+ // The waiting cards as data (the tests' and the harness's read).
1126
+ waiting: { list: () => waiting.list(), front: () => waiting.front(), docked: () => waiting.docked(), folded: () => waiting.folded(), count: (o) => waiting.count(o) },
1062
1127
  root: stage,
1063
1128
  scrollEl: scroller,
1064
1129
  };