samagotchi 0.167.0 → 0.168.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.
@@ -10,7 +10,11 @@
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
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
14
18
  // slots are drawn by stage_slots.js, the cap and the held height are
15
19
  // stage_frame.js's, and the in-use watch that times the hand-off is
16
20
  // stage_watch.js's.
@@ -25,6 +29,11 @@ import { formatDuration } from "./timing.js";
25
29
  import { easeScrollTo } from "./scroll.js";
26
30
  import { readStored, writeStored } from "./storage.js";
27
31
  import { createWorkingSetRail } from "./working_set_rail.js";
32
+ import { moveToHistoryEnd } from "./history_end.js";
33
+ import { turnElements } from "./turn_range.js";
34
+ import { createOpenedTurn } from "./stage_opened.js";
35
+ import { askingRefs } from "./turn_model.js";
36
+ import { ASKS, PENDING, waitsInStage } from "./stage_cards.js";
28
37
  import { stampRows } from "./working_set_view.js";
29
38
 
30
39
  const COLLAPSE_KEY = "chi_stage_collapsed";
@@ -42,18 +51,15 @@ const ANSWER_CUT = 12;
42
51
  const ANSWERED_LINE = 40;
43
52
  // That line brought back sits this far under the scroller's edge.
44
53
  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
54
  // The model's own question (question_cards.js data-kind; not an approval,
51
55
  // 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.
56
+ // card whose asking text opens the turn in the history (stage_opened.js).
53
57
  const ASK_CARD = '.bubble.question[data-kind="question"]:not([data-relay])';
54
58
  // 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).
59
+ // view, it gets a raised cap (raiseForApproval).
56
60
  const APPROVAL_CARD = '.bubble.question[data-kind="approval"]';
61
+ // What opens a turn in the history (reload_check.js's OPENING).
62
+ const OPENING = "[data-turn-id], [data-opening-id]";
57
63
 
58
64
  function readCollapsed() {
59
65
  return readStored(COLLAPSE_KEY) === "1";
@@ -162,14 +168,6 @@ export function createStageView({
162
168
  chip.type = "button";
163
169
  const chipLabel = node("span", "ts-chip-label", chip);
164
170
  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
171
  // Below the turn's card: the lines queued for after it (placeKind
174
172
  // "queued"), each to run as a turn of its own; they hand off last.
175
173
  const queuedSlot = node("div", "ts-queued", stage);
@@ -203,27 +201,35 @@ export function createStageView({
203
201
  // so Stop turn stays in reach (runningWithoutTurn).
204
202
  let bare = false;
205
203
  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;
204
+ // The raised cap (stage_frame.js) of an approval too tall for the stage
205
+ // (raiseForApproval), kept until the next step (releaseHeldWait).
211
206
  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
207
  // The quiet signal's clocks: the turn's last event, since when the stream
223
208
  // isn't live (null: it is), the grace after the page shows again.
224
209
  let lastEventAt = 0;
225
210
  let downSince = null;
226
211
  let graceUntil = 0;
212
+ // Where the turn's prompt and block are: the stage (its prompt slot, the
213
+ // cloud or a plain turn's answer slot), or the history once the turn is
214
+ // opened there (+opened+). Read through blockPlace and promptEl, never
215
+ // the DOM parent alone.
216
+ let opened = false;
217
+ let promptEl = null;
218
+
219
+ // The stage says where its turn's block is (refs.js turnBlockOf: a row in
220
+ // the stage belongs to the block in the history then).
221
+ function setOpened(value) {
222
+ opened = value;
223
+ if (value) stage.dataset.block = "history";
224
+ else delete stage.dataset.block;
225
+ }
226
+
227
+ // The turn opened in the history while the model's own question waits
228
+ // (stage_opened.js): its reasons, and the moves there.
229
+ const opener = createOpenedTurn({
230
+ historyEl, atHistoryEnd: historyNearBottom, renderMarkdown, linkRefs, reduce: reducedMotion,
231
+ afterSettle: (fn) => frame.afterGrowth(fn),
232
+ });
227
233
 
228
234
  const view = createTurnBlock({
229
235
  historyEl,
@@ -252,6 +258,14 @@ export function createStageView({
252
258
 
253
259
  // ── slots ────────────────────────────────────────────────────────────────
254
260
 
261
+ // "history" (an opened turn's), "cloud", "answer" (a plain turn's in
262
+ // the stage), null: no block.
263
+ function blockPlace(blockEl = view.current().blockEl) {
264
+ if (!blockEl) return null;
265
+ if (opened) return "history";
266
+ return blockEl.parentNode === cloudBody ? "cloud" : "answer";
267
+ }
268
+
255
269
  function scheduleRefresh() {
256
270
  if (rafPending) return;
257
271
  rafPending = true;
@@ -262,60 +276,10 @@ export function createStageView({
262
276
  return !!(extras.querySelector(PENDING) || tail.querySelector(PENDING));
263
277
  }
264
278
 
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
- }
313
- }
314
-
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.
279
+ // A blocking approval too tall for the stage's view: a raised cap, the
280
+ // stage takes what the page has. The card still opens at its question and
281
+ // command (stage_frame.js revealTop). The cap is a ceiling: a card that
282
+ // fits never gets here.
319
283
  function raiseForApproval(blocked) {
320
284
  if (!blocked || roomCap) return;
321
285
  const card = extras.querySelector(PENDING) || tail.querySelector(PENDING);
@@ -324,18 +288,66 @@ export function createStageView({
324
288
  frame.fitCap();
325
289
  }
326
290
 
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);
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);
331
310
  }
332
311
 
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 });
312
+ // The reply that asked the question, "" for none.
313
+ function askedText() {
314
+ return String(askingGen()?.text || "").trim();
315
+ }
316
+
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();
323
+ }
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 }));
337
+ }
338
+
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
+ }
339
351
 
340
352
  function asksCard() {
341
353
  return !endKind && !!extras.querySelector(ASKS);
@@ -353,17 +365,24 @@ export function createStageView({
353
365
  // Plain once text streams without thinking or tools; until the first
354
366
  // chunk the live slots show (a slow first token leaves the height alone).
355
367
  const plain = !endKind && isPlain(turn) && !!gen?.text;
356
- if (blockEl && !endKind) {
368
+ // The stage hosts the block (an opened turn's is in the history).
369
+ if (blockEl && !endKind && !opened) {
357
370
  const host = plain ? answer : cloudBody;
358
371
  if (blockEl.parentNode !== host) host.appendChild(blockEl);
359
372
  }
373
+ const place = blockPlace(blockEl);
360
374
  // The turn block closes at the end; the cloud shows its steps.
361
- if (blockEl && blockEl.parentNode === cloudBody) blockEl.open = true;
375
+ if (place === "cloud") blockEl.open = true;
362
376
  const narration = gen?.text ? headlineOf(gen.text, gen.textDone || gen.closed) : "";
363
377
  const thinking = thinkingLine && thinkingLine.step === turn.gens.length ? thinkingLine.text : "";
364
378
  // A question blocks the turn: its card takes the live slots' room. An
365
379
  // asking card's turn goes on: the status waits, the slots stay.
380
+ settleCards();
366
381
  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));
385
+ stage.classList.toggle("asking-form", askingForm);
367
386
  const slots = liveSlots(turn, { narration, thinking, pending: blocked || asksCard(), blocked, ended: endKind, emptyAnswer });
368
387
 
369
388
  // The live slots keep their height while the turn waits and until its
@@ -385,10 +404,8 @@ export function createStageView({
385
404
  phaseEl.textContent = slots.phase;
386
405
 
387
406
  slotsView.drawHeadline(slots.headline);
388
- slotsView.drawAsking(slots.asking, slots.askingRefs);
389
- drawRoom(blocked, slots.asking);
407
+ slotsView.drawAsking(askingForm ? "" : slots.asking, slots.askingRefs);
390
408
  raiseForApproval(blocked);
391
- drawPill();
392
409
  slotsView.drawNow(slots.tool, slots.quiet);
393
410
  drawStall(clock(), blocked);
394
411
  slotsView.drawTrail(slots.trail, flash);
@@ -412,7 +429,8 @@ export function createStageView({
412
429
  // An ended turn's live slots go, unless something under them would move
413
430
  // (a card or a row in the extras): then they stay as they were last.
414
431
  live.hidden = plain || (!!endKind && !extras.firstChild);
415
- cloud.hidden = !blockEl || blockEl.parentNode !== cloudBody;
432
+ // The chip: a block in the cloud, or in the history (it reveals it there).
433
+ cloud.hidden = place !== "cloud" && place !== "history";
416
434
  cloudBody.hidden = !cloudOpen || cloud.hidden;
417
435
  // Running: the step it is on. Ended: the count, unless the chip says it.
418
436
  stepEl.textContent = stepSlotText({ step: slots.step, ended: !!endKind, chipHidden: cloud.hidden });
@@ -441,7 +459,7 @@ export function createStageView({
441
459
  // The prompt's first words (the working set's session tags say whose
442
460
  // turn a step was).
443
461
  function promptWords() {
444
- const text = (promptSlot.querySelector(".user-message")?.textContent || "").replace(/\s+/g, " ").trim();
462
+ const text = (promptEl?.querySelector(".user-message")?.textContent || "").replace(/\s+/g, " ").trim();
445
463
  return text.length > 60 ? `${text.slice(0, 59)}\u2026` : text;
446
464
  }
447
465
 
@@ -450,8 +468,11 @@ export function createStageView({
450
468
  // the wait held goes together: the live slots' waiting height, a raised
451
469
  // cap, the tallest content seen. +held-wait+ says it is due, so a later
452
470
  // step, or a generation with the card still waiting, changes nothing.
471
+ // A card still pending is read from the slots, not the waiting class: a
472
+ // replay (a reload, a resync) runs its answer and the next step in one
473
+ // task, before the refresh that drops the class.
453
474
  function releaseHeldWait() {
454
- if (!stage.classList.contains("held-wait") || stage.classList.contains("waiting")) return;
475
+ if (!stage.classList.contains("held-wait") || pendingCard()) return;
455
476
  stage.classList.remove("held-wait");
456
477
  stage.style.removeProperty("--live-held");
457
478
  roomCap = false;
@@ -547,6 +568,12 @@ export function createStageView({
547
568
  function openStep(i, { thinking = false } = {}) {
548
569
  const step = view.step(i);
549
570
  if (!step) return;
571
+ // An opened turn's step is in the history: shown there.
572
+ if (opened) {
573
+ if (!step.el.open) step.summary.click();
574
+ opener.reveal(step.el);
575
+ return;
576
+ }
550
577
  if (collapsed) setCollapsed(false);
551
578
  setCloud(true);
552
579
  if (!step.el.open) step.summary.click();
@@ -570,16 +597,11 @@ export function createStageView({
570
597
  chip.addEventListener("click", (e) => {
571
598
  const tick = e.target.closest(".ts-tick");
572
599
  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);
573
602
  else setCloud(!cloudOpen);
574
603
  });
575
604
  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
605
  // A ref's "show in turn" (refs.js) names a row in the cloud: open the
584
606
  // stage and the cloud to it, as a hand toggle would.
585
607
  // A collapsed stage opens for this turn only: the kept choice
@@ -627,6 +649,8 @@ export function createStageView({
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,8 @@ 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
+ setOpened(false);
687
+ promptEl = null;
662
688
  // The turn left the stage: the status row and the chip say nothing until
663
689
  // the next one. Kept as they were, a hidden stage still reads "thinking ·
664
690
  // step 1" — the stale stage of a turn the page stopped following.
@@ -676,14 +702,10 @@ export function createStageView({
676
702
  thinkingLine = null;
677
703
  flash = null;
678
704
  clearTimeout(flashTimer);
679
- if (roomCard) cardSight.unobserve(roomCard);
680
- roomCard = null;
681
705
  roomCap = false;
682
- measured = null;
683
- arrived = null;
684
- pill.hidden = true;
706
+ opener.reset();
685
707
  setCloud(false);
686
- stage.classList.remove("plain", "ended", "waiting", "held-wait", "asking", "in-use", "question-room");
708
+ stage.classList.remove("plain", "ended", "waiting", "held-wait", "asking", "in-use", "asking-form");
687
709
  stage.style.removeProperty("--live-held");
688
710
  }
689
711
 
@@ -737,13 +759,18 @@ export function createStageView({
737
759
  if (!holding || !endKind) return;
738
760
  const { blockEl } = view.current();
739
761
  view.chronological();
740
- const block = blockEl && blockEl.parentNode === cloudBody ? blockEl : null;
762
+ const place = blockPlace(blockEl);
763
+ // The block moves with the pieces from the cloud; an opened turn's is
764
+ // in the history already.
765
+ const block = place === "cloud" ? blockEl : null;
741
766
  // 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.
767
+ // keep their places); its footprint takes the block's summary line,
768
+ // wherever the block is.
743
769
  const footprint = workingSet ? workingSet.handOff(view.current().turn, promptWords()) : null;
744
- if (block && footprint) block.querySelector(":scope > summary > .tw-sum")?.prepend(footprint);
770
+ if ((place === "cloud" || place === "history") && footprint) blockEl.querySelector(":scope > summary > .tw-sum")?.prepend(footprint);
745
771
  const pieces = handOffOrder({
746
- prompt: promptSlot.firstElementChild,
772
+ // The prompt still in its slot (an opened turn's is in the history).
773
+ prompt: !opened && promptEl?.parentNode === promptSlot ? promptEl : null,
747
774
  block,
748
775
  extras: [...extras.children],
749
776
  answer: [...answer.children],
@@ -752,7 +779,7 @@ export function createStageView({
752
779
  queued: [...queuedSlot.children],
753
780
  });
754
781
  const animate = !immediate && !reducedMotion() && !document.hidden && !collapsed;
755
- folding = { pieces, block: blockEl, endKind, wasAtEnd: historyNearBottom(), animate, immediate };
782
+ folding = { pieces, block: blockEl, endKind, wasAtEnd: historyNearBottom(), animate, immediate, opened, prompt: promptEl };
756
783
  releaseTurn();
757
784
  if (!animate) return finishFold();
758
785
  stage.classList.add("leaving");
@@ -768,19 +795,34 @@ export function createStageView({
768
795
  // The stage held it open; here it takes its place in the history:
769
796
  // closed, unless the turn was cut short with an outline (block_open.js).
770
797
  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
- }
798
+ moveToHistoryEnd(historyEl, fold.pieces, { animate: fold.animate });
799
+ // An opened turn's reasons go in the pieces' task (after them: the
800
+ // history is as tall as it gets, room to keep the reader's rows in
801
+ // place): each answered card's clamp says it now, as the turn reloads.
802
+ opener.end();
779
803
  clearStage();
780
804
  if (fold.wasAtEnd) easeScrollTo(historyEl, () => historyEl.scrollHeight - historyEl.clientHeight, { reduce: !fold.animate || reducedMotion() });
781
805
  // 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 });
806
+ // reload_check.js), the whole turn from its opening: an opened turn's
807
+ // earlier pieces went before, and a wake's or a reminder's turn has no
808
+ // prompt (its note opens it); +immediate+: another turn took the stage.
809
+ onHandedOff?.({ pieces: wholeTurn(fold), immediate: fold.immediate });
810
+ }
811
+
812
+ // A handed-off turn from its opening: its prompt, else the wake's note
813
+ // (data-opening-id) right before its first piece; the pieces as they are
814
+ // when the first is its opening, or nothing opens it.
815
+ function wholeTurn(fold) {
816
+ const first = fold.pieces[0];
817
+ if (first?.matches?.(OPENING) && !fold.opened) return fold.pieces;
818
+ let opening = fold.prompt?.isConnected && fold.prompt.parentElement === historyEl ? fold.prompt : null;
819
+ for (let el = (fold.block || first)?.previousElementSibling; !opening && el; el = el.previousElementSibling) {
820
+ if (el.matches("[data-turn-id]")) break;
821
+ if (el.matches("[data-opening-id]")) opening = el;
822
+ }
823
+ if (!opening) return fold.pieces;
824
+ // Its rows, notes too (a note that reached the history mid-turn is the turn's).
825
+ return [opening, ...turnElements(opening, { container: historyEl, boundary: null })];
784
826
  }
785
827
 
786
828
  function dropBare() {
@@ -801,7 +843,12 @@ export function createStageView({
801
843
  const waiting = [...queuedSlot.children].filter((el) => el !== data?.promptBubble);
802
844
  if (holding) {
803
845
  if (endKind) handOff({ immediate: true });
804
- else release();
846
+ else {
847
+ // A turn that never ended (its end lost): its reasons, still
848
+ // "asking you", go; what it moved into the history stays.
849
+ opener.drop();
850
+ release();
851
+ }
805
852
  }
806
853
  holding = true;
807
854
  frame.resetHeld();
@@ -814,7 +861,8 @@ export function createStageView({
814
861
  lastEventAt = clock();
815
862
  // The turn's prompt bubble (app.js found or drew it) sits in the prompt
816
863
  // line until the hand-off takes it back first.
817
- if (data?.promptBubble) promptSlot.appendChild(data.promptBubble);
864
+ promptEl = data?.promptBubble || null;
865
+ if (promptEl) promptSlot.appendChild(promptEl);
818
866
  // The lines still queued behind this turn went into the history with
819
867
  // the turn before (the hand-off at this turn_started, or an earlier
820
868
  // one): back below this turn's card, as a reload places them.
@@ -896,7 +944,9 @@ export function createStageView({
896
944
  clearTimeout(settleTimer);
897
945
  },
898
946
  containsLive: (el) => view.containsLive(el),
899
- askingText: () => view.askingText(),
947
+ // The reply that asked (question_cards.js keeps it for the answered
948
+ // card's two lines), a replayed question's too.
949
+ askingText: () => askedText(),
900
950
  // The asking slot pairs them on its next draw.
901
951
  questionRefs(refs) {
902
952
  alive();
@@ -921,7 +971,16 @@ export function createStageView({
921
971
  // A turn still sliding away goes into the history first: what comes
922
972
  // now comes after it.
923
973
  if (folding) finishFold();
924
- const where = placeFor({ live: holding, handingOff: false, kind: placeKind(el) });
974
+ const waits = !!(el.matches?.(PENDING) || el.querySelector?.(ASKS));
975
+ const kind = placeKind(el);
976
+ const where = placeFor({ live: holding, handingOff: false, kind, opened: opened && !endKind });
977
+ // A late recap (idle-only, it describes the chat before this turn)
978
+ // goes above an opened turn, not inside it.
979
+ const above = kind === "recap" && opened ? [promptEl, view.current().blockEl].find((x) => x?.parentElement === historyEl) : null;
980
+ if (above) {
981
+ historyEl.insertBefore(el, above);
982
+ return true;
983
+ }
925
984
  if (where === "history") return false;
926
985
  alive();
927
986
  if (where === "queued") {
@@ -930,28 +989,41 @@ export function createStageView({
930
989
  scheduleRefresh();
931
990
  return true;
932
991
  }
992
+ // An opened turn's row: the history's end, in arrival order.
993
+ if (where === "opened") {
994
+ opener.add(el);
995
+ scheduleRefresh();
996
+ return true;
997
+ }
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();
933
1004
  const slot = endKind ? tail : extras;
934
1005
  const stick = slot.scrollHeight - slot.scrollTop - slot.clientHeight < 24;
935
1006
  slot.appendChild(el);
936
1007
  slot.hidden = false;
937
- const waits = el.matches?.(PENDING) || el.querySelector?.(ASKS);
938
1008
  if (stick || waits) slot.scrollTop = slot.scrollHeight;
1009
+ if (reason) {
1010
+ const { turn } = view.current();
1011
+ opener.ask({
1012
+ card: el, text: reason, refs: askingRefs(turn) || askingGen()?.refs || null, step: turn?.gens.length || 0,
1013
+ turnId: promptEl?.dataset.turnId || null, questionId: el.dataset.qid ?? null, follow: atEnd,
1014
+ });
1015
+ }
939
1016
  // A waiting card and the asking text (refresh) land in one task.
940
1017
  if (waits) refresh();
941
1018
  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();
942
1023
  // A card that waits for the user is brought into the stage's view: in
943
1024
  // 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
- }
1025
+ // below, out of sight (once the stage has grown for it).
1026
+ if (waits) frame.afterGrowth(() => frame.reveal(slot));
955
1027
  return true;
956
1028
  },
957
1029
  // Where the live timing line goes (the status row), null: the history.
@@ -11,8 +11,11 @@ const WATCH_MS = 200;
11
11
 
12
12
  // +watching()+: the stage still holds an ended turn (else a tick stops the
13
13
  // watch). +onTick({ inUse, quietSinceMs, nowMs })+ returns { due,
14
- // quietSinceMs }; +onDue()+ hands off.
15
- export function createInUseWatch({ stage, watching, onTick, onDue }) {
14
+ // quietSinceMs }; +onDue()+ hands off. +alsoWatched()+: elements outside
15
+ // the stage that count as it (a turn opened in the history: its reasons):
16
+ // the pointer over one (:hover, they don't change while it waits) or a
17
+ // selection in one.
18
+ export function createInUseWatch({ stage, watching, onTick, onDue, alsoWatched = () => [] }) {
16
19
  let watchTimer = null;
17
20
  let quietSince = null;
18
21
  let pointerIn = false;
@@ -33,14 +36,15 @@ export function createInUseWatch({ stage, watching, onTick, onDue }) {
33
36
  let active = document.activeElement;
34
37
  while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement;
35
38
  const sel = window.getSelection();
39
+ const also = alsoWatched();
36
40
  return inUseFrom({
37
- pointerIn,
41
+ pointerIn: pointerIn || also.some((el) => el.matches(":hover")),
38
42
  lastTouchMs: lastTouch,
39
43
  // A clicked button keeps the focus in Chrome: only keyboard focus and
40
44
  // a field being typed in count.
41
45
  focusInside: !!active && stage.contains(document.activeElement)
42
46
  && (/^(INPUT|TEXTAREA|SELECT)$/.test(active.tagName) || active.matches(":focus-visible")),
43
- selectionInside: !!sel && !sel.isCollapsed && stage.contains(sel.anchorNode),
47
+ selectionInside: !!sel && !sel.isCollapsed && [stage, ...also].some((el) => el.contains(sel.anchorNode)),
44
48
  nowMs,
45
49
  });
46
50
  }